From c31a7b1ab47807f01613a571cc480f79d5fb4181 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 1 Jul 2022 21:28:52 -0700 Subject: conn, device, tun: set CLOEXEC on fds Signed-off-by: Brad Fitzpatrick Signed-off-by: Jason A. Donenfeld --- tun/tun_darwin.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'tun/tun_darwin.go') diff --git a/tun/tun_darwin.go b/tun/tun_darwin.go index 94bbfa6..1ce8a46 100644 --- a/tun/tun_darwin.go +++ b/tun/tun_darwin.go @@ -107,7 +107,7 @@ func CreateTUN(name string, mtu int) (Device, error) { } } - fd, err := unix.Socket(unix.AF_SYSTEM, unix.SOCK_DGRAM, 2) + fd, err := socketCloexec(unix.AF_SYSTEM, unix.SOCK_DGRAM, 2) if err != nil { return nil, err } @@ -173,7 +173,7 @@ func CreateTUNFromFile(file *os.File, mtu int) (Device, error) { return nil, err } - tun.routeSocket, err = unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC) + tun.routeSocket, err = socketCloexec(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC) if err != nil { tun.tunFile.Close() return nil, err @@ -276,7 +276,7 @@ func (tun *NativeTun) Close() error { } func (tun *NativeTun) setMTU(n int) error { - fd, err := unix.Socket( + fd, err := socketCloexec( unix.AF_INET, unix.SOCK_DGRAM, 0, @@ -299,7 +299,7 @@ func (tun *NativeTun) setMTU(n int) error { } func (tun *NativeTun) MTU() (int, error) { - fd, err := unix.Socket( + fd, err := socketCloexec( unix.AF_INET, unix.SOCK_DGRAM, 0, @@ -317,3 +317,15 @@ func (tun *NativeTun) MTU() (int, error) { return int(ifr.MTU), nil } + +func socketCloexec(family, sotype, proto int) (fd int, err error) { + // See go/src/net/sys_cloexec.go for background. + syscall.ForkLock.RLock() + defer syscall.ForkLock.RUnlock() + + fd, err = unix.Socket(family, sotype, proto) + if err == nil { + unix.CloseOnExec(fd) + } + return +} -- cgit v1.2.3