]> git.ipfire.org Git - thirdparty/wireguard-go.git/commitdiff
tun: avoid leaking sock fd in CreateTUN error cases
authorTobias Klauser <tklauser@distanz.ch>
Thu, 23 Sep 2021 10:05:13 +0000 (12:05 +0200)
committerJason A. Donenfeld <Jason@zx2c4.com>
Thu, 23 Sep 2021 15:53:49 +0000 (09:53 -0600)
At these points, the socket file descriptor is not yet wrapped in an
*os.File, so it needs to be closed explicitly on error.

Signed-off-by: Tobias Klauser <tklauser@distanz.ch>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
tun/tun_darwin.go
tun/tun_linux.go

index a703c8c34eac044ef483692dd52984aa585576f1..35d3085747ccd57959bc5a76d3255cf4bcc80d86 100644 (file)
@@ -108,7 +108,6 @@ func CreateTUN(name string, mtu int) (Device, error) {
        }
 
        fd, err := unix.Socket(unix.AF_SYSTEM, unix.SOCK_DGRAM, 2)
-
        if err != nil {
                return nil, err
        }
@@ -117,6 +116,7 @@ func CreateTUN(name string, mtu int) (Device, error) {
        copy(ctlInfo.Name[:], []byte(utunControlName))
        err = unix.IoctlCtlInfo(fd, ctlInfo)
        if err != nil {
+               unix.Close(fd)
                return nil, fmt.Errorf("IoctlGetCtlInfo: %w", err)
        }
 
@@ -127,11 +127,13 @@ func CreateTUN(name string, mtu int) (Device, error) {
 
        err = unix.Connect(fd, sc)
        if err != nil {
+               unix.Close(fd)
                return nil, err
        }
 
-       err = syscall.SetNonblock(fd, true)
+       err = unix.SetNonblock(fd, true)
        if err != nil {
+               unix.Close(fd)
                return nil, err
        }
        tun, err := CreateTUNFromFile(os.NewFile(uintptr(fd), ""), mtu)
index 466a805671c1b6b4b0164299380ef478bb55bcac..1cc84cba0ee5d2a37c2aa583057ceacd63794dfe 100644 (file)
@@ -419,6 +419,7 @@ func CreateTUN(name string, mtu int) (Device, error) {
        var flags uint16 = unix.IFF_TUN // | unix.IFF_NO_PI (disabled for TUN status hack)
        nameBytes := []byte(name)
        if len(nameBytes) >= unix.IFNAMSIZ {
+               unix.Close(nfd)
                return nil, fmt.Errorf("interface name too long: %w", unix.ENAMETOOLONG)
        }
        copy(ifr[:], nameBytes)
@@ -431,17 +432,19 @@ func CreateTUN(name string, mtu int) (Device, error) {
                uintptr(unsafe.Pointer(&ifr[0])),
        )
        if errno != 0 {
+               unix.Close(nfd)
                return nil, errno
        }
-       err = unix.SetNonblock(nfd, true)
-
-       // Note that the above -- open,ioctl,nonblock -- must happen prior to handing it to netpoll as below this line.
 
-       fd := os.NewFile(uintptr(nfd), cloneDevicePath)
+       err = unix.SetNonblock(nfd, true)
        if err != nil {
+               unix.Close(nfd)
                return nil, err
        }
 
+       // Note that the above -- open,ioctl,nonblock -- must happen prior to handing it to netpoll as below this line.
+
+       fd := os.NewFile(uintptr(nfd), cloneDevicePath)
        return CreateTUNFromFile(fd, mtu)
 }