1
2
3
4
5 from ctypes import wintypes, POINTER
6
7 from lib.common.defines import ADVAPI32, KERNEL32, SE_PRIVILEGE_ENABLED
8 from lib.common.defines import LUID, TOKEN_PRIVILEGES, PROCESS_ALL_ACCESS
9 from lib.common.defines import TOKEN_ALL_ACCESS, LUID_AND_ATTRIBUTES
10
12 """Grant debug privileges.
13 @param pid: PID.
14 @return: operation status.
15 """
16 ADVAPI32.OpenProcessToken.argtypes = (wintypes.HANDLE,
17 wintypes.DWORD,
18 POINTER(wintypes.HANDLE))
19
20 ADVAPI32.LookupPrivilegeValueW.argtypes = (wintypes.LPWSTR,
21 wintypes.LPWSTR,
22 POINTER(LUID))
23
24 ADVAPI32.AdjustTokenPrivileges.argtypes = (wintypes.HANDLE,
25 wintypes.BOOL,
26 POINTER(TOKEN_PRIVILEGES),
27 wintypes.DWORD,
28 POINTER(TOKEN_PRIVILEGES),
29 POINTER(wintypes.DWORD))
30
31 if pid is None:
32 h_process = KERNEL32.GetCurrentProcess()
33 else:
34 h_process = KERNEL32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
35
36 if not h_process:
37 return False
38
39 h_current_token = wintypes.HANDLE()
40 if not ADVAPI32.OpenProcessToken(h_process,
41 TOKEN_ALL_ACCESS,
42 h_current_token):
43 return False
44
45 se_original_luid = LUID()
46 if not ADVAPI32.LookupPrivilegeValueW(None,
47 "SeDebugPrivilege",
48 se_original_luid):
49 return False
50
51 luid_attributes = LUID_AND_ATTRIBUTES()
52 luid_attributes.Luid = se_original_luid
53 luid_attributes.Attributes = SE_PRIVILEGE_ENABLED
54 token_privs = TOKEN_PRIVILEGES()
55 token_privs.PrivilegeCount = 1
56 token_privs.Privileges = luid_attributes
57
58 if not ADVAPI32.AdjustTokenPrivileges(h_current_token, False, token_privs,
59 0, None, None):
60 return False
61
62 KERNEL32.CloseHandle(h_current_token)
63 KERNEL32.CloseHandle(h_process)
64 return True
65