Debian Codegraph @

dns/win32util.py

raw
1 import sys
2
3 import dns._features
4
5 # pylint: disable=W0612,W0613,C0301
6
7 if sys.platform == "win32":
8 import ctypes
9 import ctypes.wintypes as wintypes
10 import winreg # pylint: disable=import-error
11 from enum import IntEnum
12
13 import dns.name
14
15 # Keep pylint quiet on non-windows.
16 try:
17 _ = WindowsError # pylint: disable=used-before-assignment
18 except NameError:
19 WindowsError = Exception
20
21 class ConfigMethod(IntEnum):
22 Registry = 1
23 WMI = 2
24 Win32 = 3
25
26 class DnsInfo:
27 def __init__(self):
28 self.domain = None
29 self.nameservers = []
30 self.search = []
31
32 _config_method = ConfigMethod.Registry
33
34 if dns._features.have("wmi"):
35 import threading
36
37 import pythoncom # pylint: disable=import-error
38 import wmi # pylint: disable=import-error
39
40 # Prefer WMI by default if wmi is installed.
41 _config_method = ConfigMethod.WMI
42
43 class _WMIGetter(threading.Thread):
44 # pylint: disable=possibly-used-before-assignment
45 def __init__(self):
46 super().__init__()
47 self.info = DnsInfo()
48
49 def run(self):
50 pythoncom.CoInitialize()
51 try:
52 system = wmi.WMI()
53 for interface in system.Win32_NetworkAdapterConfiguration():
54 if interface.IPEnabled and interface.DNSServerSearchOrder:
55 self.info.nameservers = list(interface.DNSServerSearchOrder)
56 if interface.DNSDomain:
57 self.info.domain = _config_domain(interface.DNSDomain)
58 if interface.DNSDomainSuffixSearchOrder:
59 self.info.search = [
60 _config_domain(x)
61 for x in interface.DNSDomainSuffixSearchOrder
62 ]
63 break
64 finally:
65 pythoncom.CoUninitialize()
66
67 def get(self):
68 # We always run in a separate thread to avoid any issues with
69 # the COM threading model.
70 self.start()
71 self.join()
72 return self.info
73
74 else:
75
76 class _WMIGetter: # type: ignore
77 pass
78
79 def _config_domain(domain):
80 # Sometimes DHCP servers add a '.' prefix to the default domain, and
81 # Windows just stores such values in the registry (see #687).
82 # Check for this and fix it.
83 if domain.startswith("."):
84 domain = domain[1:]
85 return dns.name.from_text(domain)
86
87 class _RegistryGetter:
88 def __init__(self):
89 self.info = DnsInfo()
90
91 def _split(self, text):
92 # The windows registry has used both " " and "," as a delimiter, and while
93 # it is currently using "," in Windows 10 and later, updates can seemingly
94 # leave a space in too, e.g. "a, b". So we just convert all commas to
95 # spaces, and use split() in its default configuration, which splits on
96 # all whitespace and ignores empty strings.
97 return text.replace(",", " ").split()
98
99 def _config_nameservers(self, nameservers):
100 for ns in self._split(nameservers):
101 if ns not in self.info.nameservers:
102 self.info.nameservers.append(ns)
103
104 def _config_search(self, search):
105 for s in self._split(search):
106 s = _config_domain(s)
107 if s not in self.info.search:
108 self.info.search.append(s)
109
110 def _config_fromkey(self, key, always_try_domain):
111 try:
112 servers, _ = winreg.QueryValueEx(key, "NameServer")
113 except WindowsError:
114 servers = None
115 if servers:
116 self._config_nameservers(servers)
117 if servers or always_try_domain:
118 try:
119 dom, _ = winreg.QueryValueEx(key, "Domain")
120 if dom:
121 self.info.domain = _config_domain(dom)
122 except WindowsError:
123 pass
124 else:
125 try:
126 servers, _ = winreg.QueryValueEx(key, "DhcpNameServer")
127 except WindowsError:
128 servers = None
129 if servers:
130 self._config_nameservers(servers)
131 try:
132 dom, _ = winreg.QueryValueEx(key, "DhcpDomain")
133 if dom:
134 self.info.domain = _config_domain(dom)
135 except WindowsError:
136 pass
137 try:
138 search, _ = winreg.QueryValueEx(key, "SearchList")
139 except WindowsError:
140 search = None
141 if search is None:
142 try:
143 search, _ = winreg.QueryValueEx(key, "DhcpSearchList")
144 except WindowsError:
145 search = None
146 if search:
147 self._config_search(search)
148
149 def _is_nic_enabled(self, lm, guid):
150 # Look in the Windows Registry to determine whether the network
151 # interface corresponding to the given guid is enabled.
152 #
153 # (Code contributed by Paul Marks, thanks!)
154 #
155 try:
156 # This hard-coded location seems to be consistent, at least
157 # from Windows 2000 through Vista.
158 connection_key = winreg.OpenKey(
159 lm,
160 r"SYSTEM\CurrentControlSet\Control\Network"
161 r"\{4D36E972-E325-11CE-BFC1-08002BE10318}"
162 rf"\{guid}\Connection",
163 )
164
165 try:
166 # The PnpInstanceID points to a key inside Enum
167 (pnp_id, ttype) = winreg.QueryValueEx(
168 connection_key, "PnpInstanceID"
169 )
170
171 if ttype != winreg.REG_SZ:
172 raise ValueError # pragma: no cover
173
174 device_key = winreg.OpenKey(
175 lm, rf"SYSTEM\CurrentControlSet\Enum\{pnp_id}"
176 )
177
178 try:
179 # Get ConfigFlags for this device
180 (flags, ttype) = winreg.QueryValueEx(device_key, "ConfigFlags")
181
182 if ttype != winreg.REG_DWORD:
183 raise ValueError # pragma: no cover
184
185 # Based on experimentation, bit 0x1 indicates that the
186 # device is disabled.
187 #
188 # XXXRTH I suspect we really want to & with 0x03 so
189 # that CONFIGFLAGS_REMOVED devices are also ignored,
190 # but we're shifting to WMI as ConfigFlags is not
191 # supposed to be used.
192 return not flags & 0x1
193
194 finally:
195 device_key.Close()
196 finally:
197 connection_key.Close()
198 except Exception: # pragma: no cover
199 return False
200
201 def get(self):
202 """Extract resolver configuration from the Windows registry."""
203
204 lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
205 try:
206 tcp_params = winreg.OpenKey(
207 lm, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
208 )
209 try:
210 self._config_fromkey(tcp_params, True)
211 finally:
212 tcp_params.Close()
213 interfaces = winreg.OpenKey(
214 lm,
215 r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces",
216 )
217 try:
218 i = 0
219 while True:
220 try:
221 guid = winreg.EnumKey(interfaces, i)
222 i += 1
223 key = winreg.OpenKey(interfaces, guid)
224 try:
225 if not self._is_nic_enabled(lm, guid):
226 continue
227 self._config_fromkey(key, False)
228 finally:
229 key.Close()
230 except OSError:
231 break
232 finally:
233 interfaces.Close()
234 finally:
235 lm.Close()
236 return self.info
237
238 class _Win32Getter(_RegistryGetter):
239
240 def get(self):
241 """Get the attributes using the Windows API."""
242 # Load the IP Helper library
243 # # https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
244 IPHLPAPI = ctypes.WinDLL("Iphlpapi.dll")
245
246 # Constants
247 AF_UNSPEC = 0
248 ERROR_SUCCESS = 0
249 GAA_FLAG_INCLUDE_PREFIX = 0x00000010
250 AF_INET = 2
251 AF_INET6 = 23
252 IF_TYPE_SOFTWARE_LOOPBACK = 24
253
254 # Define necessary structures
255 class SOCKADDRV4(ctypes.Structure):
256 _fields_ = [
257 ("sa_family", wintypes.USHORT),
258 ("sa_data", ctypes.c_ubyte * 14),
259 ]
260
261 class SOCKADDRV6(ctypes.Structure):
262 _fields_ = [
263 ("sa_family", wintypes.USHORT),
264 ("sa_data", ctypes.c_ubyte * 26),
265 ]
266
267 class SOCKET_ADDRESS(ctypes.Structure):
268 _fields_ = [
269 ("lpSockaddr", ctypes.POINTER(SOCKADDRV4)),
270 ("iSockaddrLength", wintypes.INT),
271 ]
272
273 class IP_ADAPTER_DNS_SERVER_ADDRESS(ctypes.Structure):
274 pass # Forward declaration
275
276 IP_ADAPTER_DNS_SERVER_ADDRESS._fields_ = [
277 ("Length", wintypes.ULONG),
278 ("Reserved", wintypes.DWORD),
279 ("Next", ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS)),
280 ("Address", SOCKET_ADDRESS),
281 ]
282
283 class IF_LUID(ctypes.Structure):
284 _fields_ = [("Value", ctypes.c_ulonglong)]
285
286 class NET_IF_NETWORK_GUID(ctypes.Structure):
287 _fields_ = [("Value", ctypes.c_ubyte * 16)]
288
289 class IP_ADAPTER_PREFIX_XP(ctypes.Structure):
290 pass # Left undefined here for simplicity
291
292 class IP_ADAPTER_GATEWAY_ADDRESS_LH(ctypes.Structure):
293 pass # Left undefined here for simplicity
294
295 class IP_ADAPTER_DNS_SUFFIX(ctypes.Structure):
296 _fields_ = [
297 ("String", ctypes.c_wchar * 256),
298 ("Next", ctypes.POINTER(ctypes.c_void_p)),
299 ]
300
301 class IP_ADAPTER_UNICAST_ADDRESS_LH(ctypes.Structure):
302 pass # Left undefined here for simplicity
303
304 class IP_ADAPTER_MULTICAST_ADDRESS_XP(ctypes.Structure):
305 pass # Left undefined here for simplicity
306
307 class IP_ADAPTER_ANYCAST_ADDRESS_XP(ctypes.Structure):
308 pass # Left undefined here for simplicity
309
310 class IP_ADAPTER_DNS_SERVER_ADDRESS_XP(ctypes.Structure):
311 pass # Left undefined here for simplicity
312
313 class IP_ADAPTER_ADDRESSES(ctypes.Structure):
314 pass # Forward declaration
315
316 IP_ADAPTER_ADDRESSES._fields_ = [
317 ("Length", wintypes.ULONG),
318 ("IfIndex", wintypes.DWORD),
319 ("Next", ctypes.POINTER(IP_ADAPTER_ADDRESSES)),
320 ("AdapterName", ctypes.c_char_p),
321 ("FirstUnicastAddress", ctypes.POINTER(SOCKET_ADDRESS)),
322 ("FirstAnycastAddress", ctypes.POINTER(SOCKET_ADDRESS)),
323 ("FirstMulticastAddress", ctypes.POINTER(SOCKET_ADDRESS)),
324 (
325 "FirstDnsServerAddress",
326 ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS),
327 ),
328 ("DnsSuffix", wintypes.LPWSTR),
329 ("Description", wintypes.LPWSTR),
330 ("FriendlyName", wintypes.LPWSTR),
331 ("PhysicalAddress", ctypes.c_ubyte * 8),
332 ("PhysicalAddressLength", wintypes.ULONG),
333 ("Flags", wintypes.ULONG),
334 ("Mtu", wintypes.ULONG),
335 ("IfType", wintypes.ULONG),
336 ("OperStatus", ctypes.c_uint),
337 # Remaining fields removed for brevity
338 ]
339
340 def format_ipv4(sockaddr_in):
341 return ".".join(map(str, sockaddr_in.sa_data[2:6]))
342
343 def format_ipv6(sockaddr_in6):
344 # The sa_data is:
345 #
346 # USHORT sin6_port;
347 # ULONG sin6_flowinfo;
348 # IN6_ADDR sin6_addr;
349 # ULONG sin6_scope_id;
350 #
351 # which is 2 + 4 + 16 + 4 = 26 bytes, and we need the plus 6 below
352 # to be in the sin6_addr range.
353 parts = [
354 sockaddr_in6.sa_data[i + 6] << 8 | sockaddr_in6.sa_data[i + 6 + 1]
355 for i in range(0, 16, 2)
356 ]
357 return ":".join(f"{part:04x}" for part in parts)
358
359 buffer_size = ctypes.c_ulong(15000)
360 while True:
361 buffer = ctypes.create_string_buffer(buffer_size.value)
362
363 ret_val = IPHLPAPI.GetAdaptersAddresses(
364 AF_UNSPEC,
365 GAA_FLAG_INCLUDE_PREFIX,
366 None,
367 buffer,
368 ctypes.byref(buffer_size),
369 )
370
371 if ret_val == ERROR_SUCCESS:
372 break
373 elif ret_val != 0x6F: # ERROR_BUFFER_OVERFLOW
374 print(f"Error retrieving adapter information: {ret_val}")
375 return
376
377 adapter_addresses = ctypes.cast(
378 buffer, ctypes.POINTER(IP_ADAPTER_ADDRESSES)
379 )
380
381 current_adapter = adapter_addresses
382 while current_adapter:
383
384 # Skip non-operational adapters.
385 oper_status = current_adapter.contents.OperStatus
386 if oper_status != 1:
387 current_adapter = current_adapter.contents.Next
388 continue
389
390 # Exclude loopback adapters.
391 if current_adapter.contents.IfType == IF_TYPE_SOFTWARE_LOOPBACK:
392 current_adapter = current_adapter.contents.Next
393 continue
394
395 # Get the domain from the DnsSuffix attribute.
396 dns_suffix = current_adapter.contents.DnsSuffix
397 if dns_suffix:
398 self.info.domain = dns.name.from_text(dns_suffix)
399
400 current_dns_server = current_adapter.contents.FirstDnsServerAddress
401 while current_dns_server:
402 sockaddr = current_dns_server.contents.Address.lpSockaddr
403 sockaddr_family = sockaddr.contents.sa_family
404
405 ip = None
406 if sockaddr_family == AF_INET: # IPv4
407 ip = format_ipv4(sockaddr.contents)
408 elif sockaddr_family == AF_INET6: # IPv6
409 sockaddr = ctypes.cast(sockaddr, ctypes.POINTER(SOCKADDRV6))
410 ip = format_ipv6(sockaddr.contents)
411
412 if ip:
413 if ip not in self.info.nameservers:
414 self.info.nameservers.append(ip)
415
416 current_dns_server = current_dns_server.contents.Next
417
418 current_adapter = current_adapter.contents.Next
419
420 # Use the registry getter to get the search info, since it is set at the system level.
421 registry_getter = _RegistryGetter()
422 info = registry_getter.get()
423 self.info.search = info.search
424 return self.info
425
426 def set_config_method(method: ConfigMethod) -> None:
427 global _config_method
428 _config_method = method
429
430 def get_dns_info() -> DnsInfo:
431 """Extract resolver configuration."""
432 if _config_method == ConfigMethod.Win32:
433 getter = _Win32Getter()
434 elif _config_method == ConfigMethod.WMI:
435 getter = _WMIGetter()
436 else:
437 getter = _RegistryGetter()
438 return getter.get()