conn, device, tun: set CLOEXEC on fds

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Brad Fitzpatrick
2022-07-01 21:28:52 -07:00
committed by Jason A. Donenfeld
parent 6a08d81f6b
commit c31a7b1ab4
6 changed files with 36 additions and 24 deletions

View File

@@ -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
}