def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
python类WinDLL()的实例源码
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def get_windows_disks(self):
""" Return disks available on Windows machine
:return: list of characters representing available disks
"""
disks = list()
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
SEM_FAILCRITICALERRORS = 1
SEM_NOOPENFILEERRORBOX = 0x8000
SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS
oldmode = ctypes.c_uint()
kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode))
for s in string.ascii_uppercase:
n = s + WINDOWS_DISK_SUFFIX
if os.path.exists(n):
disks.append(n)
kernel32.SetThreadErrorMode(oldmode, ctypes.byref(oldmode))
return disks
def load_call_dict(call_dict, lib):
"""Loads argument/return types from the call dictionary
@param call_dict: call dictionary. Keyed by function name;
values are [return type, argtype0, argtype 1...]
@type call_dict: dict
@param lib: library where functions specified in L{call_dict} live.
@type lib: ctypes.WinDLL or ctypes.CDLL
"""
for funcname in call_dict:
func = getattr(lib, funcname)
args = call_dict[funcname]
func.restype = args[0]
if len(args) <= 1:
func.argtypes = None
else:
func.argtypes = args[1:]
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def __loaddll(self, fp=None):
if fp != None:
if os.path.exists(fp):
self.nnotesdll = ctypes.WinDLL(fp)
else:
self.nnotesdll = None
else:
self.nnotesdll = None
try:
# If we already have the COM/DDE interface to Notes, then nlsxbe.dll
# is already loaded, so we can just try and get nnotes.dll leaving
# Windows to search in its default search path
self.nnotesdll = ctypes.WinDLL('nnotes.dll')
except OSError:
# Try harder
for p in notesDllPathList:
fp = os.path.join(p, 'nnotes.dll')
if os.path.exists(fp):
self.nnotesdll = ctypes.WinDLL(fp)
break
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def psloadlib(name):
""" Loads driver library
:param name: driver name
:type name: str
:returns: ctypes reference to the library
:rtype: object
"""
result = None
try:
if sys.platform == 'win32':
result = ctypes.WinDLL(find_library(name))
else:
result = cdll.LoadLibrary(find_library(name))
except OSError as ex:
print name, "import(%d): Library not found" % sys.exc_info()[-1].tb_lineno
return result
def get():
'''get
Returns the library.Library singleton for nifgen.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def get():
'''get
Returns the library.Library singleton for niscope.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def get():
'''get
Returns the library.Library singleton for niswitch.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def get():
'''get
Returns the library.Library singleton for nimodinst.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def get():
'''get
Returns the library.Library singleton for nidmm.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def get():
'''get
Returns the library.Library singleton for nidcpower.
'''
global _instance
global _instance_lock
with _instance_lock:
if _instance is None:
try:
library_type = _get_library_type()
if library_type == 'windll':
ctypes_library = ctypes.WinDLL(_get_library_name())
else:
assert library_type == 'cdll'
ctypes_library = ctypes.CDLL(_get_library_name())
except OSError:
raise errors.DriverNotInstalledError()
_instance = library.Library(ctypes_library)
return _instance
def win32_get_app_data_path(*args):
shell32 = ctypes.WinDLL("shell32.dll")
SHGetFolderPath = shell32.SHGetFolderPathW
SHGetFolderPath.argtypes = (
ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32,
ctypes.c_wchar_p)
SHGetFolderPath.restype = ctypes.c_uint32
CSIDL_LOCAL_APPDATA = 0x001c
MAX_PATH = 260
buf = ctypes.create_unicode_buffer(MAX_PATH)
res = SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, buf)
if res != 0:
raise Exception("Could not deterime APPDATA path")
return os.path.join(buf.value, *args)
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def remove_ca(self, name):
import ctypes
import ctypes.wintypes
class CERT_CONTEXT(ctypes.Structure):
_fields_ = [
('dwCertEncodingType', ctypes.wintypes.DWORD),
('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
('cbCertEncoded', ctypes.wintypes.DWORD),
('pCertInfo', ctypes.c_void_p),
('hCertStore', ctypes.c_void_p),]
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
while pCertCtx:
certCtx = CERT_CONTEXT.from_address(pCertCtx)
certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata)
if hasattr(cert, 'get_subject'):
cert = cert.get_subject()
cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
if cert_name and name.lower() == cert_name.split()[0].lower():
crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
return 0
def remove_ca(self, name):
import ctypes
import ctypes.wintypes
class CERT_CONTEXT(ctypes.Structure):
_fields_ = [
('dwCertEncodingType', ctypes.wintypes.DWORD),
('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
('cbCertEncoded', ctypes.wintypes.DWORD),
('pCertInfo', ctypes.c_void_p),
('hCertStore', ctypes.c_void_p),]
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
while pCertCtx:
certCtx = CERT_CONTEXT.from_address(pCertCtx)
certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata)
if hasattr(cert, 'get_subject'):
cert = cert.get_subject()
cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
if cert_name and name.lower() == cert_name.split()[0].lower():
crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
return 0
def remove_cert(name):
if os.name == 'nt':
import ctypes, ctypes.wintypes
class CERT_CONTEXT(ctypes.Structure):
_fields_ = [
('dwCertEncodingType', ctypes.wintypes.DWORD),
('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
('cbCertEncoded', ctypes.wintypes.DWORD),
('pCertInfo', ctypes.c_void_p),
('hCertStore', ctypes.c_void_p),]
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
while pCertCtx:
certCtx = CERT_CONTEXT.from_address(pCertCtx)
certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
cert = crypto.load_certificate(crypto.FILETYPE_ASN1, certdata)
if hasattr(cert, 'get_subject'):
cert = cert.get_subject()
cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
if cert_name and name == cert_name:
crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
return 0
return -1
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def test_self_iat_hook_multithread():
"""Test IAT hook in current process with multi thread trigger"""
cp = windows.current_process
# Might change this to XP compat ?
kernelbase_mod = [m for m in cp.peb.modules if m.name == "kernelbase.dll"][0]
LdrLoadDll = [n for n in kernelbase_mod.pe.imports['ntdll.dll'] if n.name == "LdrLoadDll"][0]
calling_thread = set([])
@windows.hooks.LdrLoadDllCallback
def MyHook(*args, **kwargs):
calling_thread.add(windows.current_thread.tid)
return kwargs["real_function"]()
x = LdrLoadDll.set_hook(MyHook)
# Trigger from local thread
ctypes.WinDLL("kernel32.dll")
assert calling_thread == set([windows.current_thread.tid])
# Trigger from another thread
k32 = [m for m in cp.peb.modules if m.name == "kernel32.dll"][0]
load_libraryA = k32.pe.exports["LoadLibraryA"]
with cp.allocated_memory(0x1000) as addr:
cp.write_memory(addr, "DLLNOTFOUND.NOT_A_REAL_DLL" + "\x00")
t = cp.create_thread(load_libraryA, addr)
t.wait()
assert len(calling_thread) == 2
x.disable()
def _get_func_addr(dll_name, func_name):
# Load the DLL
ctypes.WinDLL(dll_name)
modules = windows.current_process.peb.modules
if not dll_name.lower().endswith(".dll"):
dll_name += ".dll"
mod = [x for x in modules if x.name == dll_name][0]
return mod.pe.exports[func_name]
def get_func_addr(dll_name, func_name):
# Load the DLL
ctypes.WinDLL(dll_name)
modules = windows.current_process.peb.modules
if not dll_name.lower().endswith(".dll"):
dll_name += ".dll"
mod = [x for x in modules if x.name == dll_name][0]
return mod.pe.exports[func_name]
def _command_line_to_args_list(cmdline):
"""splits a string into a list using Windows command line syntax."""
args_list = []
if cmdline and cmdline.strip():
from ctypes import c_int, c_voidp, c_wchar_p
from ctypes import byref, POINTER, WinDLL
clta = WinDLL('shell32').CommandLineToArgvW
clta.argtypes = [c_wchar_p, POINTER(c_int)]
clta.restype = POINTER(c_wchar_p)
lf = WinDLL('kernel32').LocalFree
lf.argtypes = [c_voidp]
pNumArgs = c_int()
r = clta(cmdline, byref(pNumArgs))
if r:
for index in range(0, pNumArgs.value):
if sys.hexversion >= 0x030000F0:
argval = r[index]
else:
argval = r[index].encode('ascii', 'replace')
args_list.append(argval)
lf(r)
else:
sys.stderr.write('Error parsing script arguments:\n')
sys.stderr.write(cmdline + '\n')
return args_list
def _command_line_to_args_list(cmdline):
"""splits a string into a list using Windows command line syntax."""
args_list = []
if cmdline and cmdline.strip():
from ctypes import c_int, c_voidp, c_wchar_p
from ctypes import byref, POINTER, WinDLL
clta = WinDLL('shell32').CommandLineToArgvW
clta.argtypes = [c_wchar_p, POINTER(c_int)]
clta.restype = POINTER(c_wchar_p)
lf = WinDLL('kernel32').LocalFree
lf.argtypes = [c_voidp]
pNumArgs = c_int()
r = clta(cmdline, byref(pNumArgs))
if r:
for index in range(0, pNumArgs.value):
if sys.hexversion >= 0x030000F0:
argval = r[index]
else:
argval = r[index].encode('ascii', 'replace')
args_list.append(argval)
lf(r)
else:
sys.stderr.write('Error parsing script arguments:\n')
sys.stderr.write(cmdline + '\n')
return args_list
def __init__(self, tzres_loc='tzres.dll'):
# Load the user32 DLL so we can load strings from tzres
user32 = ctypes.WinDLL('user32')
# Specify the LoadStringW function
user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
wintypes.UINT,
wintypes.LPWSTR,
ctypes.c_int)
self.LoadStringW = user32.LoadStringW
self._tzres = ctypes.WinDLL(tzres_loc)
self.tzres_loc = tzres_loc
def __init__(self, tzres_loc='tzres.dll'):
# Load the user32 DLL so we can load strings from tzres
user32 = ctypes.WinDLL('user32')
# Specify the LoadStringW function
user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
wintypes.UINT,
wintypes.LPWSTR,
ctypes.c_int)
self.LoadStringW = user32.LoadStringW
self._tzres = ctypes.WinDLL(tzres_loc)
self.tzres_loc = tzres_loc
def __init__(self, tzres_loc='tzres.dll'):
# Load the user32 DLL so we can load strings from tzres
user32 = ctypes.WinDLL('user32')
# Specify the LoadStringW function
user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
wintypes.UINT,
wintypes.LPWSTR,
ctypes.c_int)
self.LoadStringW = user32.LoadStringW
self._tzres = ctypes.WinDLL(tzres_loc)
self.tzres_loc = tzres_loc