Debian Codegraph @

overlay/network_category_windows.go

raw
1 //go:build !e2e_testing
2 // +build !e2e_testing
3
4 package overlay
5
6 import (
7 "errors"
8 "fmt"
9 "log/slog"
10 "runtime"
11 "strings"
12 "syscall"
13 "time"
14 "unsafe"
15
16 "golang.org/x/sys/windows"
17 )
18
19 // networkCategory mirrors NLM_NETWORK_CATEGORY from netlistmgr.h.
20 type networkCategory int32
21
22 const (
23 networkCategoryPublic networkCategory = 0
24 networkCategoryPrivate networkCategory = 1
25 networkCategoryDomainAuthenticated networkCategory = 2
26 )
27
28 func (c networkCategory) String() string {
29 switch c {
30 case networkCategoryPublic:
31 return "public"
32 case networkCategoryPrivate:
33 return "private"
34 case networkCategoryDomainAuthenticated:
35 return "domain"
36 }
37 return fmt.Sprintf("unknown(%d)", c)
38 }
39
40 // parseNetworkCategory accepts the user-supplied tun.network_category. A
41 // second return of false means "leave the category alone".
42 func parseNetworkCategory(s string) (networkCategory, bool, error) {
43 switch strings.ToLower(strings.TrimSpace(s)) {
44 case "", "unset":
45 return 0, false, nil
46 case "public":
47 return networkCategoryPublic, true, nil
48 case "private":
49 return networkCategoryPrivate, true, nil
50 case "domain", "domainauthenticated":
51 return networkCategoryDomainAuthenticated, true, nil
52 }
53 return 0, false, fmt.Errorf("unknown tun.network_category %q (expected public, private, domain, or unset)", s)
54 }
55
56 // CLSID_NetworkListManager {DCB00C01-570F-4A9B-8D69-199FDBA5723B}
57 var clsidNetworkListManager = windows.GUID{
58 Data1: 0xDCB00C01, Data2: 0x570F, Data3: 0x4A9B,
59 Data4: [8]byte{0x8D, 0x69, 0x19, 0x9F, 0xDB, 0xA5, 0x72, 0x3B},
60 }
61
62 // IID_INetworkListManager {DCB00000-570F-4A9B-8D69-199FDBA5723B}
63 var iidINetworkListManager = windows.GUID{
64 Data1: 0xDCB00000, Data2: 0x570F, Data3: 0x4A9B,
65 Data4: [8]byte{0x8D, 0x69, 0x19, 0x9F, 0xDB, 0xA5, 0x72, 0x3B},
66 }
67
68 // x/sys/windows doesn't expose CoCreateInstance, so we bind it ourselves.
69 var procCoCreateInstance = windows.NewLazySystemDLL("ole32.dll").NewProc("CoCreateInstance")
70
71 const clsCtxAll = windows.CLSCTX_INPROC_SERVER | windows.CLSCTX_INPROC_HANDLER |
72 windows.CLSCTX_LOCAL_SERVER | windows.CLSCTX_REMOTE_SERVER
73
74 const (
75 hrSFALSE = 0x00000001
76 hrRPCEChangedMode = 0x80010106
77 )
78
79 type hresult uint32
80
81 func (h hresult) failed() bool { return int32(h) < 0 }
82 func (h hresult) String() string {
83 return fmt.Sprintf("HRESULT 0x%08x", uint32(h))
84 }
85
86 var errAdapterNotFound = errors.New("adapter not present in network connections enumeration")
87
88 // Vtable layouts. Slot order must match the declaration order in netlistmgr.h.
89 // All NLM interfaces here derive from IDispatch, which derives from IUnknown.
90
91 type iUnknownVtbl struct {
92 QueryInterface uintptr
93 AddRef uintptr
94 Release uintptr
95 }
96
97 type iDispatchVtbl struct {
98 iUnknownVtbl
99 GetTypeInfoCount uintptr
100 GetTypeInfo uintptr
101 GetIDsOfNames uintptr
102 Invoke uintptr
103 }
104
105 type iNetworkListManagerVtbl struct {
106 iDispatchVtbl
107 GetNetworks uintptr
108 GetNetwork uintptr
109 GetNetworkConnections uintptr
110 GetNetworkConnection uintptr
111 IsConnectedToInternet uintptr
112 IsConnected uintptr
113 GetConnectivity uintptr
114 }
115
116 type iNetworkListManager struct{ Vtbl *iNetworkListManagerVtbl }
117
118 func (n *iNetworkListManager) Release() {
119 syscall.SyscallN(n.Vtbl.Release, uintptr(unsafe.Pointer(n)))
120 }
121
122 func (n *iNetworkListManager) GetNetworkConnections() (*iEnumNetworkConnections, error) {
123 var enum *iEnumNetworkConnections
124 r1, _, _ := syscall.SyscallN(n.Vtbl.GetNetworkConnections,
125 uintptr(unsafe.Pointer(n)), uintptr(unsafe.Pointer(&enum)),
126 )
127 if hr := hresult(r1); hr.failed() {
128 return nil, fmt.Errorf("INetworkListManager.GetNetworkConnections: %s", hr)
129 }
130 return enum, nil
131 }
132
133 type iEnumNetworkConnectionsVtbl struct {
134 iDispatchVtbl
135 NewEnum uintptr
136 Next uintptr
137 Skip uintptr
138 Reset uintptr
139 Clone uintptr
140 }
141
142 type iEnumNetworkConnections struct{ Vtbl *iEnumNetworkConnectionsVtbl }
143
144 func (e *iEnumNetworkConnections) Release() {
145 syscall.SyscallN(e.Vtbl.Release, uintptr(unsafe.Pointer(e)))
146 }
147
148 // Next returns the next connection, or (nil, nil) at the end of the enumeration.
149 func (e *iEnumNetworkConnections) Next() (*iNetworkConnection, error) {
150 var conn *iNetworkConnection
151 var fetched uint32
152 r1, _, _ := syscall.SyscallN(e.Vtbl.Next,
153 uintptr(unsafe.Pointer(e)), 1,
154 uintptr(unsafe.Pointer(&conn)), uintptr(unsafe.Pointer(&fetched)),
155 )
156 if hr := hresult(r1); hr.failed() {
157 return nil, fmt.Errorf("IEnumNetworkConnections.Next: %s", hr)
158 }
159 if fetched == 0 {
160 return nil, nil
161 }
162 return conn, nil
163 }
164
165 type iNetworkConnectionVtbl struct {
166 iDispatchVtbl
167 GetNetwork uintptr
168 IsConnectedToInternet uintptr
169 IsConnected uintptr
170 GetConnectivity uintptr
171 GetConnectionId uintptr
172 GetAdapterId uintptr
173 GetDomainType uintptr
174 }
175
176 type iNetworkConnection struct{ Vtbl *iNetworkConnectionVtbl }
177
178 func (c *iNetworkConnection) Release() {
179 syscall.SyscallN(c.Vtbl.Release, uintptr(unsafe.Pointer(c)))
180 }
181
182 func (c *iNetworkConnection) GetAdapterId() (windows.GUID, error) {
183 var g windows.GUID
184 r1, _, _ := syscall.SyscallN(c.Vtbl.GetAdapterId,
185 uintptr(unsafe.Pointer(c)), uintptr(unsafe.Pointer(&g)),
186 )
187 if hr := hresult(r1); hr.failed() {
188 return windows.GUID{}, fmt.Errorf("INetworkConnection.GetAdapterId: %s", hr)
189 }
190 return g, nil
191 }
192
193 func (c *iNetworkConnection) GetNetwork() (*iNetwork, error) {
194 var net *iNetwork
195 r1, _, _ := syscall.SyscallN(c.Vtbl.GetNetwork,
196 uintptr(unsafe.Pointer(c)), uintptr(unsafe.Pointer(&net)),
197 )
198 if hr := hresult(r1); hr.failed() {
199 return nil, fmt.Errorf("INetworkConnection.GetNetwork: %s", hr)
200 }
201 return net, nil
202 }
203
204 type iNetworkVtbl struct {
205 iDispatchVtbl
206 GetName uintptr
207 SetName uintptr
208 GetDescription uintptr
209 SetDescription uintptr
210 GetNetworkId uintptr
211 GetDomainType uintptr
212 GetNetworkConnections uintptr
213 GetTimeCreatedAndConnected uintptr
214 IsConnectedToInternet uintptr
215 IsConnected uintptr
216 GetConnectivity uintptr
217 GetCategory uintptr
218 SetCategory uintptr
219 }
220
221 type iNetwork struct{ Vtbl *iNetworkVtbl }
222
223 func (n *iNetwork) Release() {
224 syscall.SyscallN(n.Vtbl.Release, uintptr(unsafe.Pointer(n)))
225 }
226
227 func (n *iNetwork) GetCategory() (networkCategory, error) {
228 var c networkCategory
229 r1, _, _ := syscall.SyscallN(n.Vtbl.GetCategory,
230 uintptr(unsafe.Pointer(n)), uintptr(unsafe.Pointer(&c)),
231 )
232 if hr := hresult(r1); hr.failed() {
233 return 0, fmt.Errorf("INetwork.GetCategory: %s", hr)
234 }
235 return c, nil
236 }
237
238 func (n *iNetwork) SetCategory(c networkCategory) error {
239 r1, _, _ := syscall.SyscallN(n.Vtbl.SetCategory,
240 uintptr(unsafe.Pointer(n)), uintptr(int32(c)),
241 )
242 if hr := hresult(r1); hr.failed() {
243 return fmt.Errorf("INetwork.SetCategory: %s", hr)
244 }
245 return nil
246 }
247
248 // coInit initializes COM for the current OS thread. The returned function must
249 // be deferred to balance a successful init. RPC_E_CHANGED_MODE means COM is
250 // already initialized in a different mode on this thread, which is still fine
251 // for our calls but we must not Uninitialize in that case.
252 func coInit() (func(), error) {
253 err := windows.CoInitializeEx(0, windows.COINIT_MULTITHREADED)
254 if err == nil {
255 return windows.CoUninitialize, nil
256 }
257 if e, ok := err.(syscall.Errno); ok {
258 switch uint32(e) {
259 case hrSFALSE:
260 return windows.CoUninitialize, nil
261 case hrRPCEChangedMode:
262 return func() {}, nil
263 }
264 }
265 return nil, fmt.Errorf("CoInitializeEx: %w", err)
266 }
267
268 func createNetworkListManager() (*iNetworkListManager, error) {
269 var nlm *iNetworkListManager
270 r1, _, _ := procCoCreateInstance.Call(
271 uintptr(unsafe.Pointer(&clsidNetworkListManager)),
272 0,
273 uintptr(clsCtxAll),
274 uintptr(unsafe.Pointer(&iidINetworkListManager)),
275 uintptr(unsafe.Pointer(&nlm)),
276 )
277 if hr := hresult(r1); hr.failed() {
278 return nil, fmt.Errorf("CoCreateInstance(NetworkListManager): %s", hr)
279 }
280 return nlm, nil
281 }
282
283 // setNetworkCategory locates the network connection bound to adapterGUID and
284 // sets the category of its parent network. Returns errAdapterNotFound if the
285 // adapter is not yet visible in the NLM enumeration.
286 func setNetworkCategory(adapterGUID windows.GUID, cat networkCategory) error {
287 deinit, err := coInit()
288 if err != nil {
289 return err
290 }
291 defer deinit()
292
293 nlm, err := createNetworkListManager()
294 if err != nil {
295 return err
296 }
297 defer nlm.Release()
298
299 enum, err := nlm.GetNetworkConnections()
300 if err != nil {
301 return err
302 }
303 defer enum.Release()
304
305 for {
306 conn, err := enum.Next()
307 if err != nil {
308 return err
309 }
310 if conn == nil {
311 return errAdapterNotFound
312 }
313
314 guid, err := conn.GetAdapterId()
315 if err != nil || guid != adapterGUID {
316 conn.Release()
317 continue
318 }
319
320 net, err := conn.GetNetwork()
321 conn.Release()
322 if err != nil {
323 return err
324 }
325 err = net.SetCategory(cat)
326 net.Release()
327 return err
328 }
329 }
330
331 // applyNetworkCategory polls until the wintun adapter shows up in the NLM
332 // enumeration, then sets the category. Intended to run in its own goroutine.
333 func applyNetworkCategory(l *slog.Logger, adapterGUID windows.GUID, cat networkCategory) {
334 // COM Init/Uninit must be paired on the same OS thread.
335 runtime.LockOSThread()
336 defer runtime.UnlockOSThread()
337
338 const (
339 attempts = 30
340 interval = 500 * time.Millisecond
341 )
342 for i := 0; i < attempts; i++ {
343 err := setNetworkCategory(adapterGUID, cat)
344 if err == nil {
345 l.Info("Set Windows network category", "category", cat.String())
346 return
347 }
348 if !errors.Is(err, errAdapterNotFound) {
349 l.Warn("Failed to set Windows network category", "error", err, "category", cat.String())
350 return
351 }
352 time.Sleep(interval)
353 }
354 l.Warn("Gave up waiting for adapter to appear in NLM enumeration; network category not set",
355 "category", cat.String(),
356 "waited", time.Duration(attempts)*interval,
357 )
358 }