forked from mandiant/flare-fakenet-ng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwinutil.py
executable file
·1292 lines (942 loc) · 41.1 KB
/
winutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import logging
logging.basicConfig(format='%(asctime)s [%(name)18s] %(message)s', datefmt='%m/%d/%y %I:%M:%S %p', level=logging.DEBUG)
from ctypes import *
from ctypes.wintypes import *
import os
import sys
import socket
import struct
import time
from _winreg import *
import subprocess
NO_ERROR = 0
AF_INET = 2
AF_INET6 = 23
ULONG64 = c_uint64
##############################################################################
# Services related functions
##############################################################################
SC_MANAGER_ALL_ACCESS = 0xF003F
SERVICE_ALL_ACCESS = 0xF01FF
SERVICE_STOP = 0x0020
SERVICE_QUERY_STATUS = 0x0004
SERVICE_ENUMERATE_DEPENDENTS = 0x0008
SC_STATUS_PROCESS_INFO = 0x0
SERVICE_STOPPED = 0x1
SERVICE_START_PENDING = 0x2
SERVICE_STOP_PENDING = 0x3
SERVICE_RUNNING = 0x4
SERVICE_CONTINUE_PENDING = 0x5
SERVICE_PAUSE_PENDING = 0x6
SERVICE_PAUSED = 0x7
SERVICE_CONTROL_STOP = 0x1
SERVICE_CONTROL_PAUSE = 0x2
SERVICE_CONTROL_CONTINUE = 0x3
SERVICE_NO_CHANGE = 0xffffffff
SERVICE_AUTO_START = 0x2
SERVICE_BOOT_START = 0x0
SERVICE_DEMAND_START = 0x3
SERVICE_DISABLED = 0x4
SERVICE_SYSTEM_START = 0x1
class SERVICE_STATUS_PROCESS(Structure):
_fields_ = [
("dwServiceType", DWORD),
("dwCurrentState", DWORD),
("dwControlsAccepted", DWORD),
("dwWin32ExitCode", DWORD),
("dwServiceSpecificExitCode", DWORD),
("dwCheckPoint", DWORD),
("dwWaitHint", DWORD),
("dwProcessId", DWORD),
("dwServiceFlags", DWORD),
]
##############################################################################
# Process related functions
##############################################################################
##############################################################################
# GetExtendedTcpTable constants and structures
TCP_TABLE_OWNER_PID_ALL = 5
class MIB_TCPROW_OWNER_PID(Structure):
_fields_ = [
("dwState", DWORD),
("dwLocalAddr", DWORD),
("dwLocalPort", DWORD),
("dwRemoteAddr", DWORD),
("dwRemotePort", DWORD),
("dwOwningPid", DWORD)
]
class MIB_TCPTABLE_OWNER_PID(Structure):
_fields_ = [
("dwNumEntries", DWORD),
("table", MIB_TCPROW_OWNER_PID * 512)
]
##############################################################################
# GetExtendedUdpTable constants and structures
UDP_TABLE_OWNER_PID = 1
class MIB_UDPROW_OWNER_PID(Structure):
_fields_ = [
("dwLocalAddr", DWORD),
("dwLocalPort", DWORD),
("dwOwningPid", DWORD)
]
class MIB_UDPTABLE_OWNER_PID(Structure):
_fields_ = [
("dwNumEntries", DWORD),
("table", MIB_UDPROW_OWNER_PID * 512)
]
###############################################################################
# GetProcessImageFileName constants and structures
MAX_PATH = 260
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
###############################################################################
# Network interface related functions
###############################################################################
MIB_IF_TYPE_ETHERNET = 6
MIB_IF_TYPE_LOOPBACK = 28
IF_TYPE_IEEE80211 = 71
###############################################################################
# GetAdaptersAddresses constants and structures
MAX_ADAPTER_ADDRESS_LENGTH = 8
MAX_DHCPV6_DUID_LENGTH = 130
IFOPERSTATUSUP = 1
class SOCKADDR(Structure):
_fields_ = [
("sa_family", c_ushort),
("sa_data", c_char * 14),
]
class SOCKET_ADDRESS(Structure):
_fields_ = [
("Sockaddr", POINTER(SOCKADDR)),
("SockaddrLength", INT),
]
class IP_ADAPTER_PREFIX(Structure):
pass
IP_ADAPTER_PREFIX._fields_ = [
("Length", ULONG),
("Flags", DWORD),
("Next", POINTER(IP_ADAPTER_PREFIX)),
("Address", SOCKET_ADDRESS),
("PrefixLength", ULONG),
]
class IP_ADAPTER_ADDRESSES(Structure):
pass
IP_ADAPTER_ADDRESSES._fields_ = [
("Length", ULONG),
("IfIndex", DWORD),
("Next", POINTER(IP_ADAPTER_ADDRESSES)),
("AdapterName", LPSTR),
("FirstUnicastAddress", c_void_p), # Not used
("FirstAnycastAddress", c_void_p), # Not used
("FirstMulticastAddress", c_void_p), # Not used
("FirstDnsServerAddress", c_void_p), # Not used
("DnsSuffix", LPWSTR),
("Description", LPWSTR),
("FriendlyName", LPWSTR),
("PhysicalAddress", BYTE * MAX_ADAPTER_ADDRESS_LENGTH),
("PhysicalAddressLength", DWORD),
("Flags", DWORD),
("Mtu", DWORD),
("IfType", DWORD),
("OperStatus", DWORD),
("Ipv6IfIndex", DWORD),
("ZoneIndices", DWORD * 16),
("FirstPrefix", POINTER(IP_ADAPTER_PREFIX)),
("TransmitLinkSpeed", ULONG64),
("ReceiveLinkSpeed", ULONG64),
("FirstWinsServerAddress", c_void_p), # Not used
("FirstGatewayAddress", c_void_p), # Not used
("Ipv4Metric", ULONG),
("Ipv6Metric", ULONG),
("Luid", ULONG64),
("Dhcpv4Server", SOCKET_ADDRESS),
("CompartmentId", DWORD),
("NetworkGuid", BYTE * 16),
("ConnectionType", DWORD),
("TunnelType", DWORD),
("Dhcpv6Server", SOCKET_ADDRESS),
("Dhcpv6ClientDuid", BYTE * MAX_DHCPV6_DUID_LENGTH),
("Dhcpv6ClientDuidLength", ULONG),
("Dhcpv6Iaid", ULONG),
("FirstDnsSuffix", c_void_p), # Not used
]
###############################################################################
# GetAdaptersInfo constants and structures
MAX_ADAPTER_NAME_LENGTH = 256
MAX_ADAPTER_DESCRIPTION_LENGTH = 128
MAX_ADAPTER_LENGTH = 8
MIB_IF_TYPE_ETHERNET = 6
MIB_IF_TYPE_LOOPBACK = 28
IF_TYPE_IEEE80211 = 71
class IP_ADDRESS_STRING(Structure):
_fields_ = [
("String", c_char * 16),
]
class IP_MASK_STRING(Structure):
_fields_ = [
("String", c_char * 16),
]
class IP_ADDR_STRING(Structure):
pass
IP_ADDR_STRING._fields_ = [
("Next", POINTER(IP_ADDR_STRING)),
("IpAddress", IP_ADDRESS_STRING),
("IpMask", IP_MASK_STRING),
("Context", DWORD),
]
class IP_ADAPTER_INFO(Structure):
pass
IP_ADAPTER_INFO._fields_ = [
("Next", POINTER(IP_ADAPTER_INFO)),
("ComboIndex", DWORD),
("AdapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
("Description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
("AddressLength", UINT),
("Address", BYTE * MAX_ADAPTER_LENGTH),
("Index", DWORD),
("Type", UINT),
("DhcpEnabled", UINT),
("CurrentIpAddress", c_void_p), # Not used
("IpAddressList", IP_ADDR_STRING),
("GatewayList", IP_ADDR_STRING),
("DhcpServer", IP_ADDR_STRING),
("HaveWins", BOOL),
("PrimaryWinsServer", IP_ADDR_STRING),
("SecondaryWinsServer", IP_ADDR_STRING),
("LeaseObtained", c_ulong),
("LeaseExpires", c_ulong),
]
###############################################################################
# GetNetworkParams constants and structures
MAX_HOSTNAME_LEN = 128
MAX_DOMAIN_NAME_LEN = 128
MAX_SCOPE_ID_LEN = 256
###############################################################################
# ConvertInterface constants and structures
NDIS_IF_MAX_STRING_SIZE = 256
class IP_ADDRESS_STRING(Structure):
_fields_ = [
("String", c_char * 16),
]
class IP_MASK_STRING(Structure):
_fields_ = [
("String", c_char * 16),
]
class IP_ADDR_STRING(Structure):
pass
IP_ADDR_STRING._fields_ = [
("Next", POINTER(IP_ADDR_STRING)),
("IpAddress", IP_ADDRESS_STRING),
("IpMask", IP_MASK_STRING),
("Context", DWORD),
]
class FIXED_INFO(Structure):
_fields_ = [
("HostName", c_char * (MAX_HOSTNAME_LEN + 4)),
("DomainName", c_char * (MAX_DOMAIN_NAME_LEN + 4)),
("CurrentDnsServer", c_void_p), # Not used
("DnsServerList", IP_ADDR_STRING),
("NodeType", UINT),
("ScopeId", c_char * (MAX_SCOPE_ID_LEN + 4)),
("EnableRouting", UINT),
("EnableProxy", UINT),
("EnableDns", UINT),
]
class WinUtilMixin():
###########################################################################
# Service related functions
###########################################################################
###########################################################################
# Establishes a connection to the service control manager on the specified computer and opens the specified service control manager database.
#
# SC_HANDLE WINAPI OpenSCManager(
# _In_opt_ LPCTSTR lpMachineName,
# _In_opt_ LPCTSTR lpDatabaseName,
# _In_ DWORD dwDesiredAccess
# );
def open_sc_manager(self):
sc_handle = windll.advapi32.OpenSCManagerA(0, 0, SC_MANAGER_ALL_ACCESS)
if sc_handle == 0:
self.logger.error("Failed to call OpenSCManager")
return
return sc_handle
###########################################################################
# Closes a handle to a service control manager or service object
#
# BOOL WINAPI CloseServiceHandle(
# _In_ SC_HANDLE hSCObject
# );
def close_service_handle(self, sc_handle):
if windll.advapi32.CloseServiceHandle(sc_handle) == 0:
self.logger.error('Failed to call CloseServiceHandle')
return False
return True
###########################################################################
# Opens an existing service.
#
# SC_HANDLE WINAPI OpenService(
# _In_ SC_HANDLE hSCManager,
# _In_ LPCTSTR lpServiceName,
# _In_ DWORD dwDesiredAccess
# );
def open_service(self, sc_handle, service_name, dwDesiredAccess = SERVICE_ALL_ACCESS):
if not sc_handle:
return
service_handle = windll.advapi32.OpenServiceA(sc_handle, service_name, dwDesiredAccess)
if service_handle == 0:
self.logger.error('Failed to call OpenService')
return
return service_handle
###########################################################################
# Retrieves the current status of the specified service based on the specified information level.
#
# BOOL WINAPI QueryServiceStatusEx(
# _In_ SC_HANDLE hService,
# _In_ SC_STATUS_TYPE InfoLevel,
# _Out_opt_ LPBYTE lpBuffer,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded
# );
def query_service_status_ex(self, service_handle):
lpBuffer = SERVICE_STATUS_PROCESS()
cbBufSize = DWORD(sizeof(SERVICE_STATUS_PROCESS))
pcbBytesNeeded = DWORD()
if windll.advapi32.QueryServiceStatusEx(service_handle, SC_STATUS_PROCESS_INFO, byref(lpBuffer), cbBufSize, byref(pcbBytesNeeded)) == 0:
self.logger.error('Failed to call QueryServiceStatusEx')
return
return lpBuffer
###########################################################################
# Sends a control code to a service.
#
# BOOL WINAPI ControlService(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwControl,
# _Out_ LPSERVICE_STATUS lpServiceStatus
# );
def control_service(self, service_handle, dwControl):
lpServiceStatus = SERVICE_STATUS_PROCESS()
if windll.advapi32.ControlService(service_handle, dwControl, byref(lpServiceStatus)) == 0:
self.logger.error('Failed to call ControlService')
return
return lpServiceStatus
###########################################################################
# Starts a service
#
# BOOL WINAPI StartService(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwNumServiceArgs,
# _In_opt_ LPCTSTR *lpServiceArgVectors
# );
def start_service(self, service_handle):
if windll.advapi32.StartServiceA(service_handle, 0, 0) == 0:
self.logger.error('Failed to call StartService')
return False
else:
return True
###########################################################################
# Changes the configuration parameters of a service.
#
# BOOL WINAPI ChangeServiceConfig(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwServiceType,
# _In_ DWORD dwStartType,
# _In_ DWORD dwErrorControl,
# _In_opt_ LPCTSTR lpBinaryPathName,
# _In_opt_ LPCTSTR lpLoadOrderGroup,
# _Out_opt_ LPDWORD lpdwTagId,
# _In_opt_ LPCTSTR lpDependencies,
# _In_opt_ LPCTSTR lpServiceStartName,
# _In_opt_ LPCTSTR lpPassword,
# _In_opt_ LPCTSTR lpDisplayName
# );
def change_service_config(self, service_handle, dwStartType = SERVICE_DISABLED):
if windll.advapi32.ChangeServiceConfigA(service_handle, SERVICE_NO_CHANGE, dwStartType, SERVICE_NO_CHANGE, 0, 0, 0, 0, 0, 0, 0) == 0:
self.logger.error('Failed to call ChangeServiceConfig')
raise WinError(get_last_error())
return False
else:
return True
def start_service_helper(self, service_name = 'Dnscache'):
sc_handle = None
service_handle = None
timeout = 5
sc_handle = self.open_sc_manager()
if not sc_handle:
return
service_handle = self.open_service(sc_handle, service_name)
if not service_handle:
self.close_service_handle(sc_handle)
return
# Enable the service
if not self.change_service_config(service_handle, SERVICE_AUTO_START):
# Backup enable the service
try:
subprocess.check_call("sc config %s start= auto" % service_name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError, e:
self.logger.error('Failed to enable the service %s. (sc config)', service_name)
else:
self.logger.info('Successfully enabled the service %s. (sc config)', service_name)
else:
self.logger.info('Successfully enabled the service %s.', service_name)
service_status = self.query_service_status_ex(service_handle)
if service_status:
if not service_status.dwCurrentState in [SERVICE_RUNNING, SERVICE_START_PENDING]:
# Start service
if self.start_service(service_handle):
# Wait for the service to start
while timeout:
timeout -= 1
time.sleep(1)
service_status = self.query_service_status_ex(service_handle)
if service_status.dwCurrentState == SERVICE_RUNNING:
self.logger.info('Successfully started the service %s.', service_name)
break
else:
self.logger.error('Timed out while trying to start the service %s.', service_name)
else:
self.logger.error('Failed to start the service %s.', service_name)
else:
self.logger.error('Service %s is already running.', service_name)
# As a backup call net stop
if service_status.dwCurrentState != SERVICE_RUNNING:
try:
subprocess.check_call("net start %s" % service_name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError, e:
self.logger.error('Failed to start the service %s. (net stop)', service_name)
else:
self.logger.info('Successfully started the service %s.', service_name)
self.close_service_handle(service_handle)
self.close_service_handle(sc_handle)
def stop_service_helper(self, service_name = 'Dnscache'):
sc_handle = None
service_handle = None
Control = SERVICE_CONTROL_STOP
dwControl = DWORD(Control)
timeout = 5
sc_handle = self.open_sc_manager()
if not sc_handle:
return
service_handle = self.open_service(sc_handle, service_name)
if not service_handle:
self.close_service_handle(sc_handle)
return
# Disable the service
if not self.change_service_config(service_handle, SERVICE_DISABLED):
# Backup disable the service
try:
subprocess.check_call("sc config %s start= disabled" % service_name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError, e:
self.logger.error('Failed to disable the service %s. (sc config)', service_name)
else:
self.logger.info('Successfully disabled the service %s. (sc config)', service_name)
else:
self.logger.info('Successfully disabled the service %s.', service_name)
service_status = self.query_service_status_ex(service_handle)
if service_status:
if service_status.dwCurrentState != SERVICE_STOPPED:
# Send a stop code to the service
if self.control_service(service_handle, dwControl):
# Wait for the service to stop
while timeout:
timeout -= 1
time.sleep(1)
service_status = self.query_service_status_ex(service_handle)
if service_status.dwCurrentState == SERVICE_STOPPED:
self.logger.info('Successfully stopped the service %s.', service_name)
break
else:
self.logger.error('Timed out while trying to stop the service %s.', service_name)
else:
self.logger.error('Failed to stop the service %s.', service_name)
else:
self.logger.error('Service %s is already stopped.', service_name)
# As a backup call net stop
if service_status.dwCurrentState != SERVICE_STOPPED:
try:
subprocess.check_call("net stop %s" % service_name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError, e:
self.logger.error('Failed to stop the service %s. (net stop)', service_name)
else:
self.logger.info('Successfully stopped the service %s.', service_name)
self.close_service_handle(service_handle)
self.close_service_handle(sc_handle)
###########################################################################
# Process related functions
###########################################################################
###########################################################################
# The GetExtendedTcpTable function retrieves a table that contains a list of TCP endpoints available to the application.
#
# DWORD GetExtendedTcpTable(
# _Out_ PVOID pTcpTable,
# _Inout_ PDWORD pdwSize,
# _In_ BOOL bOrder,
# _In_ ULONG ulAf,
# _In_ TCP_TABLE_CLASS TableClass,
# _In_ ULONG Reserved
# );
def get_extended_tcp_table(self):
dwSize = DWORD(sizeof(MIB_TCPROW_OWNER_PID) * 512 + 4)
TcpTable = MIB_TCPTABLE_OWNER_PID()
if windll.iphlpapi.GetExtendedTcpTable(byref(TcpTable), byref(dwSize), False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != NO_ERROR:
self.logger.error("Failed to call GetExtendedTcpTable")
return
for item in TcpTable.table[:TcpTable.dwNumEntries]:
yield item
def get_pid_port_tcp(self, port):
for item in self.get_extended_tcp_table():
lPort = socket.ntohs(item.dwLocalPort)
lAddr = socket.inet_ntoa(struct.pack('L', item.dwLocalAddr))
pid = item.dwOwningPid
if lPort == port:
return pid
else:
return None
#################################################################################
# The GetExtendedUdpTable function retrieves a table that contains a list of UDP endpoints available to the application.
#
# DWORD GetExtendedUdpTable(
# _Out_ PVOID pUdpTable,
# _Inout_ PDWORD pdwSize,
# _In_ BOOL bOrder,
# _In_ ULONG ulAf,
# _In_ UDP_TABLE_CLASS TableClass,
# _In_ ULONG Reserved
# );
def get_extended_udp_table(self):
dwSize = DWORD(sizeof(MIB_UDPROW_OWNER_PID) * 512 + 4)
UdpTable = MIB_UDPTABLE_OWNER_PID()
if windll.iphlpapi.GetExtendedUdpTable(byref(UdpTable), byref(dwSize), False, AF_INET, UDP_TABLE_OWNER_PID, 0) != NO_ERROR:
self.logger.error("Failed to call GetExtendedUdpTable")
return
for item in UdpTable.table[:UdpTable.dwNumEntries]:
yield item
def get_pid_port_udp(self, port):
for item in self.get_extended_udp_table():
lPort = socket.ntohs(item.dwLocalPort)
lAddr = socket.inet_ntoa(struct.pack('L', item.dwLocalAddr))
pid = item.dwOwningPid
if lPort == port:
return pid
else:
return None
###############################################################################
# Retrieves the name of the executable file for the specified process.
#
# DWORD WINAPI GetProcessImageFileName(
# _In_ HANDLE hProcess,
# _Out_ LPTSTR lpImageFileName,
# _In_ DWORD nSize
# );
def get_process_image_filename(self, pid):
process_name = None
hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if hProcess:
lpImageFileName = create_string_buffer(MAX_PATH)
if windll.psapi.GetProcessImageFileNameA(hProcess, lpImageFileName, MAX_PATH) > 0:
process_name = os.path.basename(lpImageFileName.value)
else:
self.logger.error('Failed to call GetProcessImageFileNameA')
windll.kernel32.CloseHandle(hProcess)
return process_name
###############################################################################
# The GetAdaptersAddresses function retrieves the addresses associated with the adapters on the local computer.
#
# ULONG WINAPI GetAdaptersAddresses(
# _In_ ULONG Family,
# _In_ ULONG Flags,
# _In_ PVOID Reserved,
# _Inout_ PIP_ADAPTER_ADDRESSES AdapterAddresses,
# _Inout_ PULONG SizePointer
# );
def get_adapters_addresses(self):
Size = ULONG(0)
windll.iphlpapi.GetAdaptersAddresses(AF_INET, 0, None, None, byref(Size))
AdapterAddresses = create_string_buffer(Size.value)
pAdapterAddresses = cast(AdapterAddresses, POINTER(IP_ADAPTER_ADDRESSES))
if not windll.iphlpapi.GetAdaptersAddresses(AF_INET, 0, None, pAdapterAddresses, byref(Size)) == NO_ERROR:
self.logger.error('Failed calling GetAdaptersAddresses')
return
while pAdapterAddresses:
yield pAdapterAddresses.contents
pAdapterAddresses = pAdapterAddresses.contents.Next
def get_active_ethernet_adapters(self):
for adapter in self.get_adapters_addresses():
if adapter.IfType == MIB_IF_TYPE_ETHERNET and adapter.OperStatus == IFOPERSTATUSUP:
yield adapter
def check_active_ethernet_adapters(self):
for adapter in self.get_adapters_addresses():
if adapter.IfType == MIB_IF_TYPE_ETHERNET and adapter.OperStatus == IFOPERSTATUSUP:
return True
else:
return False
def get_adapter_friendlyname(self, if_index):
for adapter in self.get_adapters_addresses():
if adapter.IfIndex == if_index:
return adapter.FriendlyName
else:
return None
###########################################################################
# The GetAdaptersInfo function retrieves adapter information for the local computer.
#
# On Windows XP and later: Use the GetAdaptersAddresses function instead of GetAdaptersInfo.
#
# DWORD GetAdaptersInfo(
# _Out_ PIP_ADAPTER_INFO pAdapterInfo,
# _Inout_ PULONG pOutBufLen
# );
def get_adapters_info(self):
OutBufLen = DWORD(0)
windll.iphlpapi.GetAdaptersInfo(None, byref(OutBufLen))
AdapterInfo = create_string_buffer(OutBufLen.value)
pAdapterInfo = cast(AdapterInfo, POINTER(IP_ADAPTER_INFO))
if not windll.iphlpapi.GetAdaptersInfo(byref(AdapterInfo), byref(OutBufLen)) == NO_ERROR:
self.logger.error('Failed calling GetAdaptersInfo')
return
while pAdapterInfo:
yield pAdapterInfo.contents
pAdapterInfo = pAdapterInfo.contents.Next
def get_gateways(self, adapter):
gateway = adapter.GatewayList
while gateway:
yield gateway.IpAddress.String
gateway = gateway.Next
def get_ipaddresses(self, adapter):
ipaddress = adapter.IpAddressList
while ipaddress:
yield ipaddress.IpAddress.String
ipaddress = ipaddress.Next
def get_ipaddresses_netmask(self, adapter):
ipaddress = adapter.IpAddressList
while ipaddress:
yield (ipaddress.IpAddress.String, ipaddress.IpMask.String)
ipaddress = ipaddress.Next
def get_ipaddresses_index(self, index):
for adapter in self.get_adapters_info():
if adapter.Index == index:
return self.get_ipaddresses(adapter)
def check_gateways(self):
for adapter in self.get_adapters_info():
for gateway in self.get_gateways(adapter):
if gateway != '0.0.0.0':
return True
else:
return False
def get_ip_with_gateway(self):
for adapter in self.get_adapters_info():
for gateway in self.get_gateways(adapter):
if gateway != '0.0.0.0':
return self.get_ipaddresses(adapter).next()
else:
return None
def check_ipaddresses_interface(self, adapter):
for ipaddress in self.get_ipaddresses(adapter):
if ipaddress != '0.0.0.0':
return True
else:
return False
def check_ipaddresses(self):
for adapter in self.get_adapters_info():
if self.check_ipaddresses_interface(adapter):
return True
else:
return False
###########################################################################
# The GetNetworkParams function retrieves network parameters for the local computer.
#
# DWORD GetNetworkParams(
# _Out_ PFIXED_INFO pFixedInfo,
# _In_ PULONG pOutBufLen
# );
def get_network_params(self):
OutBufLen = ULONG(sizeof(FIXED_INFO))
FixedInfo = FIXED_INFO()
if not windll.iphlpapi.GetNetworkParams(byref(FixedInfo), byref(OutBufLen)) == NO_ERROR:
self.logger.error('Failed calling GetNetworkParams')
return None
return FixedInfo
def get_dns_servers(self):
FixedInfo = self.get_network_params()
if not FixedInfo:
return
ip_addr_string = FixedInfo.DnsServerList
while ip_addr_string:
yield ip_addr_string.IpAddress.String
ip_addr_string = ip_addr_string.Next
def check_dns_servers(self):
FixedInfo = self.get_network_params()
if not FixedInfo:
return
ip_addr_string = FixedInfo.DnsServerList
if ip_addr_string and ip_addr_string.IpAddress.String:
return True
else:
return False
###########################################################################
# The GetBestInterface function retrieves the index of the interface that has the best route to the specified IPv4 address.
#
# DWORD GetBestInterface(
# _In_ IPAddr dwDestAddr,
# _Out_ PDWORD pdwBestIfIndex
# );
def get_best_interface(self, ip='8.8.8.8'):
BestIfIndex = DWORD()
DestAddr = socket.inet_aton(ip)
if not windll.iphlpapi.GetBestInterface(DestAddr, byref(BestIfIndex)) == NO_ERROR:
self.logger.error('Failed calling GetBestInterface')
return None
return BestIfIndex.value
def check_best_interface(self, ip='8.8.8.8'):
BestIfIndex = DWORD()
DestAddr = socket.inet_aton(ip)
if not windll.iphlpapi.GetBestInterface(DestAddr, byref(BestIfIndex)) == NO_ERROR:
return False
return True
# Return the best local IP address to reach defined IP address
def get_best_ipaddress(self, ip='8.8.8.8'):
index = self.get_best_interface(ip)
if index != None:
addresses = self.get_ipaddresses_index(index)
for address in addresses:
return address
else:
return None
else:
return None
###########################################################################
# Convert interface index to name
#
# NETIO_STATUS WINAPI ConvertInterfaceIndexToLuid(
# _In_ NET_IFINDEX InterfaceIndex,
# _Out_ PNET_LUID InterfaceLuid
# );
#
# NETIO_STATUS WINAPI ConvertInterfaceLuidToNameA(
# _In_ const NET_LUID *InterfaceLuid,
# _Out_ PSTR InterfaceName,
# _In_ SIZE_T Length
# );
def convert_interface_index_to_name(self, index):
InterfaceLuid = ULONG64()
if not windll.iphlpapi.ConvertInterfaceIndexToLuid(index, byref(InterfaceLuid)) == NO_ERROR:
self.logger.error('Failed calling ConvertInterfaceIndexToLuid')
return None
InterfaceName = create_string_buffer(NDIS_IF_MAX_STRING_SIZE + 1)
if not windll.iphlpapi.ConvertInterfaceLuidToNameA(byref(InterfaceLuid), InterfaceName, NDIS_IF_MAX_STRING_SIZE + 1) == NO_ERROR:
self.logger.error('Failed calling ConvertInterfaceLuidToName')
return None
return InterfaceName.value
###########################################################################
# DnsFlushResolverCache
#
# DWORD APIENTRY DhcpNotifyConfigChange(
# LPWSTR lpwszServerName,
# LPWSTR lpwszAdapterName,
# BOOL fIsNewIPAddress,
# DWORD dwIPIndex,
# DWORD dwIPAddress,
# DWORD dwSubnetMask,
# int nServiceEnable );
def notify_ip_change(self, adapter_name):
if windll.dhcpcsvc.DhcpNotifyConfigChange(0, adapter_name, 0, 0, 0, 0, 0) == NO_ERROR:
self.logger.debug('Successfully performed adapter change notification on %s', adapter_name)
else:
self.logger.error('Failed to notify adapter change on %s', adapter_name)