因为 win7 对程序的权限进行了一些限制, 导致有些程序在 xp 下正常运行, 而在 win7 下就出错了, 例如 OpenProcess() 失败, 这时就需要提升我们程序的特权, 开启它的 Debug 权限.
直接上代码
数据结构定义:
class LUID_AND_ATTRIBUTES(Structure):
_fields_ = [
('Luid', DWORD),
('Attributes', DWORD),
]
class TOKEN_PRIVILEGES(Structure):
_fields_ = [
('PrivilegeCount', DWORD),
('Privileges', LUID_AND_ATTRIBUTES * 512),
]
核心代码:
# -*- coding: utf-8 -*-
from ctypes import *
from my_debugger_defines import *
kernel32 = windll.kernel32
advapi32 = windll.advapi32
class debugger():
# ...
def privilege(self):
# token_handle = win32security.OpenProcessToken(kernel32.GetCurrentProcess(), win32con.TOKEN_ALL_ACCESS) != 0
# if token_handle == 0:
# print '提取令牌失败'
# else:
# Luid = win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME)
# if Luid == 0:
# print 'Luid获取失败'
# else:
# new_token_pricileges = (Luid, win32security.SE_PRIVILEGE_ENABLED)
# i = win32security.AdjustTokenPrivileges(token_handle, 0, new_token_pricileges)
# if i == 0:
# print '提权失败'
# win32api.CloseHandle(token_handle)
h_token = HANDLE()
TOKEN_ALL_ACCESS = 0x000F01FF
SE_PRIVILEGE_ENABLED = 0x00000002
if kernel32.OpenProcessToken(kernel32.GetCurrentProcess(), TOKEN_ALL_ACCESS, byref(h_token)) != True:
print '提权失败 -- OpenProcessToken'
return False
tp = TOKEN_PRIVILEGES()
luid = DWORD()
if advapi32.LookupPrivilegeValueA(None, 'SeDebugPrivilege', byref(luid)) != True:
print '提权失败 -- LookupPrivilegeValueA'
return False
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
if advapi32.AdjustTokenPrivileges(h_token, False, byref(tp), sizeof(tp), None, None) != True:
print '提权失败 -- AdjustTokenPrivileges'
return False
kernel32.CloseHandle(h_token)
print '提权成功'
return True
测试代码:
# -*- coding: utf-8 -*-
import my_debugger
debugger = my_debugger.debugger()
if debugger.privilege():
pid = raw_input('Enter the pid: ')
debugger.attach(int(pid))
# ...
debugger.detach()
else:
print '退出'