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 Wrapper for advapi32.dll in ctypes.
33 """
34
35 __revision__ = "$Id: advapi32.py 1299 2013-12-20 09:30:55Z qvasimodo $"
36
37 from defines import *
38 from kernel32 import *
39
40
41
42
43
44
45 _all = None
46 _all = set(vars().keys())
47
48
49
50
51
52 SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"
53 SE_AUDIT_NAME = "SeAuditPrivilege"
54 SE_BACKUP_NAME = "SeBackupPrivilege"
55 SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"
56 SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege"
57 SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"
58 SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"
59 SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege"
60 SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"
61 SE_DEBUG_NAME = "SeDebugPrivilege"
62 SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege"
63 SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"
64 SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"
65 SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"
66 SE_INC_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege"
67 SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"
68 SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"
69 SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"
70 SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege"
71 SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"
72 SE_RELABEL_NAME = "SeRelabelPrivilege"
73 SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"
74 SE_RESTORE_NAME = "SeRestorePrivilege"
75 SE_SECURITY_NAME = "SeSecurityPrivilege"
76 SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
77 SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege"
78 SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"
79 SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"
80 SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"
81 SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
82 SE_TCB_NAME = "SeTcbPrivilege"
83 SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"
84 SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"
85 SE_UNDOCK_NAME = "SeUndockPrivilege"
86 SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"
87
88 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001
89 SE_PRIVILEGE_ENABLED = 0x00000002
90 SE_PRIVILEGE_REMOVED = 0x00000004
91 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
92
93 TOKEN_ADJUST_PRIVILEGES = 0x00000020
94
95 LOGON_WITH_PROFILE = 0x00000001
96 LOGON_NETCREDENTIALS_ONLY = 0x00000002
97
98
99 TOKEN_ASSIGN_PRIMARY = 0x0001
100 TOKEN_DUPLICATE = 0x0002
101 TOKEN_IMPERSONATE = 0x0004
102 TOKEN_QUERY = 0x0008
103 TOKEN_QUERY_SOURCE = 0x0010
104 TOKEN_ADJUST_PRIVILEGES = 0x0020
105 TOKEN_ADJUST_GROUPS = 0x0040
106 TOKEN_ADJUST_DEFAULT = 0x0080
107 TOKEN_ADJUST_SESSIONID = 0x0100
108 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY)
109 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
110 TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
111 TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
112 TOKEN_ADJUST_SESSIONID)
113
114
115 HKEY_CLASSES_ROOT = 0x80000000
116 HKEY_CURRENT_USER = 0x80000001
117 HKEY_LOCAL_MACHINE = 0x80000002
118 HKEY_USERS = 0x80000003
119 HKEY_PERFORMANCE_DATA = 0x80000004
120 HKEY_CURRENT_CONFIG = 0x80000005
121
122
123 KEY_ALL_ACCESS = 0xF003F
124 KEY_CREATE_LINK = 0x0020
125 KEY_CREATE_SUB_KEY = 0x0004
126 KEY_ENUMERATE_SUB_KEYS = 0x0008
127 KEY_EXECUTE = 0x20019
128 KEY_NOTIFY = 0x0010
129 KEY_QUERY_VALUE = 0x0001
130 KEY_READ = 0x20019
131 KEY_SET_VALUE = 0x0002
132 KEY_WOW64_32KEY = 0x0200
133 KEY_WOW64_64KEY = 0x0100
134 KEY_WRITE = 0x20006
135
136
137 REG_NONE = 0
138 REG_SZ = 1
139 REG_EXPAND_SZ = 2
140 REG_BINARY = 3
141 REG_DWORD = 4
142 REG_DWORD_LITTLE_ENDIAN = REG_DWORD
143 REG_DWORD_BIG_ENDIAN = 5
144 REG_LINK = 6
145 REG_MULTI_SZ = 7
146 REG_RESOURCE_LIST = 8
147 REG_FULL_RESOURCE_DESCRIPTOR = 9
148 REG_RESOURCE_REQUIREMENTS_LIST = 10
149 REG_QWORD = 11
150 REG_QWORD_LITTLE_ENDIAN = REG_QWORD
151
152
153
154
155
156
157
158
159 -class LUID(Structure):
160 _fields_ = [
161 ("LowPart", DWORD),
162 ("HighPart", LONG),
163 ]
164
165 PLUID = POINTER(LUID)
173 _fields_ = [
174 ("Luid", LUID),
175 ("Attributes", DWORD),
176 ]
177
189
190
191 PTOKEN_PRIVILEGES = POINTER(TOKEN_PRIVILEGES)
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 TOKEN_INFORMATION_CLASS = ctypes.c_int
240
241 TokenUser = 1
242 TokenGroups = 2
243 TokenPrivileges = 3
244 TokenOwner = 4
245 TokenPrimaryGroup = 5
246 TokenDefaultDacl = 6
247 TokenSource = 7
248 TokenType = 8
249 TokenImpersonationLevel = 9
250 TokenStatistics = 10
251 TokenRestrictedSids = 11
252 TokenSessionId = 12
253 TokenGroupsAndPrivileges = 13
254 TokenSessionReference = 14
255 TokenSandBoxInert = 15
256 TokenAuditPolicy = 16
257 TokenOrigin = 17
258 TokenElevationType = 18
259 TokenLinkedToken = 19
260 TokenElevation = 20
261 TokenHasRestrictions = 21
262 TokenAccessInformation = 22
263 TokenVirtualizationAllowed = 23
264 TokenVirtualizationEnabled = 24
265 TokenIntegrityLevel = 25
266 TokenUIAccess = 26
267 TokenMandatoryPolicy = 27
268 TokenLogonSid = 28
269 TokenIsAppContainer = 29
270 TokenCapabilities = 30
271 TokenAppContainerSid = 31
272 TokenAppContainerNumber = 32
273 TokenUserClaimAttributes = 33
274 TokenDeviceClaimAttributes = 34
275 TokenRestrictedUserClaimAttributes = 35
276 TokenRestrictedDeviceClaimAttributes = 36
277 TokenDeviceGroups = 37
278 TokenRestrictedDeviceGroups = 38
279 TokenSecurityAttributes = 39
280 TokenIsRestricted = 40
281 MaxTokenInfoClass = 41
282
283
284
285
286
287
288 TOKEN_TYPE = ctypes.c_int
289 PTOKEN_TYPE = POINTER(TOKEN_TYPE)
290
291 TokenPrimary = 1
292 TokenImpersonation = 2
293
294
295
296
297
298
299
300 TokenElevationTypeDefault = 1
301 TokenElevationTypeFull = 2
302 TokenElevationTypeLimited = 3
303
304 TOKEN_ELEVATION_TYPE = ctypes.c_int
305 PTOKEN_ELEVATION_TYPE = POINTER(TOKEN_ELEVATION_TYPE)
306
307
308
309
310
311
312
313
314 SecurityAnonymous = 0
315 SecurityIdentification = 1
316 SecurityImpersonation = 2
317 SecurityDelegation = 3
318
319 SECURITY_IMPERSONATION_LEVEL = ctypes.c_int
320 PSECURITY_IMPERSONATION_LEVEL = POINTER(SECURITY_IMPERSONATION_LEVEL)
327 _fields_ = [
328 ("Sid", PSID),
329 ("Attributes", DWORD),
330 ]
331 PSID_AND_ATTRIBUTES = POINTER(SID_AND_ATTRIBUTES)
340 PTOKEN_USER = POINTER(TOKEN_USER)
349 PTOKEN_MANDATORY_LABEL = POINTER(TOKEN_MANDATORY_LABEL)
355 _fields_ = [
356 ("Owner", PSID),
357 ]
358 PTOKEN_OWNER = POINTER(TOKEN_OWNER)
364 _fields_ = [
365 ("PrimaryGroup", PSID),
366 ]
367 PTOKEN_PRIMARY_GROUP = POINTER(TOKEN_PRIMARY_GROUP)
376 PTOKEN_APPCONTAINER_INFORMATION = POINTER(TOKEN_APPCONTAINER_INFORMATION)
382 _fields_ = [
383 ("OriginatingLogonSession", LUID),
384 ]
385 PTOKEN_ORIGIN = POINTER(TOKEN_ORIGIN)
391 _fields_ = [
392 ("LinkedToken", HANDLE),
393 ]
394 PTOKEN_LINKED_TOKEN = POINTER(TOKEN_LINKED_TOKEN)
395
396
397
398
399
400
401
402
403
404
405
406
407
408 -class TOKEN_STATISTICS(Structure):
409 _fields_ = [
410 ("TokenId", LUID),
411 ("AuthenticationId", LUID),
412 ("ExpirationTime", LONGLONG),
413 ("TokenType", TOKEN_TYPE),
414 ("ImpersonationLevel", SECURITY_IMPERSONATION_LEVEL),
415 ("DynamicCharged", DWORD),
416 ("DynamicAvailable", DWORD),
417 ("GroupCount", DWORD),
418 ("PrivilegeCount", DWORD),
419 ("ModifiedId", LUID),
420 ]
421 PTOKEN_STATISTICS = POINTER(TOKEN_STATISTICS)
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438 SidTypeUser = 1
439 SidTypeGroup = 2
440 SidTypeDomain = 3
441 SidTypeAlias = 4
442 SidTypeWellKnownGroup = 5
443 SidTypeDeletedAccount = 6
444 SidTypeInvalid = 7
445 SidTypeUnknown = 8
446 SidTypeComputer = 9
447 SidTypeLabel = 10
448
449
450
451 WCT_MAX_NODE_COUNT = 16
452 WCT_OBJNAME_LENGTH = 128
453 WCT_ASYNC_OPEN_FLAG = 1
454 WCTP_OPEN_ALL_FLAGS = WCT_ASYNC_OPEN_FLAG
455 WCT_OUT_OF_PROC_FLAG = 1
456 WCT_OUT_OF_PROC_COM_FLAG = 2
457 WCT_OUT_OF_PROC_CS_FLAG = 4
458 WCTP_GETINFO_ALL_FLAGS = WCT_OUT_OF_PROC_FLAG | WCT_OUT_OF_PROC_COM_FLAG | WCT_OUT_OF_PROC_CS_FLAG
459
460 HWCT = LPVOID
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477 WCT_OBJECT_TYPE = DWORD
478
479 WctCriticalSectionType = 1
480 WctSendMessageType = 2
481 WctMutexType = 3
482 WctAlpcType = 4
483 WctComType = 5
484 WctThreadWaitType = 6
485 WctProcessWaitType = 7
486 WctThreadType = 8
487 WctComActivationType = 9
488 WctUnknownType = 10
489 WctMaxType = 11
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506 WCT_OBJECT_STATUS = DWORD
507
508 WctStatusNoAccess = 1
509 WctStatusRunning = 2
510 WctStatusBlocked = 3
511 WctStatusPidOnly = 4
512 WctStatusPidOnlyRpcss = 5
513 WctStatusOwned = 6
514 WctStatusNotOwned = 7
515 WctStatusAbandoned = 8
516 WctStatusUnknown = 9
517 WctStatusError = 10
518 WctStatusMax = 11
544
546 _fields_ = [
547 ("ProcessId", DWORD),
548 ("ThreadId", DWORD),
549 ("WaitTime", DWORD),
550 ("ContextSwitches", DWORD),
551 ]
552
558
565
566 PWAITCHAIN_NODE_INFO = POINTER(WAITCHAIN_NODE_INFO)
569 """
570 Represents a node in the wait chain.
571
572 It's a wrapper on the L{WAITCHAIN_NODE_INFO} structure.
573
574 The following members are defined only
575 if the node is of L{WctThreadType} type:
576 - C{ProcessId}
577 - C{ThreadId}
578 - C{WaitTime}
579 - C{ContextSwitches}
580
581 @see: L{GetThreadWaitChain}
582
583 @type ObjectName: unicode
584 @ivar ObjectName: Object name. May be an empty string.
585
586 @type ObjectType: int
587 @ivar ObjectType: Object type.
588 Should be one of the following values:
589 - L{WctCriticalSectionType}
590 - L{WctSendMessageType}
591 - L{WctMutexType}
592 - L{WctAlpcType}
593 - L{WctComType}
594 - L{WctThreadWaitType}
595 - L{WctProcessWaitType}
596 - L{WctThreadType}
597 - L{WctComActivationType}
598 - L{WctUnknownType}
599
600 @type ObjectStatus: int
601 @ivar ObjectStatus: Wait status.
602 Should be one of the following values:
603 - L{WctStatusNoAccess} I{(ACCESS_DENIED for this object)}
604 - L{WctStatusRunning} I{(Thread status)}
605 - L{WctStatusBlocked} I{(Thread status)}
606 - L{WctStatusPidOnly} I{(Thread status)}
607 - L{WctStatusPidOnlyRpcss} I{(Thread status)}
608 - L{WctStatusOwned} I{(Dispatcher object status)}
609 - L{WctStatusNotOwned} I{(Dispatcher object status)}
610 - L{WctStatusAbandoned} I{(Dispatcher object status)}
611 - L{WctStatusUnknown} I{(All objects)}
612 - L{WctStatusError} I{(All objects)}
613
614 @type ProcessId: int
615 @ivar ProcessId: Process global ID.
616
617 @type ThreadId: int
618 @ivar ThreadId: Thread global ID.
619
620 @type WaitTime: int
621 @ivar WaitTime: Wait time.
622
623 @type ContextSwitches: int
624 @ivar ContextSwitches: Number of context switches.
625 """
626
627
628
629
630
631
632
633
634
646
650 """
651 Thread wait chain session handle.
652
653 Returned by L{OpenThreadWaitChainSession}.
654
655 @see: L{Handle}
656 """
657
665
670
672 raise NotImplementedError()
673
674 - def wait(self, dwMilliseconds = None):
675 raise NotImplementedError()
676
677 @property
680
681 @property
684
685
686
687 SAFER_LEVEL_HANDLE = HANDLE
688
689 SAFER_SCOPEID_MACHINE = 1
690 SAFER_SCOPEID_USER = 2
691
692 SAFER_LEVEL_OPEN = 1
693
694 SAFER_LEVELID_DISALLOWED = 0x00000
695 SAFER_LEVELID_UNTRUSTED = 0x01000
696 SAFER_LEVELID_CONSTRAINED = 0x10000
697 SAFER_LEVELID_NORMALUSER = 0x20000
698 SAFER_LEVELID_FULLYTRUSTED = 0x40000
699
700 SAFER_POLICY_INFO_CLASS = DWORD
701 SaferPolicyLevelList = 1
702 SaferPolicyEnableTransparentEnforcement = 2
703 SaferPolicyDefaultLevel = 3
704 SaferPolicyEvaluateUserScope = 4
705 SaferPolicyScopeFlags = 5
706
707 SAFER_TOKEN_NULL_IF_EQUAL = 1
708 SAFER_TOKEN_COMPARE_ONLY = 2
709 SAFER_TOKEN_MAKE_INERT = 4
710 SAFER_TOKEN_WANT_FLAGS = 8
711 SAFER_TOKEN_MASK = 15
712
713
714
715 SC_HANDLE = HANDLE
716
717 SERVICES_ACTIVE_DATABASEW = u"ServicesActive"
718 SERVICES_FAILED_DATABASEW = u"ServicesFailed"
719
720 SERVICES_ACTIVE_DATABASEA = "ServicesActive"
721 SERVICES_FAILED_DATABASEA = "ServicesFailed"
722
723 SC_GROUP_IDENTIFIERW = u'+'
724 SC_GROUP_IDENTIFIERA = '+'
725
726 SERVICE_NO_CHANGE = 0xffffffff
727
728
729 SC_STATUS_TYPE = ctypes.c_int
730 SC_STATUS_PROCESS_INFO = 0
731
732
733 SC_ENUM_TYPE = ctypes.c_int
734 SC_ENUM_PROCESS_INFO = 0
735
736
737
738
739 SERVICE_ALL_ACCESS = 0xF01FF
740 SERVICE_QUERY_CONFIG = 0x0001
741 SERVICE_CHANGE_CONFIG = 0x0002
742 SERVICE_QUERY_STATUS = 0x0004
743 SERVICE_ENUMERATE_DEPENDENTS = 0x0008
744 SERVICE_START = 0x0010
745 SERVICE_STOP = 0x0020
746 SERVICE_PAUSE_CONTINUE = 0x0040
747 SERVICE_INTERROGATE = 0x0080
748 SERVICE_USER_DEFINED_CONTROL = 0x0100
749
750 SC_MANAGER_ALL_ACCESS = 0xF003F
751 SC_MANAGER_CONNECT = 0x0001
752 SC_MANAGER_CREATE_SERVICE = 0x0002
753 SC_MANAGER_ENUMERATE_SERVICE = 0x0004
754 SC_MANAGER_LOCK = 0x0008
755 SC_MANAGER_QUERY_LOCK_STATUS = 0x0010
756 SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020
757
758
759 SERVICE_BOOT_START = 0x00000000
760 SERVICE_SYSTEM_START = 0x00000001
761 SERVICE_AUTO_START = 0x00000002
762 SERVICE_DEMAND_START = 0x00000003
763 SERVICE_DISABLED = 0x00000004
764
765
766 SERVICE_ERROR_IGNORE = 0x00000000
767 SERVICE_ERROR_NORMAL = 0x00000001
768 SERVICE_ERROR_SEVERE = 0x00000002
769 SERVICE_ERROR_CRITICAL = 0x00000003
770
771
772 SERVICE_ACTIVE = 1
773 SERVICE_INACTIVE = 2
774 SERVICE_STATE_ALL = 3
775
776
777 SERVICE_KERNEL_DRIVER = 0x00000001
778 SERVICE_FILE_SYSTEM_DRIVER = 0x00000002
779 SERVICE_ADAPTER = 0x00000004
780 SERVICE_RECOGNIZER_DRIVER = 0x00000008
781 SERVICE_WIN32_OWN_PROCESS = 0x00000010
782 SERVICE_WIN32_SHARE_PROCESS = 0x00000020
783 SERVICE_INTERACTIVE_PROCESS = 0x00000100
784
785
786 SERVICE_DRIVER = 0x0000000B
787 SERVICE_WIN32 = 0x00000030
788
789
790 SERVICE_STOPPED = 0x00000001
791 SERVICE_START_PENDING = 0x00000002
792 SERVICE_STOP_PENDING = 0x00000003
793 SERVICE_RUNNING = 0x00000004
794 SERVICE_CONTINUE_PENDING = 0x00000005
795 SERVICE_PAUSE_PENDING = 0x00000006
796 SERVICE_PAUSED = 0x00000007
797
798
799 SERVICE_ACCEPT_STOP = 0x00000001
800 SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002
801 SERVICE_ACCEPT_SHUTDOWN = 0x00000004
802 SERVICE_ACCEPT_PARAMCHANGE = 0x00000008
803 SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010
804 SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020
805 SERVICE_ACCEPT_POWEREVENT = 0x00000040
806 SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080
807 SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100
808
809
810 SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001
811
812
813 SERVICE_CONTROL_STOP = 0x00000001
814 SERVICE_CONTROL_PAUSE = 0x00000002
815 SERVICE_CONTROL_CONTINUE = 0x00000003
816 SERVICE_CONTROL_INTERROGATE = 0x00000004
817 SERVICE_CONTROL_SHUTDOWN = 0x00000005
818 SERVICE_CONTROL_PARAMCHANGE = 0x00000006
819 SERVICE_CONTROL_NETBINDADD = 0x00000007
820 SERVICE_CONTROL_NETBINDREMOVE = 0x00000008
821 SERVICE_CONTROL_NETBINDENABLE = 0x00000009
822 SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A
823 SERVICE_CONTROL_DEVICEEVENT = 0x0000000B
824 SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C
825 SERVICE_CONTROL_POWEREVENT = 0x0000000D
826 SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E
827
828
829 SERVICE_ACCEPT_STOP = 0x00000001
830 SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002
831 SERVICE_ACCEPT_SHUTDOWN = 0x00000004
832 SERVICE_ACCEPT_PARAMCHANGE = 0x00000008
833 SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010
834 SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020
835 SERVICE_ACCEPT_POWEREVENT = 0x00000040
836 SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080
837 SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100
838 SERVICE_ACCEPT_TIMECHANGE = 0x00000200
839 SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400
840 SERVICE_ACCEPT_USERMODEREBOOT = 0x00000800
841
842
843 SC_ACTION_NONE = 0
844 SC_ACTION_RESTART = 1
845 SC_ACTION_REBOOT = 2
846 SC_ACTION_RUN_COMMAND = 3
847
848
849 SERVICE_CONFIG_DESCRIPTION = 1
850 SERVICE_CONFIG_FAILURE_ACTIONS = 2
851
852
853
854
855
856
857
858
859
860
861 -class SERVICE_STATUS(Structure):
862 _fields_ = [
863 ("dwServiceType", DWORD),
864 ("dwCurrentState", DWORD),
865 ("dwControlsAccepted", DWORD),
866 ("dwWin32ExitCode", DWORD),
867 ("dwServiceSpecificExitCode", DWORD),
868 ("dwCheckPoint", DWORD),
869 ("dwWaitHint", DWORD),
870 ]
871 LPSERVICE_STATUS = POINTER(SERVICE_STATUS)
889 LPSERVICE_STATUS_PROCESS = POINTER(SERVICE_STATUS_PROCESS)
897 _fields_ = [
898 ("lpServiceName", LPSTR),
899 ("lpDisplayName", LPSTR),
900 ("ServiceStatus", SERVICE_STATUS),
901 ]
903 _fields_ = [
904 ("lpServiceName", LPWSTR),
905 ("lpDisplayName", LPWSTR),
906 ("ServiceStatus", SERVICE_STATUS),
907 ]
908 LPENUM_SERVICE_STATUSA = POINTER(ENUM_SERVICE_STATUSA)
909 LPENUM_SERVICE_STATUSW = POINTER(ENUM_SERVICE_STATUSW)
928 LPENUM_SERVICE_STATUS_PROCESSA = POINTER(ENUM_SERVICE_STATUS_PROCESSA)
929 LPENUM_SERVICE_STATUS_PROCESSW = POINTER(ENUM_SERVICE_STATUS_PROCESSW)
932 """
933 Wrapper for the L{SERVICE_STATUS} structure.
934 """
935
948
950 """
951 Wrapper for the L{SERVICE_STATUS_PROCESS} structure.
952 """
953
968
969 -class ServiceStatusEntry(object):
970 """
971 Service status entry returned by L{EnumServicesStatus}.
972 """
973
974 - def __init__(self, raw):
975 """
976 @type raw: L{ENUM_SERVICE_STATUSA} or L{ENUM_SERVICE_STATUSW}
977 @param raw: Raw structure for this service status entry.
978 """
979 self.ServiceName = raw.lpServiceName
980 self.DisplayName = raw.lpDisplayName
981 self.ServiceType = raw.ServiceStatus.dwServiceType
982 self.CurrentState = raw.ServiceStatus.dwCurrentState
983 self.ControlsAccepted = raw.ServiceStatus.dwControlsAccepted
984 self.Win32ExitCode = raw.ServiceStatus.dwWin32ExitCode
985 self.ServiceSpecificExitCode = raw.ServiceStatus.dwServiceSpecificExitCode
986 self.CheckPoint = raw.ServiceStatus.dwCheckPoint
987 self.WaitHint = raw.ServiceStatus.dwWaitHint
988
990 output = []
991 if self.ServiceType & SERVICE_INTERACTIVE_PROCESS:
992 output.append("Interactive service")
993 else:
994 output.append("Service")
995 if self.DisplayName:
996 output.append("\"%s\" (%s)" % (self.DisplayName, self.ServiceName))
997 else:
998 output.append("\"%s\"" % self.ServiceName)
999 if self.CurrentState == SERVICE_CONTINUE_PENDING:
1000 output.append("is about to continue.")
1001 elif self.CurrentState == SERVICE_PAUSE_PENDING:
1002 output.append("is pausing.")
1003 elif self.CurrentState == SERVICE_PAUSED:
1004 output.append("is paused.")
1005 elif self.CurrentState == SERVICE_RUNNING:
1006 output.append("is running.")
1007 elif self.CurrentState == SERVICE_START_PENDING:
1008 output.append("is starting.")
1009 elif self.CurrentState == SERVICE_STOP_PENDING:
1010 output.append("is stopping.")
1011 elif self.CurrentState == SERVICE_STOPPED:
1012 output.append("is stopped.")
1013 return " ".join(output)
1014
1016 """
1017 Service status entry returned by L{EnumServicesStatusEx}.
1018 """
1019
1020 - def __init__(self, raw):
1021 """
1022 @type raw: L{ENUM_SERVICE_STATUS_PROCESSA} or L{ENUM_SERVICE_STATUS_PROCESSW}
1023 @param raw: Raw structure for this service status entry.
1024 """
1025 self.ServiceName = raw.lpServiceName
1026 self.DisplayName = raw.lpDisplayName
1027 self.ServiceType = raw.ServiceStatusProcess.dwServiceType
1028 self.CurrentState = raw.ServiceStatusProcess.dwCurrentState
1029 self.ControlsAccepted = raw.ServiceStatusProcess.dwControlsAccepted
1030 self.Win32ExitCode = raw.ServiceStatusProcess.dwWin32ExitCode
1031 self.ServiceSpecificExitCode = raw.ServiceStatusProcess.dwServiceSpecificExitCode
1032 self.CheckPoint = raw.ServiceStatusProcess.dwCheckPoint
1033 self.WaitHint = raw.ServiceStatusProcess.dwWaitHint
1034 self.ProcessId = raw.ServiceStatusProcess.dwProcessId
1035 self.ServiceFlags = raw.ServiceStatusProcess.dwServiceFlags
1036
1037 - def __str__(self):
1038 output = []
1039 if self.ServiceType & SERVICE_INTERACTIVE_PROCESS:
1040 output.append("Interactive service ")
1041 else:
1042 output.append("Service ")
1043 if self.DisplayName:
1044 output.append("\"%s\" (%s)" % (self.DisplayName, self.ServiceName))
1045 else:
1046 output.append("\"%s\"" % self.ServiceName)
1047 if self.CurrentState == SERVICE_CONTINUE_PENDING:
1048 output.append(" is about to continue")
1049 elif self.CurrentState == SERVICE_PAUSE_PENDING:
1050 output.append(" is pausing")
1051 elif self.CurrentState == SERVICE_PAUSED:
1052 output.append(" is paused")
1053 elif self.CurrentState == SERVICE_RUNNING:
1054 output.append(" is running")
1055 elif self.CurrentState == SERVICE_START_PENDING:
1056 output.append(" is starting")
1057 elif self.CurrentState == SERVICE_STOP_PENDING:
1058 output.append(" is stopping")
1059 elif self.CurrentState == SERVICE_STOPPED:
1060 output.append(" is stopped")
1061 if self.ProcessId:
1062 output.append(" at process %d" % self.ProcessId)
1063 output.append(".")
1064 return "".join(output)
1065
1070 """
1071 Access token handle.
1072
1073 @see: L{Handle}
1074 """
1075 pass
1076
1078 """
1079 Registry key handle.
1080 """
1081
1082 _TYPE = HKEY
1083
1086
1088 """
1089 Safer level handle.
1090
1091 @see: U{http://msdn.microsoft.com/en-us/library/ms722425(VS.85).aspx}
1092 """
1093
1094 _TYPE = SAFER_LEVEL_HANDLE
1095
1098
1100 """
1101 Service handle.
1102
1103 @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684330(v=vs.85).aspx}
1104 """
1105
1106 _TYPE = SC_HANDLE
1107
1110
1112 """
1113 Service Control Manager (SCM) handle.
1114
1115 @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684323(v=vs.85).aspx}
1116 """
1117
1118 _TYPE = SC_HANDLE
1119
1122
1130 _GetUserNameA = windll.advapi32.GetUserNameA
1131 _GetUserNameA.argtypes = [LPSTR, LPDWORD]
1132 _GetUserNameA.restype = bool
1133
1134 nSize = DWORD(0)
1135 _GetUserNameA(None, byref(nSize))
1136 error = GetLastError()
1137 if error != ERROR_INSUFFICIENT_BUFFER:
1138 raise ctypes.WinError(error)
1139 lpBuffer = ctypes.create_string_buffer('', nSize.value + 1)
1140 success = _GetUserNameA(lpBuffer, byref(nSize))
1141 if not success:
1142 raise ctypes.WinError()
1143 return lpBuffer.value
1144
1146 _GetUserNameW = windll.advapi32.GetUserNameW
1147 _GetUserNameW.argtypes = [LPWSTR, LPDWORD]
1148 _GetUserNameW.restype = bool
1149
1150 nSize = DWORD(0)
1151 _GetUserNameW(None, byref(nSize))
1152 error = GetLastError()
1153 if error != ERROR_INSUFFICIENT_BUFFER:
1154 raise ctypes.WinError(error)
1155 lpBuffer = ctypes.create_unicode_buffer(u'', nSize.value + 1)
1156 success = _GetUserNameW(lpBuffer, byref(nSize))
1157 if not success:
1158 raise ctypes.WinError()
1159 return lpBuffer.value
1160
1161 GetUserName = DefaultStringType(GetUserNameA, GetUserNameW)
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184 -def LookupAccountSidA(lpSystemName, lpSid):
1185 _LookupAccountSidA = windll.advapi32.LookupAccountSidA
1186 _LookupAccountSidA.argtypes = [LPSTR, PSID, LPSTR, LPDWORD, LPSTR, LPDWORD, LPDWORD]
1187 _LookupAccountSidA.restype = bool
1188
1189 cchName = DWORD(0)
1190 cchReferencedDomainName = DWORD(0)
1191 peUse = DWORD(0)
1192 _LookupAccountSidA(lpSystemName, lpSid, None, byref(cchName), None, byref(cchReferencedDomainName), byref(peUse))
1193 error = GetLastError()
1194 if error != ERROR_INSUFFICIENT_BUFFER:
1195 raise ctypes.WinError(error)
1196 lpName = ctypes.create_string_buffer('', cchName + 1)
1197 lpReferencedDomainName = ctypes.create_string_buffer('', cchReferencedDomainName + 1)
1198 success = _LookupAccountSidA(lpSystemName, lpSid, lpName, byref(cchName), lpReferencedDomainName, byref(cchReferencedDomainName), byref(peUse))
1199 if not success:
1200 raise ctypes.WinError()
1201 return lpName.value, lpReferencedDomainName.value, peUse.value
1202
1204 _LookupAccountSidW = windll.advapi32.LookupAccountSidA
1205 _LookupAccountSidW.argtypes = [LPSTR, PSID, LPWSTR, LPDWORD, LPWSTR, LPDWORD, LPDWORD]
1206 _LookupAccountSidW.restype = bool
1207
1208 cchName = DWORD(0)
1209 cchReferencedDomainName = DWORD(0)
1210 peUse = DWORD(0)
1211 _LookupAccountSidW(lpSystemName, lpSid, None, byref(cchName), None, byref(cchReferencedDomainName), byref(peUse))
1212 error = GetLastError()
1213 if error != ERROR_INSUFFICIENT_BUFFER:
1214 raise ctypes.WinError(error)
1215 lpName = ctypes.create_unicode_buffer(u'', cchName + 1)
1216 lpReferencedDomainName = ctypes.create_unicode_buffer(u'', cchReferencedDomainName + 1)
1217 success = _LookupAccountSidW(lpSystemName, lpSid, lpName, byref(cchName), lpReferencedDomainName, byref(cchReferencedDomainName), byref(peUse))
1218 if not success:
1219 raise ctypes.WinError()
1220 return lpName.value, lpReferencedDomainName.value, peUse.value
1221
1222 LookupAccountSid = GuessStringType(LookupAccountSidA, LookupAccountSidW)
1229 _ConvertSidToStringSidA = windll.advapi32.ConvertSidToStringSidA
1230 _ConvertSidToStringSidA.argtypes = [PSID, LPSTR]
1231 _ConvertSidToStringSidA.restype = bool
1232 _ConvertSidToStringSidA.errcheck = RaiseIfZero
1233
1234 pStringSid = LPSTR()
1235 _ConvertSidToStringSidA(Sid, byref(pStringSid))
1236 try:
1237 StringSid = pStringSid.value
1238 finally:
1239 LocalFree(pStringSid)
1240 return StringSid
1241
1243 _ConvertSidToStringSidW = windll.advapi32.ConvertSidToStringSidW
1244 _ConvertSidToStringSidW.argtypes = [PSID, LPWSTR]
1245 _ConvertSidToStringSidW.restype = bool
1246 _ConvertSidToStringSidW.errcheck = RaiseIfZero
1247
1248 pStringSid = LPWSTR()
1249 _ConvertSidToStringSidW(Sid, byref(pStringSid))
1250 try:
1251 StringSid = pStringSid.value
1252 finally:
1253 LocalFree(pStringSid)
1254 return StringSid
1255
1256 ConvertSidToStringSid = DefaultStringType(ConvertSidToStringSidA, ConvertSidToStringSidW)
1263 _ConvertStringSidToSidA = windll.advapi32.ConvertStringSidToSidA
1264 _ConvertStringSidToSidA.argtypes = [LPSTR, PVOID]
1265 _ConvertStringSidToSidA.restype = bool
1266 _ConvertStringSidToSidA.errcheck = RaiseIfZero
1267
1268 Sid = PVOID()
1269 _ConvertStringSidToSidA(StringSid, ctypes.pointer(Sid))
1270 return Sid.value
1271
1273 _ConvertStringSidToSidW = windll.advapi32.ConvertStringSidToSidW
1274 _ConvertStringSidToSidW.argtypes = [LPWSTR, PVOID]
1275 _ConvertStringSidToSidW.restype = bool
1276 _ConvertStringSidToSidW.errcheck = RaiseIfZero
1277
1278 Sid = PVOID()
1279 _ConvertStringSidToSidW(StringSid, ctypes.pointer(Sid))
1280 return Sid.value
1281
1282 ConvertStringSidToSid = GuessStringType(ConvertStringSidToSidA, ConvertStringSidToSidW)
1288 _IsValidSid = windll.advapi32.IsValidSid
1289 _IsValidSid.argtypes = [PSID]
1290 _IsValidSid.restype = bool
1291 return _IsValidSid(pSid)
1292
1293
1294
1295
1296
1297 -def EqualSid(pSid1, pSid2):
1298 _EqualSid = windll.advapi32.EqualSid
1299 _EqualSid.argtypes = [PSID, PSID]
1300 _EqualSid.restype = bool
1301 return _EqualSid(pSid1, pSid2)
1302
1307 _GetLengthSid = windll.advapi32.GetLengthSid
1308 _GetLengthSid.argtypes = [PSID]
1309 _GetLengthSid.restype = DWORD
1310 return _GetLengthSid(pSid)
1311
1312
1313
1314
1315
1316
1317 -def CopySid(pSourceSid):
1318 _CopySid = windll.advapi32.CopySid
1319 _CopySid.argtypes = [DWORD, PVOID, PSID]
1320 _CopySid.restype = bool
1321 _CopySid.errcheck = RaiseIfZero
1322
1323 nDestinationSidLength = GetLengthSid(pSourceSid)
1324 DestinationSid = ctypes.create_string_buffer('', nDestinationSidLength)
1325 pDestinationSid = ctypes.cast(ctypes.pointer(DestinationSid), PVOID)
1326 _CopySid(nDestinationSidLength, pDestinationSid, pSourceSid)
1327 return ctypes.cast(pDestinationSid, PSID)
1328
1338
1353
1354
1355
1356
1357
1358
1359
1360 -def OpenThreadToken(ThreadHandle, DesiredAccess, OpenAsSelf = True):
1369
1384
1394 _DuplicateTokenEx = windll.advapi32.DuplicateTokenEx
1395 _DuplicateTokenEx.argtypes = [HANDLE, DWORD, LPSECURITY_ATTRIBUTES, SECURITY_IMPERSONATION_LEVEL, TOKEN_TYPE, PHANDLE]
1396 _DuplicateTokenEx.restype = bool
1397 _DuplicateTokenEx.errcheck = RaiseIfZero
1398
1399 DuplicateTokenHandle = HANDLE(INVALID_HANDLE_VALUE)
1400 _DuplicateTokenEx(hExistingToken, dwDesiredAccess, lpTokenAttributes, ImpersonationLevel, TokenType, byref(DuplicateTokenHandle))
1401 return TokenHandle(DuplicateTokenHandle.value)
1402
1414
1421 _LookupPrivilegeValueA = windll.advapi32.LookupPrivilegeValueA
1422 _LookupPrivilegeValueA.argtypes = [LPSTR, LPSTR, PLUID]
1423 _LookupPrivilegeValueA.restype = bool
1424 _LookupPrivilegeValueA.errcheck = RaiseIfZero
1425
1426 lpLuid = LUID()
1427 if not lpSystemName:
1428 lpSystemName = None
1429 _LookupPrivilegeValueA(lpSystemName, lpName, byref(lpLuid))
1430 return lpLuid
1431
1433 _LookupPrivilegeValueW = windll.advapi32.LookupPrivilegeValueW
1434 _LookupPrivilegeValueW.argtypes = [LPWSTR, LPWSTR, PLUID]
1435 _LookupPrivilegeValueW.restype = bool
1436 _LookupPrivilegeValueW.errcheck = RaiseIfZero
1437
1438 lpLuid = LUID()
1439 if not lpSystemName:
1440 lpSystemName = None
1441 _LookupPrivilegeValueW(lpSystemName, lpName, byref(lpLuid))
1442 return lpLuid
1443
1444 LookupPrivilegeValue = GuessStringType(LookupPrivilegeValueA, LookupPrivilegeValueW)
1454 _LookupPrivilegeNameA = windll.advapi32.LookupPrivilegeNameA
1455 _LookupPrivilegeNameA.argtypes = [LPSTR, PLUID, LPSTR, LPDWORD]
1456 _LookupPrivilegeNameA.restype = bool
1457 _LookupPrivilegeNameA.errcheck = RaiseIfZero
1458
1459 cchName = DWORD(0)
1460 _LookupPrivilegeNameA(lpSystemName, byref(lpLuid), NULL, byref(cchName))
1461 lpName = ctypes.create_string_buffer("", cchName.value)
1462 _LookupPrivilegeNameA(lpSystemName, byref(lpLuid), byref(lpName), byref(cchName))
1463 return lpName.value
1464
1466 _LookupPrivilegeNameW = windll.advapi32.LookupPrivilegeNameW
1467 _LookupPrivilegeNameW.argtypes = [LPWSTR, PLUID, LPWSTR, LPDWORD]
1468 _LookupPrivilegeNameW.restype = bool
1469 _LookupPrivilegeNameW.errcheck = RaiseIfZero
1470
1471 cchName = DWORD(0)
1472 _LookupPrivilegeNameW(lpSystemName, byref(lpLuid), NULL, byref(cchName))
1473 lpName = ctypes.create_unicode_buffer(u"", cchName.value)
1474 _LookupPrivilegeNameW(lpSystemName, byref(lpLuid), byref(lpName), byref(cchName))
1475 return lpName.value
1476
1477 LookupPrivilegeName = GuessStringType(LookupPrivilegeNameA, LookupPrivilegeNameW)
1488 _AdjustTokenPrivileges = windll.advapi32.AdjustTokenPrivileges
1489 _AdjustTokenPrivileges.argtypes = [HANDLE, BOOL, LPVOID, DWORD, LPVOID, LPVOID]
1490 _AdjustTokenPrivileges.restype = bool
1491 _AdjustTokenPrivileges.errcheck = RaiseIfZero
1492
1493
1494
1495
1496
1497
1498
1499 if not NewState:
1500 _AdjustTokenPrivileges(TokenHandle, TRUE, NULL, 0, NULL, NULL)
1501 else:
1502 success = True
1503 for (privilege, enabled) in NewState:
1504 if not isinstance(privilege, LUID):
1505 privilege = LookupPrivilegeValue(NULL, privilege)
1506 if enabled == True:
1507 flags = SE_PRIVILEGE_ENABLED
1508 elif enabled == False:
1509 flags = SE_PRIVILEGE_REMOVED
1510 elif enabled == None:
1511 flags = 0
1512 else:
1513 flags = enabled
1514 laa = LUID_AND_ATTRIBUTES(privilege, flags)
1515 tp = TOKEN_PRIVILEGES(1, laa)
1516 _AdjustTokenPrivileges(TokenHandle, FALSE, byref(tp), sizeof(tp), NULL, NULL)
1517
1610
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646 -def CreateProcessWithLogonW(lpUsername = None, lpDomain = None, lpPassword = None, dwLogonFlags = 0, lpApplicationName = None, lpCommandLine = None, dwCreationFlags = 0, lpEnvironment = None, lpCurrentDirectory = None, lpStartupInfo = None):
1647 _CreateProcessWithLogonW = windll.advapi32.CreateProcessWithLogonW
1648 _CreateProcessWithLogonW.argtypes = [LPWSTR, LPWSTR, LPWSTR, DWORD, LPWSTR, LPWSTR, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
1649 _CreateProcessWithLogonW.restype = bool
1650 _CreateProcessWithLogonW.errcheck = RaiseIfZero
1651
1652 if not lpUsername:
1653 lpUsername = None
1654 if not lpDomain:
1655 lpDomain = None
1656 if not lpPassword:
1657 lpPassword = None
1658 if not lpApplicationName:
1659 lpApplicationName = None
1660 if not lpCommandLine:
1661 lpCommandLine = None
1662 else:
1663 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
1664 if not lpEnvironment:
1665 lpEnvironment = None
1666 else:
1667 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
1668 if not lpCurrentDirectory:
1669 lpCurrentDirectory = None
1670 if not lpStartupInfo:
1671 lpStartupInfo = STARTUPINFOW()
1672 lpStartupInfo.cb = sizeof(STARTUPINFOW)
1673 lpStartupInfo.lpReserved = 0
1674 lpStartupInfo.lpDesktop = 0
1675 lpStartupInfo.lpTitle = 0
1676 lpStartupInfo.dwFlags = 0
1677 lpStartupInfo.cbReserved2 = 0
1678 lpStartupInfo.lpReserved2 = 0
1679 lpProcessInformation = PROCESS_INFORMATION()
1680 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
1681 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
1682 lpProcessInformation.dwProcessId = 0
1683 lpProcessInformation.dwThreadId = 0
1684 _CreateProcessWithLogonW(lpUsername, lpDomain, lpPassword, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
1685 return ProcessInformation(lpProcessInformation)
1686
1687 CreateProcessWithLogonA = MakeANSIVersion(CreateProcessWithLogonW)
1688 CreateProcessWithLogon = DefaultStringType(CreateProcessWithLogonA, CreateProcessWithLogonW)
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701 -def CreateProcessWithTokenW(hToken = None, dwLogonFlags = 0, lpApplicationName = None, lpCommandLine = None, dwCreationFlags = 0, lpEnvironment = None, lpCurrentDirectory = None, lpStartupInfo = None):
1702 _CreateProcessWithTokenW = windll.advapi32.CreateProcessWithTokenW
1703 _CreateProcessWithTokenW.argtypes = [HANDLE, DWORD, LPWSTR, LPWSTR, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
1704 _CreateProcessWithTokenW.restype = bool
1705 _CreateProcessWithTokenW.errcheck = RaiseIfZero
1706
1707 if not hToken:
1708 hToken = None
1709 if not lpApplicationName:
1710 lpApplicationName = None
1711 if not lpCommandLine:
1712 lpCommandLine = None
1713 else:
1714 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
1715 if not lpEnvironment:
1716 lpEnvironment = None
1717 else:
1718 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
1719 if not lpCurrentDirectory:
1720 lpCurrentDirectory = None
1721 if not lpStartupInfo:
1722 lpStartupInfo = STARTUPINFOW()
1723 lpStartupInfo.cb = sizeof(STARTUPINFOW)
1724 lpStartupInfo.lpReserved = 0
1725 lpStartupInfo.lpDesktop = 0
1726 lpStartupInfo.lpTitle = 0
1727 lpStartupInfo.dwFlags = 0
1728 lpStartupInfo.cbReserved2 = 0
1729 lpStartupInfo.lpReserved2 = 0
1730 lpProcessInformation = PROCESS_INFORMATION()
1731 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
1732 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
1733 lpProcessInformation.dwProcessId = 0
1734 lpProcessInformation.dwThreadId = 0
1735 _CreateProcessWithTokenW(hToken, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
1736 return ProcessInformation(lpProcessInformation)
1737
1738 CreateProcessWithTokenA = MakeANSIVersion(CreateProcessWithTokenW)
1739 CreateProcessWithToken = DefaultStringType(CreateProcessWithTokenA, CreateProcessWithTokenW)
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754 -def CreateProcessAsUserA(hToken = None, lpApplicationName = None, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
1755 _CreateProcessAsUserA = windll.advapi32.CreateProcessAsUserA
1756 _CreateProcessAsUserA.argtypes = [HANDLE, LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION]
1757 _CreateProcessAsUserA.restype = bool
1758 _CreateProcessAsUserA.errcheck = RaiseIfZero
1759
1760 if not lpApplicationName:
1761 lpApplicationName = None
1762 if not lpCommandLine:
1763 lpCommandLine = None
1764 else:
1765 lpCommandLine = ctypes.create_string_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
1766 if not lpEnvironment:
1767 lpEnvironment = None
1768 else:
1769 lpEnvironment = ctypes.create_string_buffer(lpEnvironment)
1770 if not lpCurrentDirectory:
1771 lpCurrentDirectory = None
1772 if not lpProcessAttributes:
1773 lpProcessAttributes = None
1774 else:
1775 lpProcessAttributes = byref(lpProcessAttributes)
1776 if not lpThreadAttributes:
1777 lpThreadAttributes = None
1778 else:
1779 lpThreadAttributes = byref(lpThreadAttributes)
1780 if not lpStartupInfo:
1781 lpStartupInfo = STARTUPINFO()
1782 lpStartupInfo.cb = sizeof(STARTUPINFO)
1783 lpStartupInfo.lpReserved = 0
1784 lpStartupInfo.lpDesktop = 0
1785 lpStartupInfo.lpTitle = 0
1786 lpStartupInfo.dwFlags = 0
1787 lpStartupInfo.cbReserved2 = 0
1788 lpStartupInfo.lpReserved2 = 0
1789 lpProcessInformation = PROCESS_INFORMATION()
1790 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
1791 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
1792 lpProcessInformation.dwProcessId = 0
1793 lpProcessInformation.dwThreadId = 0
1794 _CreateProcessAsUserA(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
1795 return ProcessInformation(lpProcessInformation)
1796
1797 -def CreateProcessAsUserW(hToken = None, lpApplicationName = None, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
1798 _CreateProcessAsUserW = windll.advapi32.CreateProcessAsUserW
1799 _CreateProcessAsUserW.argtypes = [HANDLE, LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
1800 _CreateProcessAsUserW.restype = bool
1801 _CreateProcessAsUserW.errcheck = RaiseIfZero
1802
1803 if not lpApplicationName:
1804 lpApplicationName = None
1805 if not lpCommandLine:
1806 lpCommandLine = None
1807 else:
1808 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
1809 if not lpEnvironment:
1810 lpEnvironment = None
1811 else:
1812 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
1813 if not lpCurrentDirectory:
1814 lpCurrentDirectory = None
1815 if not lpProcessAttributes:
1816 lpProcessAttributes = None
1817 else:
1818 lpProcessAttributes = byref(lpProcessAttributes)
1819 if not lpThreadAttributes:
1820 lpThreadAttributes = None
1821 else:
1822 lpThreadAttributes = byref(lpThreadAttributes)
1823 if not lpStartupInfo:
1824 lpStartupInfo = STARTUPINFO()
1825 lpStartupInfo.cb = sizeof(STARTUPINFO)
1826 lpStartupInfo.lpReserved = 0
1827 lpStartupInfo.lpDesktop = 0
1828 lpStartupInfo.lpTitle = 0
1829 lpStartupInfo.dwFlags = 0
1830 lpStartupInfo.cbReserved2 = 0
1831 lpStartupInfo.lpReserved2 = 0
1832 lpProcessInformation = PROCESS_INFORMATION()
1833 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
1834 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
1835 lpProcessInformation.dwProcessId = 0
1836 lpProcessInformation.dwThreadId = 0
1837 _CreateProcessAsUserW(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
1838 return ProcessInformation(lpProcessInformation)
1839
1840 CreateProcessAsUser = GuessStringType(CreateProcessAsUserA, CreateProcessAsUserW)
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850 PWAITCHAINCALLBACK = WINFUNCTYPE(HWCT, DWORD_PTR, DWORD, LPDWORD, PWAITCHAIN_NODE_INFO, LPBOOL)
1866
1877 _GetThreadWaitChain = windll.advapi32.GetThreadWaitChain
1878 _GetThreadWaitChain.argtypes = [HWCT, LPDWORD, DWORD, DWORD, LPDWORD, PWAITCHAIN_NODE_INFO, LPBOOL]
1879 _GetThreadWaitChain.restype = bool
1880 _GetThreadWaitChain.errcheck = RaiseIfZero
1881
1882 dwNodeCount = DWORD(NodeCount)
1883 NodeInfoArray = (WAITCHAIN_NODE_INFO * NodeCount)()
1884 IsCycle = BOOL(0)
1885 _GetThreadWaitChain(WctHandle, Context, Flags, ThreadId, byref(dwNodeCount), ctypes.cast(ctypes.pointer(NodeInfoArray), PWAITCHAIN_NODE_INFO), byref(IsCycle))
1886 while dwNodeCount.value > NodeCount:
1887 NodeCount = dwNodeCount.value
1888 NodeInfoArray = (WAITCHAIN_NODE_INFO * NodeCount)()
1889 _GetThreadWaitChain(WctHandle, Context, Flags, ThreadId, byref(dwNodeCount), ctypes.cast(ctypes.pointer(NodeInfoArray), PWAITCHAIN_NODE_INFO), byref(IsCycle))
1890 return (
1891 [ WaitChainNodeInfo(NodeInfoArray[index]) for index in xrange(dwNodeCount.value) ],
1892 bool(IsCycle.value)
1893 )
1894
1902
1911 _SaferCreateLevel = windll.advapi32.SaferCreateLevel
1912 _SaferCreateLevel.argtypes = [DWORD, DWORD, DWORD, POINTER(SAFER_LEVEL_HANDLE), LPVOID]
1913 _SaferCreateLevel.restype = BOOL
1914 _SaferCreateLevel.errcheck = RaiseIfZero
1915
1916 hLevelHandle = SAFER_LEVEL_HANDLE(INVALID_HANDLE_VALUE)
1917 _SaferCreateLevel(dwScopeId, dwLevelId, OpenFlags, byref(hLevelHandle), None)
1918 return SaferLevelHandle(hLevelHandle.value)
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936 -def SaferComputeTokenFromLevel(LevelHandle, InAccessToken=None, dwFlags=0):
1946
1951 _SaferCloseLevel = windll.advapi32.SaferCloseLevel
1952 _SaferCloseLevel.argtypes = [SAFER_LEVEL_HANDLE]
1953 _SaferCloseLevel.restype = BOOL
1954 _SaferCloseLevel.errcheck = RaiseIfZero
1955
1956 if hasattr(hLevelHandle, 'value'):
1957 _SaferCloseLevel(hLevelHandle.value)
1958 else:
1959 _SaferCloseLevel(hLevelHandle)
1960
1973
1974
1975 SaferIsExecutableFileType = SaferiIsExecutableFileType
2003
2018
2028
2029 RegConnectRegistry = GuessStringType(RegConnectRegistryA, RegConnectRegistryW)
2045
2055
2056 RegCreateKey = GuessStringType(RegCreateKeyA, RegCreateKeyW)
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077 -def RegOpenKeyA(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None):
2086
2096
2097 RegOpenKey = GuessStringType(RegOpenKeyA, RegOpenKeyW)
2115
2125
2126 RegOpenKeyEx = GuessStringType(RegOpenKeyExA, RegOpenKeyExW)
2141
2157
2158
2159
2160
2161
2162
2163
2164 -def RegQueryValueA(hKey, lpSubKey = None):
2165 _RegQueryValueA = windll.advapi32.RegQueryValueA
2166 _RegQueryValueA.argtypes = [HKEY, LPSTR, LPVOID, PLONG]
2167 _RegQueryValueA.restype = LONG
2168 _RegQueryValueA.errcheck = RaiseIfNotErrorSuccess
2169
2170 cbValue = LONG(0)
2171 _RegQueryValueA(hKey, lpSubKey, None, byref(cbValue))
2172 lpValue = ctypes.create_string_buffer(cbValue.value)
2173 _RegQueryValueA(hKey, lpSubKey, lpValue, byref(cbValue))
2174 return lpValue.value
2175
2177 _RegQueryValueW = windll.advapi32.RegQueryValueW
2178 _RegQueryValueW.argtypes = [HKEY, LPWSTR, LPVOID, PLONG]
2179 _RegQueryValueW.restype = LONG
2180 _RegQueryValueW.errcheck = RaiseIfNotErrorSuccess
2181
2182 cbValue = LONG(0)
2183 _RegQueryValueW(hKey, lpSubKey, None, byref(cbValue))
2184 lpValue = ctypes.create_unicode_buffer(cbValue.value * sizeof(WCHAR))
2185 _RegQueryValueW(hKey, lpSubKey, lpValue, byref(cbValue))
2186 return lpValue.value
2187
2188 RegQueryValue = GuessStringType(RegQueryValueA, RegQueryValueW)
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198 -def _internal_RegQueryValueEx(ansi, hKey, lpValueName = None, bGetData = True):
2199 _RegQueryValueEx = _caller_RegQueryValueEx(ansi)
2200
2201 cbData = DWORD(0)
2202 dwType = DWORD(-1)
2203 _RegQueryValueEx(hKey, lpValueName, None, byref(dwType), None, byref(cbData))
2204 Type = dwType.value
2205
2206 if not bGetData:
2207 return cbData.value, Type
2208
2209 if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN):
2210 if cbData.value != 4:
2211 raise ValueError("REG_DWORD value of size %d" % cbData.value)
2212 dwData = DWORD(0)
2213 _RegQueryValueEx(hKey, lpValueName, None, None, byref(dwData), byref(cbData))
2214 return dwData.value, Type
2215
2216 if Type == REG_QWORD:
2217 if cbData.value != 8:
2218 raise ValueError("REG_QWORD value of size %d" % cbData.value)
2219 qwData = QWORD(0L)
2220 _RegQueryValueEx(hKey, lpValueName, None, None, byref(qwData), byref(cbData))
2221 return qwData.value, Type
2222
2223 if Type in (REG_SZ, REG_EXPAND_SZ):
2224 if ansi:
2225 szData = ctypes.create_string_buffer(cbData.value)
2226 else:
2227 szData = ctypes.create_unicode_buffer(cbData.value)
2228 _RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
2229 return szData.value, Type
2230
2231 if Type == REG_MULTI_SZ:
2232 if ansi:
2233 szData = ctypes.create_string_buffer(cbData.value)
2234 else:
2235 szData = ctypes.create_unicode_buffer(cbData.value)
2236 _RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
2237 Data = szData[:]
2238 if ansi:
2239 aData = Data.split('\0')
2240 else:
2241 aData = Data.split(u'\0')
2242 aData = [token for token in aData if token]
2243 return aData, Type
2244
2245 if Type == REG_LINK:
2246 szData = ctypes.create_unicode_buffer(cbData.value)
2247 _RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
2248 return szData.value, Type
2249
2250
2251 szData = ctypes.create_string_buffer(cbData.value)
2252 _RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
2253 return szData.raw, Type
2254
2256 if ansi:
2257 _RegQueryValueEx = windll.advapi32.RegQueryValueExA
2258 _RegQueryValueEx.argtypes = [HKEY, LPSTR, LPVOID, PDWORD, LPVOID, PDWORD]
2259 else:
2260 _RegQueryValueEx = windll.advapi32.RegQueryValueExW
2261 _RegQueryValueEx.argtypes = [HKEY, LPWSTR, LPVOID, PDWORD, LPVOID, PDWORD]
2262 _RegQueryValueEx.restype = LONG
2263 _RegQueryValueEx.errcheck = RaiseIfNotErrorSuccess
2264 return _RegQueryValueEx
2265
2269
2273
2274 RegQueryValueEx = GuessStringType(RegQueryValueExA, RegQueryValueExW)
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284 -def RegSetValueEx(hKey, lpValueName = None, lpData = None, dwType = None):
2285
2286
2287 if lpValueName is None:
2288 if isinstance(lpData, GuessStringType.t_ansi):
2289 ansi = True
2290 elif isinstance(lpData, GuessStringType.t_unicode):
2291 ansi = False
2292 else:
2293 ansi = (GuessStringType.t_ansi == GuessStringType.t_default)
2294 elif isinstance(lpValueName, GuessStringType.t_ansi):
2295 ansi = True
2296 elif isinstance(lpValueName, GuessStringType.t_unicode):
2297 ansi = False
2298 else:
2299 raise TypeError("String expected, got %s instead" % type(lpValueName))
2300
2301
2302
2303 if dwType is None:
2304 if lpValueName is None:
2305 dwType = REG_SZ
2306 elif lpData is None:
2307 dwType = REG_NONE
2308 elif isinstance(lpData, GuessStringType.t_ansi):
2309 dwType = REG_SZ
2310 elif isinstance(lpData, GuessStringType.t_unicode):
2311 dwType = REG_SZ
2312 elif isinstance(lpData, int):
2313 dwType = REG_DWORD
2314 elif isinstance(lpData, long):
2315 dwType = REG_QWORD
2316 else:
2317 dwType = REG_BINARY
2318
2319
2320 if ansi:
2321 _RegSetValueEx = windll.advapi32.RegSetValueExA
2322 _RegSetValueEx.argtypes = [HKEY, LPSTR, DWORD, DWORD, LPVOID, DWORD]
2323 else:
2324 _RegSetValueEx = windll.advapi32.RegSetValueExW
2325 _RegSetValueEx.argtypes = [HKEY, LPWSTR, DWORD, DWORD, LPVOID, DWORD]
2326 _RegSetValueEx.restype = LONG
2327 _RegSetValueEx.errcheck = RaiseIfNotErrorSuccess
2328
2329
2330 if lpData is None:
2331 DataRef = None
2332 DataSize = 0
2333 else:
2334 if dwType in (REG_DWORD, REG_DWORD_BIG_ENDIAN):
2335 Data = DWORD(lpData)
2336 elif dwType == REG_QWORD:
2337 Data = QWORD(lpData)
2338 elif dwType in (REG_SZ, REG_EXPAND_SZ):
2339 if ansi:
2340 Data = ctypes.create_string_buffer(lpData)
2341 else:
2342 Data = ctypes.create_unicode_buffer(lpData)
2343 elif dwType == REG_MULTI_SZ:
2344 if ansi:
2345 Data = ctypes.create_string_buffer('\0'.join(lpData) + '\0\0')
2346 else:
2347 Data = ctypes.create_unicode_buffer(u'\0'.join(lpData) + u'\0\0')
2348 elif dwType == REG_LINK:
2349 Data = ctypes.create_unicode_buffer(lpData)
2350 else:
2351 Data = ctypes.create_string_buffer(lpData)
2352 DataRef = byref(Data)
2353 DataSize = sizeof(Data)
2354
2355
2356 _RegSetValueEx(hKey, lpValueName, 0, dwType, DataRef, DataSize)
2357
2358
2359 RegSetValueExA = RegSetValueExW = RegSetValueEx
2360
2361
2362
2363
2364
2365
2366
2367 -def RegEnumKeyA(hKey, dwIndex):
2368 _RegEnumKeyA = windll.advapi32.RegEnumKeyA
2369 _RegEnumKeyA.argtypes = [HKEY, DWORD, LPSTR, DWORD]
2370 _RegEnumKeyA.restype = LONG
2371
2372 cchName = 1024
2373 while True:
2374 lpName = ctypes.create_string_buffer(cchName)
2375 errcode = _RegEnumKeyA(hKey, dwIndex, lpName, cchName)
2376 if errcode != ERROR_MORE_DATA:
2377 break
2378 cchName = cchName + 1024
2379 if cchName > 65536:
2380 raise ctypes.WinError(errcode)
2381 if errcode == ERROR_NO_MORE_ITEMS:
2382 return None
2383 if errcode != ERROR_SUCCESS:
2384 raise ctypes.WinError(errcode)
2385 return lpName.value
2386
2388 _RegEnumKeyW = windll.advapi32.RegEnumKeyW
2389 _RegEnumKeyW.argtypes = [HKEY, DWORD, LPWSTR, DWORD]
2390 _RegEnumKeyW.restype = LONG
2391
2392 cchName = 512
2393 while True:
2394 lpName = ctypes.create_unicode_buffer(cchName)
2395 errcode = _RegEnumKeyW(hKey, dwIndex, lpName, cchName * 2)
2396 if errcode != ERROR_MORE_DATA:
2397 break
2398 cchName = cchName + 512
2399 if cchName > 32768:
2400 raise ctypes.WinError(errcode)
2401 if errcode == ERROR_NO_MORE_ITEMS:
2402 return None
2403 if errcode != ERROR_SUCCESS:
2404 raise ctypes.WinError(errcode)
2405 return lpName.value
2406
2407 RegEnumKey = DefaultStringType(RegEnumKeyA, RegEnumKeyW)
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432 -def _internal_RegEnumValue(ansi, hKey, dwIndex, bGetData = True):
2433 if ansi:
2434 _RegEnumValue = windll.advapi32.RegEnumValueA
2435 _RegEnumValue.argtypes = [HKEY, DWORD, LPSTR, LPDWORD, LPVOID, LPDWORD, LPVOID, LPDWORD]
2436 else:
2437 _RegEnumValue = windll.advapi32.RegEnumValueW
2438 _RegEnumValue.argtypes = [HKEY, DWORD, LPWSTR, LPDWORD, LPVOID, LPDWORD, LPVOID, LPDWORD]
2439 _RegEnumValue.restype = LONG
2440
2441 cchValueName = DWORD(1024)
2442 dwType = DWORD(-1)
2443 lpcchValueName = byref(cchValueName)
2444 lpType = byref(dwType)
2445 if ansi:
2446 lpValueName = ctypes.create_string_buffer(cchValueName.value)
2447 else:
2448 lpValueName = ctypes.create_unicode_buffer(cchValueName.value)
2449 if bGetData:
2450 cbData = DWORD(0)
2451 lpcbData = byref(cbData)
2452 else:
2453 lpcbData = None
2454 lpData = None
2455 errcode = _RegEnumValue(hKey, dwIndex, lpValueName, lpcchValueName, None, lpType, lpData, lpcbData)
2456
2457 if errcode == ERROR_MORE_DATA or (bGetData and errcode == ERROR_SUCCESS):
2458 if ansi:
2459 cchValueName.value = cchValueName.value + sizeof(CHAR)
2460 lpValueName = ctypes.create_string_buffer(cchValueName.value)
2461 else:
2462 cchValueName.value = cchValueName.value + sizeof(WCHAR)
2463 lpValueName = ctypes.create_unicode_buffer(cchValueName.value)
2464
2465 if bGetData:
2466 Type = dwType.value
2467
2468 if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN):
2469 if cbData.value != sizeof(DWORD):
2470 raise ValueError("REG_DWORD value of size %d" % cbData.value)
2471 Data = DWORD(0)
2472
2473 elif Type == REG_QWORD:
2474 if cbData.value != sizeof(QWORD):
2475 raise ValueError("REG_QWORD value of size %d" % cbData.value)
2476 Data = QWORD(0L)
2477
2478 elif Type in (REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ):
2479 if ansi:
2480 Data = ctypes.create_string_buffer(cbData.value)
2481 else:
2482 Data = ctypes.create_unicode_buffer(cbData.value)
2483
2484 elif Type == REG_LINK:
2485 Data = ctypes.create_unicode_buffer(cbData.value)
2486
2487 else:
2488 Data = ctypes.create_string_buffer(cbData.value)
2489
2490 lpData = byref(Data)
2491
2492 errcode = _RegEnumValue(hKey, dwIndex, lpValueName, lpcchValueName, None, lpType, lpData, lpcbData)
2493
2494 if errcode == ERROR_NO_MORE_ITEMS:
2495 return None
2496
2497
2498
2499 if not bGetData:
2500 return lpValueName.value, dwType.value
2501
2502 if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD, REG_SZ, REG_EXPAND_SZ, REG_LINK):
2503 return lpValueName.value, dwType.value, Data.value
2504
2505 if Type == REG_MULTI_SZ:
2506 sData = Data[:]
2507 del Data
2508 if ansi:
2509 aData = sData.split('\0')
2510 else:
2511 aData = sData.split(u'\0')
2512 aData = [token for token in aData if token]
2513 return lpValueName.value, dwType.value, aData
2514
2515
2516 return lpValueName.value, dwType.value, Data.raw
2517
2520
2523
2524 RegEnumValue = DefaultStringType(RegEnumValueA, RegEnumValueW)
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553 -def RegDeleteValueA(hKeySrc, lpValueName = None):
2565 RegDeleteValue = GuessStringType(RegDeleteValueA, RegDeleteValueW)
2566
2567
2568
2569
2570
2571
2572 -def RegDeleteKeyValueA(hKeySrc, lpSubKey = None, lpValueName = None):
2573 _RegDeleteKeyValueA = windll.advapi32.RegDeleteKeyValueA
2574 _RegDeleteKeyValueA.argtypes = [HKEY, LPSTR, LPSTR]
2575 _RegDeleteKeyValueA.restype = LONG
2576 _RegDeleteKeyValueA.errcheck = RaiseIfNotErrorSuccess
2577 _RegDeleteKeyValueA(hKeySrc, lpSubKey, lpValueName)
2579 _RegDeleteKeyValueW = windll.advapi32.RegDeleteKeyValueW
2580 _RegDeleteKeyValueW.argtypes = [HKEY, LPWSTR, LPWSTR]
2581 _RegDeleteKeyValueW.restype = LONG
2582 _RegDeleteKeyValueW.errcheck = RaiseIfNotErrorSuccess
2583 _RegDeleteKeyValueW(hKeySrc, lpSubKey, lpValueName)
2584 RegDeleteKeyValue = GuessStringType(RegDeleteKeyValueA, RegDeleteKeyValueW)
2585
2586
2587
2588
2589
2590 -def RegDeleteKeyA(hKeySrc, lpSubKey = None):
2602 RegDeleteKey = GuessStringType(RegDeleteKeyA, RegDeleteKeyW)
2612 _RegDeleteKeyExA = windll.advapi32.RegDeleteKeyExA
2613 _RegDeleteKeyExA.argtypes = [HKEY, LPSTR, REGSAM, DWORD]
2614 _RegDeleteKeyExA.restype = LONG
2615 _RegDeleteKeyExA.errcheck = RaiseIfNotErrorSuccess
2616 _RegDeleteKeyExA(hKeySrc, lpSubKey, samDesired, 0)
2618 _RegDeleteKeyExW = windll.advapi32.RegDeleteKeyExW
2619 _RegDeleteKeyExW.argtypes = [HKEY, LPWSTR, REGSAM, DWORD]
2620 _RegDeleteKeyExW.restype = LONG
2621 _RegDeleteKeyExW.errcheck = RaiseIfNotErrorSuccess
2622 _RegDeleteKeyExW(hKeySrc, lpSubKey, samDesired, 0)
2623 RegDeleteKeyEx = GuessStringType(RegDeleteKeyExA, RegDeleteKeyExW)
2624
2625
2626
2627
2628
2629
2630 -def RegCopyTreeA(hKeySrc, lpSubKey, hKeyDest):
2642 RegCopyTree = GuessStringType(RegCopyTreeA, RegCopyTreeW)
2660 RegDeleteTree = GuessStringType(RegDeleteTreeA, RegDeleteTreeW)
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689 -def CloseServiceHandle(hSCObject):
2690 _CloseServiceHandle = windll.advapi32.CloseServiceHandle
2691 _CloseServiceHandle.argtypes = [SC_HANDLE]
2692 _CloseServiceHandle.restype = bool
2693 _CloseServiceHandle.errcheck = RaiseIfZero
2694
2695 if isinstance(hSCObject, Handle):
2696
2697 hSCObject.close()
2698 else:
2699 _CloseServiceHandle(hSCObject)
2700
2714
2716 _OpenSCManagerW = windll.advapi32.OpenSCManagerW
2717 _OpenSCManagerW.argtypes = [LPWSTR, LPWSTR, DWORD]
2718 _OpenSCManagerW.restype = SC_HANDLE
2719 _OpenSCManagerW.errcheck = RaiseIfZero
2720
2721 hSCObject = _OpenSCManagerA(lpMachineName, lpDatabaseName, dwDesiredAccess)
2722 return ServiceControlManagerHandle(hSCObject)
2723
2724 OpenSCManager = GuessStringType(OpenSCManagerA, OpenSCManagerW)
2737
2744
2745 OpenService = GuessStringType(OpenServiceA, OpenServiceW)
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762 -def CreateServiceA(hSCManager, lpServiceName,
2763 lpDisplayName = None,
2764 dwDesiredAccess = SERVICE_ALL_ACCESS,
2765 dwServiceType = SERVICE_WIN32_OWN_PROCESS,
2766 dwStartType = SERVICE_DEMAND_START,
2767 dwErrorControl = SERVICE_ERROR_NORMAL,
2768 lpBinaryPathName = None,
2769 lpLoadOrderGroup = None,
2770 lpDependencies = None,
2771 lpServiceStartName = None,
2772 lpPassword = None):
2773
2774 _CreateServiceA = windll.advapi32.CreateServiceA
2775 _CreateServiceA.argtypes = [SC_HANDLE, LPSTR, LPSTR, DWORD, DWORD, DWORD, DWORD, LPSTR, LPSTR, LPDWORD, LPSTR, LPSTR, LPSTR]
2776 _CreateServiceA.restype = SC_HANDLE
2777 _CreateServiceA.errcheck = RaiseIfZero
2778
2779 dwTagId = DWORD(0)
2780 hService = _CreateServiceA(hSCManager, lpServiceName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, byref(dwTagId), lpDependencies, lpServiceStartName, lpPassword)
2781 return ServiceHandle(hService), dwTagId.value
2782
2783 -def CreateServiceW(hSCManager, lpServiceName,
2784 lpDisplayName = None,
2785 dwDesiredAccess = SERVICE_ALL_ACCESS,
2786 dwServiceType = SERVICE_WIN32_OWN_PROCESS,
2787 dwStartType = SERVICE_DEMAND_START,
2788 dwErrorControl = SERVICE_ERROR_NORMAL,
2789 lpBinaryPathName = None,
2790 lpLoadOrderGroup = None,
2791 lpDependencies = None,
2792 lpServiceStartName = None,
2793 lpPassword = None):
2794
2795 _CreateServiceW = windll.advapi32.CreateServiceW
2796 _CreateServiceW.argtypes = [SC_HANDLE, LPWSTR, LPWSTR, DWORD, DWORD, DWORD, DWORD, LPWSTR, LPWSTR, LPDWORD, LPWSTR, LPWSTR, LPWSTR]
2797 _CreateServiceW.restype = SC_HANDLE
2798 _CreateServiceW.errcheck = RaiseIfZero
2799
2800 dwTagId = DWORD(0)
2801 hService = _CreateServiceW(hSCManager, lpServiceName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, byref(dwTagId), lpDependencies, lpServiceStartName, lpPassword)
2802 return ServiceHandle(hService), dwTagId.value
2803
2804 CreateService = GuessStringType(CreateServiceA, CreateServiceW)
2810 _DeleteService = windll.advapi32.DeleteService
2811 _DeleteService.argtypes = [SC_HANDLE]
2812 _DeleteService.restype = bool
2813 _DeleteService.errcheck = RaiseIfZero
2814 _DeleteService(hService)
2815
2837
2853
2854 GetServiceKeyName = GuessStringType(GetServiceKeyNameA, GetServiceKeyNameW)
2877
2893
2894 GetServiceDisplayName = GuessStringType(GetServiceDisplayNameA, GetServiceDisplayNameW)
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944 -def StartServiceA(hService, ServiceArgVectors = None):
2945 _StartServiceA = windll.advapi32.StartServiceA
2946 _StartServiceA.argtypes = [SC_HANDLE, DWORD, LPVOID]
2947 _StartServiceA.restype = bool
2948 _StartServiceA.errcheck = RaiseIfZero
2949
2950 if ServiceArgVectors:
2951 dwNumServiceArgs = len(ServiceArgVectors)
2952 CServiceArgVectors = (LPSTR * dwNumServiceArgs)(*ServiceArgVectors)
2953 lpServiceArgVectors = ctypes.pointer(CServiceArgVectors)
2954 else:
2955 dwNumServiceArgs = 0
2956 lpServiceArgVectors = None
2957 _StartServiceA(hService, dwNumServiceArgs, lpServiceArgVectors)
2958
2960 _StartServiceW = windll.advapi32.StartServiceW
2961 _StartServiceW.argtypes = [SC_HANDLE, DWORD, LPVOID]
2962 _StartServiceW.restype = bool
2963 _StartServiceW.errcheck = RaiseIfZero
2964
2965 if ServiceArgVectors:
2966 dwNumServiceArgs = len(ServiceArgVectors)
2967 CServiceArgVectors = (LPWSTR * dwNumServiceArgs)(*ServiceArgVectors)
2968 lpServiceArgVectors = ctypes.pointer(CServiceArgVectors)
2969 else:
2970 dwNumServiceArgs = 0
2971 lpServiceArgVectors = None
2972 _StartServiceW(hService, dwNumServiceArgs, lpServiceArgVectors)
2973
2974 StartService = GuessStringType(StartServiceA, StartServiceW)
2975
2976
2977
2978
2979
2980
2981 -def ControlService(hService, dwControl):
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012 -def QueryServiceStatus(hService):
3021
3030
3031 if InfoLevel != SC_STATUS_PROCESS_INFO:
3032 raise NotImplementedError()
3033
3034 _QueryServiceStatusEx = windll.advapi32.QueryServiceStatusEx
3035 _QueryServiceStatusEx.argtypes = [SC_HANDLE, SC_STATUS_TYPE, LPVOID, DWORD, LPDWORD]
3036 _QueryServiceStatusEx.restype = bool
3037 _QueryServiceStatusEx.errcheck = RaiseIfZero
3038
3039 lpBuffer = SERVICE_STATUS_PROCESS()
3040 cbBytesNeeded = DWORD(sizeof(lpBuffer))
3041 _QueryServiceStatusEx(hService, InfoLevel, byref(lpBuffer), sizeof(lpBuffer), byref(cbBytesNeeded))
3042 return ServiceStatusProcess(lpBuffer)
3043
3055 _EnumServicesStatusA = windll.advapi32.EnumServicesStatusA
3056 _EnumServicesStatusA.argtypes = [SC_HANDLE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD]
3057 _EnumServicesStatusA.restype = bool
3058
3059 cbBytesNeeded = DWORD(0)
3060 ServicesReturned = DWORD(0)
3061 ResumeHandle = DWORD(0)
3062
3063 _EnumServicesStatusA(hSCManager, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
3064
3065 Services = []
3066 success = False
3067 while GetLastError() == ERROR_MORE_DATA:
3068 if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUSA):
3069 break
3070 ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
3071 success = _EnumServicesStatusA(hSCManager, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
3072 if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUSA) * ServicesReturned.value):
3073 raise ctypes.WinError()
3074 lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUSA)
3075 for index in xrange(0, ServicesReturned.value):
3076 Services.append( ServiceStatusEntry(lpServicesArray[index]) )
3077 if success: break
3078 if not success:
3079 raise ctypes.WinError()
3080
3081 return Services
3082
3084 _EnumServicesStatusW = windll.advapi32.EnumServicesStatusW
3085 _EnumServicesStatusW.argtypes = [SC_HANDLE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD]
3086 _EnumServicesStatusW.restype = bool
3087
3088 cbBytesNeeded = DWORD(0)
3089 ServicesReturned = DWORD(0)
3090 ResumeHandle = DWORD(0)
3091
3092 _EnumServicesStatusW(hSCManager, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
3093
3094 Services = []
3095 success = False
3096 while GetLastError() == ERROR_MORE_DATA:
3097 if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUSW):
3098 break
3099 ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
3100 success = _EnumServicesStatusW(hSCManager, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
3101 if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUSW) * ServicesReturned.value):
3102 raise ctypes.WinError()
3103 lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUSW)
3104 for index in xrange(0, ServicesReturned.value):
3105 Services.append( ServiceStatusEntry(lpServicesArray[index]) )
3106 if success: break
3107 if not success:
3108 raise ctypes.WinError()
3109
3110 return Services
3111
3112 EnumServicesStatus = DefaultStringType(EnumServicesStatusA, EnumServicesStatusW)
3127
3128 if InfoLevel != SC_ENUM_PROCESS_INFO:
3129 raise NotImplementedError()
3130
3131 _EnumServicesStatusExA = windll.advapi32.EnumServicesStatusExA
3132 _EnumServicesStatusExA.argtypes = [SC_HANDLE, SC_ENUM_TYPE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD, LPSTR]
3133 _EnumServicesStatusExA.restype = bool
3134
3135 cbBytesNeeded = DWORD(0)
3136 ServicesReturned = DWORD(0)
3137 ResumeHandle = DWORD(0)
3138
3139 _EnumServicesStatusExA(hSCManager, InfoLevel, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
3140
3141 Services = []
3142 success = False
3143 while GetLastError() == ERROR_MORE_DATA:
3144 if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUS_PROCESSA):
3145 break
3146 ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
3147 success = _EnumServicesStatusExA(hSCManager, InfoLevel, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
3148 if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUS_PROCESSA) * ServicesReturned.value):
3149 raise ctypes.WinError()
3150 lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUS_PROCESSA)
3151 for index in xrange(0, ServicesReturned.value):
3152 Services.append( ServiceStatusProcessEntry(lpServicesArray[index]) )
3153 if success: break
3154 if not success:
3155 raise ctypes.WinError()
3156
3157 return Services
3158
3160 _EnumServicesStatusExW = windll.advapi32.EnumServicesStatusExW
3161 _EnumServicesStatusExW.argtypes = [SC_HANDLE, SC_ENUM_TYPE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD, LPWSTR]
3162 _EnumServicesStatusExW.restype = bool
3163
3164 if InfoLevel != SC_ENUM_PROCESS_INFO:
3165 raise NotImplementedError()
3166
3167 cbBytesNeeded = DWORD(0)
3168 ServicesReturned = DWORD(0)
3169 ResumeHandle = DWORD(0)
3170
3171 _EnumServicesStatusExW(hSCManager, InfoLevel, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
3172
3173 Services = []
3174 success = False
3175 while GetLastError() == ERROR_MORE_DATA:
3176 if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUS_PROCESSW):
3177 break
3178 ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
3179 success = _EnumServicesStatusExW(hSCManager, InfoLevel, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
3180 if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUS_PROCESSW) * ServicesReturned.value):
3181 raise ctypes.WinError()
3182 lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUS_PROCESSW)
3183 for index in xrange(0, ServicesReturned.value):
3184 Services.append( ServiceStatusProcessEntry(lpServicesArray[index]) )
3185 if success: break
3186 if not success:
3187 raise ctypes.WinError()
3188
3189 return Services
3190
3191 EnumServicesStatusEx = DefaultStringType(EnumServicesStatusExA, EnumServicesStatusExW)
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206 _all = set(vars().keys()).difference(_all)
3207 __all__ = [_x for _x in _all if not _x.startswith('_')]
3208 __all__.sort()
3209
3210