Signed-off-by: leonnicolas <leonloechner@gmx.de>
This commit is contained in:
leonnicolas
2021-11-27 17:10:42 +01:00
parent 3320ae3f05
commit afe7273a91
219 changed files with 15781 additions and 12253 deletions

View File

@@ -1,14 +0,0 @@
module golang.zx2c4.com/wireguard/wgctrl
go 1.13
require (
github.com/google/go-cmp v0.5.5
github.com/mdlayher/genetlink v1.0.0
github.com/mdlayher/netlink v1.4.0
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721
golang.org/x/crypto v0.0.0-20210503195802-e9a32991a82e
golang.org/x/net v0.0.0-20210504132125-bbd867fde50d // indirect
golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6
golang.zx2c4.com/wireguard v0.0.0-20210427022245-097af6e1351b
)

View File

@@ -1,84 +0,0 @@
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/josharian/native v0.0.0-20200817173448-b6b71def0850 h1:uhL5Gw7BINiiPAo24A2sxkcDI0Jt/sqp1v5xQCniEFA=
github.com/josharian/native v0.0.0-20200817173448-b6b71def0850/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw=
github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ=
github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok=
github.com/jsimonetti/rtnetlink v0.0.0-20201216134343-bde56ed16391/go.mod h1:cR77jAZG3Y3bsb8hF6fHJbFoyFukLFOkQ98S0pQz3xw=
github.com/jsimonetti/rtnetlink v0.0.0-20201220180245-69540ac93943/go.mod h1:z4c53zj6Eex712ROyh8WI0ihysb5j2ROyV42iNogmAs=
github.com/jsimonetti/rtnetlink v0.0.0-20210122163228-8d122574c736/go.mod h1:ZXpIyOK59ZnN7J0BV99cZUPmsqDRZ3eq5X+st7u/oSA=
github.com/jsimonetti/rtnetlink v0.0.0-20210212075122-66c871082f2b h1:c3NTyLNozICy8B4mlMXemD3z/gXgQzVXZS/HqT+i3do=
github.com/jsimonetti/rtnetlink v0.0.0-20210212075122-66c871082f2b/go.mod h1:8w9Rh8m+aHZIG69YPGGem1i5VzoyRC8nw2kA8B+ik5U=
github.com/mdlayher/ethtool v0.0.0-20210210192532-2b88debcdd43 h1:WgyLFv10Ov49JAQI/ZLUkCZ7VJS3r74hwFIGXJsgZlY=
github.com/mdlayher/ethtool v0.0.0-20210210192532-2b88debcdd43/go.mod h1:+t7E0lkKfbBsebllff1xdTmyJt8lH37niI6kwFk9OTo=
github.com/mdlayher/genetlink v1.0.0 h1:OoHN1OdyEIkScEmRgxLEe2M9U8ClMytqA5niynLtfj0=
github.com/mdlayher/genetlink v1.0.0/go.mod h1:0rJ0h4itni50A86M2kHcgS85ttZazNt7a8H2a2cw0Gc=
github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA=
github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M=
github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY=
github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o=
github.com/mdlayher/netlink v1.2.0/go.mod h1:kwVW1io0AZy9A1E2YYgaD4Cj+C+GPkU6klXCMzIJ9p8=
github.com/mdlayher/netlink v1.2.1/go.mod h1:bacnNlfhqHqqLo4WsYeXSqfyXkInQ9JneWI68v1KwSU=
github.com/mdlayher/netlink v1.2.2-0.20210123213345-5cc92139ae3e/go.mod h1:bacnNlfhqHqqLo4WsYeXSqfyXkInQ9JneWI68v1KwSU=
github.com/mdlayher/netlink v1.3.0/go.mod h1:xK/BssKuwcRXHrtN04UBkwQ6dY9VviGGuriDdoPSWys=
github.com/mdlayher/netlink v1.4.0 h1:n3ARR+Fm0dDv37dj5wSWZXDKcy+U0zwcXS3zKMnSiT0=
github.com/mdlayher/netlink v1.4.0/go.mod h1:dRJi5IABcZpBD2A3D0Mv/AiX8I9uDEu5oGkAVrekmf8=
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721 h1:RlZweED6sbSArvlE924+mUcZuXKLBHA35U7LN621Bws=
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721/go.mod h1:Ickgr2WtCLZ2MDGd4Gr0geeCH5HybhRJbonOgQpvSxc=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210503195802-e9a32991a82e h1:8foAy0aoO5GkqCvAEJ4VC4P3zksTg4X4aJCDpZzmgQI=
golang.org/x/crypto v0.0.0-20210503195802-e9a32991a82e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201216054612-986b41b23924/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210504132125-bbd867fde50d h1:nTDGCTeAu2LhcsHTRzjyIUbZHCJ4QePArsm27Hka0UM=
golang.org/x/net v0.0.0-20210504132125-bbd867fde50d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201118182958-a01c418693c7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201218084310-7d0127a74742/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210123111255-9b0068b26619/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210309040221-94ec62e08169/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6 h1:cdsMqa2nXzqlgs183pHxtvoVwU7CyzaCTAUOg94af4c=
golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wireguard v0.0.0-20210427022245-097af6e1351b h1:XDLXhn7ryprJVo+Lpkiib6CIuXE2031GDwtfEm7vLjI=
golang.zx2c4.com/wireguard v0.0.0-20210427022245-097af6e1351b/go.mod h1:a057zjmoc00UN7gVkaJt2sXVK523kMJcogDTEvPIasg=

View File

@@ -1,4 +1,5 @@
//+build linux
//go:build linux
// +build linux
package wglinux

View File

@@ -1,4 +1,5 @@
//+build linux
//go:build linux
// +build linux
package wglinux

View File

@@ -1,4 +1,5 @@
//+build linux
//go:build linux
// +build linux
package wglinux

View File

@@ -1,4 +1,5 @@
//+build openbsd
//go:build openbsd
// +build openbsd
package wgopenbsd

View File

@@ -1,4 +1,5 @@
//+build openbsd,386
//go:build openbsd && 386
// +build openbsd,386
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go

View File

@@ -1,4 +1,5 @@
//+build openbsd,amd64
//go:build openbsd && amd64
// +build openbsd,amd64
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go

View File

@@ -1,4 +1,5 @@
//+build !windows
//go:build !windows
// +build !windows
package wguser

View File

@@ -1,17 +1,15 @@
//+build windows
//go:build windows
// +build windows
package wguser
import (
"errors"
"net"
"os"
"runtime"
"strings"
"unsafe"
"time"
"golang.org/x/sys/windows"
"golang.zx2c4.com/wireguard/ipc/winpipe"
"golang.zx2c4.com/wireguard/ipc/namedpipe"
)
// Expected prefixes when dealing with named pipes.
@@ -22,182 +20,14 @@ const (
// dial is the default implementation of Client.dial.
func dial(device string) (net.Conn, error) {
// Thanks to @zx2c4 for the sample code that makes this possible:
// https://github.com/WireGuard/wgctrl-go/issues/36#issuecomment-491912143.
//
// See also:
// https://docs.microsoft.com/en-us/windows/desktop/secauthz/impersonation-tokens
// https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-reverttoself
//
// All of these operations require a locked OS thread for the duration of
// this function. Once the pipe is opened successfully, RevertToSelf
// terminates the impersonation of a client application.
runtime.LockOSThread()
defer func() {
// Terminate the token impersonation operation. Per the Microsoft
// documentation, the process should shut down if RevertToSelf fails.
if err := windows.RevertToSelf(); err != nil {
panicf("wguser: failed to terminate token impersonation, panicking per Microsoft recommendation: %v", err)
}
runtime.UnlockOSThread()
}()
privileges := windows.Tokenprivileges{
PrivilegeCount: 1,
Privileges: [1]windows.LUIDAndAttributes{
{
Attributes: windows.SE_PRIVILEGE_ENABLED,
},
},
}
err := windows.LookupPrivilegeValue(
nil,
windows.StringToUTF16Ptr("SeDebugPrivilege"),
&privileges.Privileges[0].Luid,
)
if err != nil {
return nil, err
}
processes, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer windows.CloseHandle(processes)
e := windows.ProcessEntry32{
Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{})),
}
// Iterate the process list looking for any processes named winlogon.exe.
//
// It is possible for an attacker to attempt a denial of service of this
// application by creating bogus processes with that name, so we must
// attempt dialing a connection for each matching process until we either
// succeed or run out of processes to try.
//
// It is unlikely that an attacker's process could appear before the true
// winlogon.exe in this list, but better safe than sorry.
for err := windows.Process32First(processes, &e); ; err = windows.Process32Next(processes, &e) {
// Handle any errors from process list iteration.
switch err {
case nil:
// Keep iterating processes.
case windows.ERROR_NO_MORE_FILES:
// No more files to check.
return nil, errors.New("wguser: unable to find suitable winlogon.exe process to communicate with WireGuard")
default:
return nil, err
}
if strings.ToLower(windows.UTF16ToString(e.ExeFile[:])) != "winlogon.exe" {
continue
}
// Can we communicate with the device by impersonating this process?
c, err := tryDial(device, e.ProcessID, privileges)
switch {
case err == nil:
// Success, use this connection.
return c, nil
case os.IsPermission(err):
// We found a process named winlogon.exe that doesn't have permission
// to open a handle to the WireGuard device. Skip it and keep trying.
default:
return nil, err
}
}
}
// tryDial attempts to impersonate the security token of pid to dial device.
// tryDial _must_ only be invoked by dial.
func tryDial(device string, pid uint32, privileges windows.Tokenprivileges) (net.Conn, error) {
// Revert to normal thread state before attempting any further manipulation.
// See comment in dial about the panic.
if err := windows.RevertToSelf(); err != nil {
panicf("wguser: failed to terminate token impersonation, panicking per Microsoft recommendation: %v", err)
}
if err := windows.ImpersonateSelf(windows.SecurityImpersonation); err != nil {
return nil, err
}
thread, err := windows.GetCurrentThread()
if err != nil {
return nil, err
}
defer windows.CloseHandle(thread)
var ttok windows.Token
err = windows.OpenThreadToken(
thread,
windows.TOKEN_ADJUST_PRIVILEGES,
false,
&ttok,
)
if err != nil {
return nil, err
}
defer ttok.Close()
err = windows.AdjustTokenPrivileges(
ttok,
false,
&privileges,
uint32(unsafe.Sizeof(privileges)),
nil,
nil,
)
if err != nil {
return nil, err
}
proc, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid)
if err != nil {
return nil, err
}
defer windows.CloseHandle(proc)
var ptok windows.Token
err = windows.OpenProcessToken(
proc,
windows.TOKEN_IMPERSONATE|windows.TOKEN_DUPLICATE,
&ptok,
)
if err != nil {
return nil, err
}
defer ptok.Close()
var dup windows.Token
err = windows.DuplicateTokenEx(
ptok,
0,
nil,
windows.SecurityImpersonation,
windows.TokenImpersonation,
&dup,
)
if err != nil {
return nil, err
}
defer dup.Close()
if err := windows.SetThreadToken(nil, dup); err != nil {
return nil, err
}
localSystem, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
if err != nil {
return nil, err
}
pipeCfg := &winpipe.DialConfig{
return (&namedpipe.DialConfig{
ExpectedOwner: localSystem,
}
return winpipe.Dial(device, nil, pipeCfg)
}).DialTimeout(device, time.Duration(0))
}
// find is the default implementation of Client.find.

View File

@@ -0,0 +1,295 @@
package wgwindows
import (
"net"
"os"
"time"
"unsafe"
"golang.org/x/sys/windows"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgwindows/internal/ioctl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
var _ wginternal.Client = &Client{}
// A Client provides access to WireGuardNT ioctl information.
type Client struct {
cachedAdapters map[string]string
lastLenGuess uint32
}
var (
deviceClassNetGUID = windows.GUID{0x4d36e972, 0xe325, 0x11ce, [8]byte{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}}
deviceInterfaceNetGUID = windows.GUID{0xcac88484, 0x7515, 0x4c03, [8]byte{0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61}}
devpkeyWgName = windows.DEVPROPKEY{
FmtID: windows.DEVPROPGUID{0x65726957, 0x7547, 0x7261, [8]byte{0x64, 0x4e, 0x61, 0x6d, 0x65, 0x4b, 0x65, 0x79}},
PID: windows.DEVPROPID_FIRST_USABLE + 1,
}
)
var enumerator = `SWD\WireGuard`
func init() {
if maj, min, _ := windows.RtlGetNtVersionNumbers(); (maj == 6 && min <= 1) || maj < 6 {
enumerator = `ROOT\WIREGUARD`
}
}
func (c *Client) refreshInstanceIdCache() error {
cachedAdapters := make(map[string]string, 5)
devInfo, err := windows.SetupDiGetClassDevsEx(&deviceClassNetGUID, enumerator, 0, windows.DIGCF_PRESENT, 0, "")
if err != nil {
return err
}
defer windows.SetupDiDestroyDeviceInfoList(devInfo)
for i := 0; ; i++ {
devInfoData, err := windows.SetupDiEnumDeviceInfo(devInfo, i)
if err != nil {
if err == windows.ERROR_NO_MORE_ITEMS {
break
}
continue
}
prop, err := windows.SetupDiGetDeviceProperty(devInfo, devInfoData, &devpkeyWgName)
if err != nil {
continue
}
adapterName, ok := prop.(string)
if !ok {
continue
}
var status, problemCode uint32
ret := windows.CM_Get_DevNode_Status(&status, &problemCode, devInfoData.DevInst, 0)
if ret != windows.CR_SUCCESS || (status&windows.DN_DRIVER_LOADED|windows.DN_STARTED) != windows.DN_DRIVER_LOADED|windows.DN_STARTED {
continue
}
instanceId, err := windows.SetupDiGetDeviceInstanceId(devInfo, devInfoData)
if err != nil {
continue
}
cachedAdapters[adapterName] = instanceId
}
c.cachedAdapters = cachedAdapters
return nil
}
func (c *Client) interfaceHandle(name string) (windows.Handle, error) {
instanceId, ok := c.cachedAdapters[name]
if !ok {
err := c.refreshInstanceIdCache()
if err != nil {
return 0, err
}
instanceId, ok = c.cachedAdapters[name]
if !ok {
return 0, os.ErrNotExist
}
}
interfaces, err := windows.CM_Get_Device_Interface_List(instanceId, &deviceInterfaceNetGUID, windows.CM_GET_DEVICE_INTERFACE_LIST_PRESENT)
if err != nil {
return 0, err
}
interface16, err := windows.UTF16PtrFromString(interfaces[0])
if err != nil {
return 0, err
}
return windows.CreateFile(interface16, windows.GENERIC_READ|windows.GENERIC_WRITE, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, 0, 0)
}
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
err := c.refreshInstanceIdCache()
if err != nil {
return nil, err
}
ds := make([]*wgtypes.Device, 0, len(c.cachedAdapters))
for name := range c.cachedAdapters {
d, err := c.Device(name)
if err != nil {
return nil, err
}
ds = append(ds, d)
}
return ds, nil
}
// New creates a new Client
func New() *Client {
return &Client{}
}
// Close implements wginternal.Client.
func (c *Client) Close() error {
return nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
handle, err := c.interfaceHandle(name)
if err != nil {
return nil, err
}
defer windows.CloseHandle(handle)
size := c.lastLenGuess
if size == 0 {
size = 512
}
var buf []byte
for {
buf = make([]byte, size)
err = windows.DeviceIoControl(handle, ioctl.IoctlGet, nil, 0, &buf[0], size, &size, nil)
if err == windows.ERROR_MORE_DATA {
continue
}
if err != nil {
return nil, err
}
break
}
c.lastLenGuess = size
interfaze := (*ioctl.Interface)(unsafe.Pointer(&buf[0]))
device := wgtypes.Device{Type: wgtypes.WindowsKernel, Name: name}
if interfaze.Flags&ioctl.InterfaceHasPrivateKey != 0 {
device.PrivateKey = interfaze.PrivateKey
}
if interfaze.Flags&ioctl.InterfaceHasPublicKey != 0 {
device.PublicKey = interfaze.PublicKey
}
if interfaze.Flags&ioctl.InterfaceHasListenPort != 0 {
device.ListenPort = int(interfaze.ListenPort)
}
var p *ioctl.Peer
for i := uint32(0); i < interfaze.PeerCount; i++ {
if p == nil {
p = interfaze.FirstPeer()
} else {
p = p.NextPeer()
}
peer := wgtypes.Peer{}
if p.Flags&ioctl.PeerHasPublicKey != 0 {
peer.PublicKey = p.PublicKey
}
if p.Flags&ioctl.PeerHasPresharedKey != 0 {
peer.PresharedKey = p.PresharedKey
}
if p.Flags&ioctl.PeerHasEndpoint != 0 {
peer.Endpoint = &net.UDPAddr{IP: p.Endpoint.IP(), Port: int(p.Endpoint.Port())}
}
if p.Flags&ioctl.PeerHasPersistentKeepalive != 0 {
peer.PersistentKeepaliveInterval = time.Duration(p.PersistentKeepalive) * time.Second
}
if p.Flags&ioctl.PeerHasProtocolVersion != 0 {
peer.ProtocolVersion = int(p.ProtocolVersion)
}
peer.TransmitBytes = int64(p.TxBytes)
peer.ReceiveBytes = int64(p.RxBytes)
if p.LastHandshake != 0 {
peer.LastHandshakeTime = time.Unix(0, int64((p.LastHandshake-116444736000000000)*100))
}
var a *ioctl.AllowedIP
for j := uint32(0); j < p.AllowedIPsCount; j++ {
if a == nil {
a = p.FirstAllowedIP()
} else {
a = a.NextAllowedIP()
}
var ip net.IP
var bits int
if a.AddressFamily == windows.AF_INET {
ip = a.Address[:4]
bits = 32
} else if a.AddressFamily == windows.AF_INET6 {
ip = a.Address[:16]
bits = 128
}
peer.AllowedIPs = append(peer.AllowedIPs, net.IPNet{
IP: ip,
Mask: net.CIDRMask(int(a.Cidr), bits),
})
}
device.Peers = append(device.Peers, peer)
}
return &device, nil
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
handle, err := c.interfaceHandle(name)
if err != nil {
return err
}
defer windows.CloseHandle(handle)
preallocation := unsafe.Sizeof(ioctl.Interface{}) + uintptr(len(cfg.Peers))*unsafe.Sizeof(ioctl.Peer{})
for i := range cfg.Peers {
preallocation += uintptr(len(cfg.Peers[i].AllowedIPs)) * unsafe.Sizeof(ioctl.AllowedIP{})
}
var b ioctl.ConfigBuilder
b.Preallocate(uint32(preallocation))
interfaze := &ioctl.Interface{PeerCount: uint32(len(cfg.Peers))}
if cfg.ReplacePeers {
interfaze.Flags |= ioctl.InterfaceReplacePeers
}
if cfg.PrivateKey != nil {
interfaze.PrivateKey = *cfg.PrivateKey
interfaze.Flags |= ioctl.InterfaceHasPrivateKey
}
if cfg.ListenPort != nil {
interfaze.ListenPort = uint16(*cfg.ListenPort)
interfaze.Flags |= ioctl.InterfaceHasListenPort
}
b.AppendInterface(interfaze)
for i := range cfg.Peers {
peer := &ioctl.Peer{
Flags: ioctl.PeerHasPublicKey,
PublicKey: cfg.Peers[i].PublicKey,
AllowedIPsCount: uint32(len(cfg.Peers[i].AllowedIPs)),
}
if cfg.Peers[i].ReplaceAllowedIPs {
peer.Flags |= ioctl.PeerReplaceAllowedIPs
}
if cfg.Peers[i].UpdateOnly {
peer.Flags |= ioctl.PeerUpdateOnly
}
if cfg.Peers[i].Remove {
peer.Flags |= ioctl.PeerRemove
}
if cfg.Peers[i].PresharedKey != nil {
peer.Flags |= ioctl.PeerHasPresharedKey
peer.PresharedKey = *cfg.Peers[i].PresharedKey
}
if cfg.Peers[i].Endpoint != nil {
peer.Flags |= ioctl.PeerHasEndpoint
peer.Endpoint.SetIP(cfg.Peers[i].Endpoint.IP, uint16(cfg.Peers[i].Endpoint.Port))
}
if cfg.Peers[i].PersistentKeepaliveInterval != nil {
peer.Flags |= ioctl.PeerHasPersistentKeepalive
peer.PersistentKeepalive = uint16(*cfg.Peers[i].PersistentKeepaliveInterval / time.Second)
}
b.AppendPeer(peer)
for j := range cfg.Peers[i].AllowedIPs {
var family ioctl.AddressFamily
var ip net.IP
if ip = cfg.Peers[i].AllowedIPs[j].IP.To4(); ip != nil {
family = windows.AF_INET
} else if ip = cfg.Peers[i].AllowedIPs[j].IP.To16(); ip != nil {
family = windows.AF_INET6
} else {
ip = cfg.Peers[i].AllowedIPs[j].IP
}
cidr, _ := cfg.Peers[i].AllowedIPs[j].Mask.Size()
a := &ioctl.AllowedIP{
AddressFamily: family,
Cidr: uint8(cidr),
}
copy(a.Address[:], ip)
b.AppendAllowedIP(a)
}
}
interfaze, size := b.Interface()
return windows.DeviceIoControl(handle, ioctl.IoctlSet, nil, 0, (*byte)(unsafe.Pointer(interfaze)), size, &size, nil)
}

View File

@@ -0,0 +1,135 @@
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
*/
package ioctl
import "unsafe"
const (
IoctlGet = 0xb098c506
IoctlSet = 0xb098c509
)
type AllowedIP struct {
Address [16]byte
AddressFamily AddressFamily
Cidr uint8
_ [4]byte
}
type PeerFlag uint32
const (
PeerHasPublicKey PeerFlag = 1 << 0
PeerHasPresharedKey PeerFlag = 1 << 1
PeerHasPersistentKeepalive PeerFlag = 1 << 2
PeerHasEndpoint PeerFlag = 1 << 3
PeerHasProtocolVersion PeerFlag = 1 << 4
PeerReplaceAllowedIPs PeerFlag = 1 << 5
PeerRemove PeerFlag = 1 << 6
PeerUpdateOnly PeerFlag = 1 << 7
)
type Peer struct {
Flags PeerFlag
ProtocolVersion uint32
PublicKey [32]byte
PresharedKey [32]byte
PersistentKeepalive uint16
_ uint16
Endpoint RawSockaddrInet
TxBytes uint64
RxBytes uint64
LastHandshake uint64
AllowedIPsCount uint32
_ [4]byte
}
type InterfaceFlag uint32
const (
InterfaceHasPublicKey InterfaceFlag = 1 << 0
InterfaceHasPrivateKey InterfaceFlag = 1 << 1
InterfaceHasListenPort InterfaceFlag = 1 << 2
InterfaceReplacePeers InterfaceFlag = 1 << 3
)
type Interface struct {
Flags InterfaceFlag
ListenPort uint16
PrivateKey [32]byte
PublicKey [32]byte
PeerCount uint32
_ [4]byte
}
func (interfaze *Interface) FirstPeer() *Peer {
return (*Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(interfaze)) + unsafe.Sizeof(*interfaze)))
}
func (peer *Peer) NextPeer() *Peer {
return (*Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(peer)) + unsafe.Sizeof(*peer) + uintptr(peer.AllowedIPsCount)*unsafe.Sizeof(AllowedIP{})))
}
func (peer *Peer) FirstAllowedIP() *AllowedIP {
return (*AllowedIP)(unsafe.Pointer(uintptr(unsafe.Pointer(peer)) + unsafe.Sizeof(*peer)))
}
func (allowedIP *AllowedIP) NextAllowedIP() *AllowedIP {
return (*AllowedIP)(unsafe.Pointer(uintptr(unsafe.Pointer(allowedIP)) + unsafe.Sizeof(*allowedIP)))
}
type ConfigBuilder struct {
buffer []byte
}
func (builder *ConfigBuilder) Preallocate(size uint32) {
if builder.buffer == nil {
builder.buffer = make([]byte, 0, size)
}
}
func (builder *ConfigBuilder) AppendInterface(interfaze *Interface) {
var newBytes []byte
unsafeSlice(unsafe.Pointer(&newBytes), unsafe.Pointer(interfaze), int(unsafe.Sizeof(*interfaze)))
builder.buffer = append(builder.buffer, newBytes...)
}
func (builder *ConfigBuilder) AppendPeer(peer *Peer) {
var newBytes []byte
unsafeSlice(unsafe.Pointer(&newBytes), unsafe.Pointer(peer), int(unsafe.Sizeof(*peer)))
builder.buffer = append(builder.buffer, newBytes...)
}
func (builder *ConfigBuilder) AppendAllowedIP(allowedIP *AllowedIP) {
var newBytes []byte
unsafeSlice(unsafe.Pointer(&newBytes), unsafe.Pointer(allowedIP), int(unsafe.Sizeof(*allowedIP)))
builder.buffer = append(builder.buffer, newBytes...)
}
func (builder *ConfigBuilder) Interface() (*Interface, uint32) {
if builder.buffer == nil {
return nil, 0
}
return (*Interface)(unsafe.Pointer(&builder.buffer[0])), uint32(len(builder.buffer))
}
// unsafeSlice updates the slice slicePtr to be a slice
// referencing the provided data with its length & capacity set to
// lenCap.
//
// TODO: whenGo 1.17 is the minimum supported version,
// update callers to use unsafe.Slice instead of this.
func unsafeSlice(slicePtr, data unsafe.Pointer, lenCap int) {
type sliceHeader struct {
Data unsafe.Pointer
Len int
Cap int
}
h := (*sliceHeader)(slicePtr)
h.Data = data
h.Len = lenCap
h.Cap = lenCap
}

View File

@@ -0,0 +1,87 @@
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
*/
package ioctl
import (
"encoding/binary"
"net"
"unsafe"
"golang.org/x/sys/windows"
)
// AddressFamily enumeration specifies protocol family and is one of the windows.AF_* constants.
type AddressFamily uint16
// RawSockaddrInet union contains an IPv4, an IPv6 address, or an address family.
// https://docs.microsoft.com/en-us/windows/desktop/api/ws2ipdef/ns-ws2ipdef-_sockaddr_inet
type RawSockaddrInet struct {
Family AddressFamily
data [26]byte
}
func ntohs(i uint16) uint16 {
return binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&i))[:])
}
func htons(i uint16) uint16 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, i)
return *(*uint16)(unsafe.Pointer(&b[0]))
}
// SetIP method sets family, address, and port to the given IPv4 or IPv6 address and port.
// All other members of the structure are set to zero.
func (addr *RawSockaddrInet) SetIP(ip net.IP, port uint16) error {
if v4 := ip.To4(); v4 != nil {
addr4 := (*windows.RawSockaddrInet4)(unsafe.Pointer(addr))
addr4.Family = windows.AF_INET
copy(addr4.Addr[:], v4)
addr4.Port = htons(port)
for i := 0; i < 8; i++ {
addr4.Zero[i] = 0
}
return nil
}
if v6 := ip.To16(); v6 != nil {
addr6 := (*windows.RawSockaddrInet6)(unsafe.Pointer(addr))
addr6.Family = windows.AF_INET6
addr6.Port = htons(port)
addr6.Flowinfo = 0
copy(addr6.Addr[:], v6)
addr6.Scope_id = 0
return nil
}
return windows.ERROR_INVALID_PARAMETER
}
// IP returns IPv4 or IPv6 address, or nil if the address is neither.
func (addr *RawSockaddrInet) IP() net.IP {
switch addr.Family {
case windows.AF_INET:
return (*windows.RawSockaddrInet4)(unsafe.Pointer(addr)).Addr[:]
case windows.AF_INET6:
return (*windows.RawSockaddrInet6)(unsafe.Pointer(addr)).Addr[:]
}
return nil
}
// Port returns the port if the address if IPv4 or IPv6, or 0 if neither.
func (addr *RawSockaddrInet) Port() uint16 {
switch addr.Family {
case windows.AF_INET:
return ntohs((*windows.RawSockaddrInet4)(unsafe.Pointer(addr)).Port)
case windows.AF_INET6:
return ntohs((*windows.RawSockaddrInet6)(unsafe.Pointer(addr)).Port)
}
return 0
}

View File

@@ -1,4 +1,5 @@
//+build linux
//go:build linux
// +build linux
package wgctrl

View File

@@ -1,4 +1,5 @@
//+build openbsd
//go:build openbsd
// +build openbsd
package wgctrl
@@ -12,8 +13,7 @@ import (
func newClients() ([]wginternal.Client, error) {
var clients []wginternal.Client
// OpenBSD has an experimental in-kernel WireGuard implementation:
// https://git.zx2c4.com/wireguard-openbsd/about/. Determine if it is
// OpenBSD has an in-kernel WireGuard implementation. Determine if it is
// available and make use of it if so.
kc, ok, err := wgopenbsd.New()
if err != nil {

View File

@@ -1,4 +1,5 @@
//+build !linux,!openbsd
//go:build !linux && !openbsd && !windows
// +build !linux,!openbsd,!windows
package wgctrl

27
vendor/golang.zx2c4.com/wireguard/wgctrl/os_windows.go generated vendored Normal file
View File

@@ -0,0 +1,27 @@
//go:build windows
// +build windows
package wgctrl
import (
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/internal/wguser"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgwindows"
)
// newClients configures wginternal.Clients for Windows systems.
func newClients() ([]wginternal.Client, error) {
var clients []wginternal.Client
// Windows has an in-kernel WireGuard implementation.
kc := wgwindows.New()
clients = append(clients, kc)
uc, err := wguser.New()
if err != nil {
return nil, err
}
clients = append(clients, uc)
return clients, nil
}

View File

@@ -18,6 +18,7 @@ const (
Unknown DeviceType = iota
LinuxKernel
OpenBSDKernel
WindowsKernel
Userspace
)
@@ -28,6 +29,8 @@ func (dt DeviceType) String() string {
return "Linux kernel"
case OpenBSDKernel:
return "OpenBSD kernel"
case WindowsKernel:
return "Windows kernel"
case Userspace:
return "userspace"
default: