본문 바로가기

해킹

취약점 분석에 필요한 windbg에 python을 연동해보자!

안녕하세요? 더미다로 패킹된 프로그램을 분석하면서 안티 디버깅을 무력화 시키기 위해

스크립트가 필요한 상황이 생겼는데요. 안디 디버깅이라는 것은 프로그램 분석(리버싱)을 방해하는 스킬을 말합니다.

그래서 오늘 pykd를 설치하는 겸에 글을 쓰게 되었습니다.

 

먼저 pykd bootstrapper를 다운받고, DLL파일을 windbg의 폴더 내 winext 폴더에 저장합니다.

https://githomelab.ru/pykd/pykd/-/wikis/home

 

Home · Wiki · pykd / pykd

This project can help to automate debugging and crash dump analysis using Python. It allows one to take the best from both worlds: the expressiveness and convenience of Python with...

githomelab.ru

 

그리고 setup.py를 다운받고 아래의 명령어를 실행하여 설치하시면 됩니다.

python setup.py install

https://githomelab.ru/pykd/pykdwin

 

pykd / pykdwin

GitHomeLab

githomelab.ru

 

설치가 완료됬다면, windbg에서 프로세스를 실행하거나, attach한 후 아래와 같은 명령어를 사용하시면 됩니다.

0:037> .load pykd
0:037> !py  
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23)
[MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> print("TEST")
TEST 

 

만약 파이썬에서 windbg의 명령어를 실행하고 싶으시다면 아래와 같이 할 수 있습니다.

0:037> !py
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import pykd
>>> pykd.dbgCommand(".printf \"TEST!\"")
'TEST!'

 

그 외 명령어들을 스크립트로 만들고 싶다면 아래를 참고하시면 좋습니다.

https://rayanfam.com/topics/pykd-tutorial-part1/

 

PyKD Tutorial - part 1 - Sina & Shahriar's Blog

Using windbg script syntax is such annoying thing that almost all reverse engineers have problems dealing with it but automating debugging gives such a power that can't be easily ignored. A good solution to solve this problem is using the power and simplic

rayanfam.com

https://githomelab.ru/pykd/pykd/blob/0.3.2/samples/um/virtalloc.py

 

samples/um/virtalloc.py · 0.3.2 · pykd / pykd

This project can help to automate debugging and crash dump analysis using Python. It allows one to take the best from both worlds: the expressiveness and convenience of Python with...

githomelab.ru

 

PageGuard 안티 디버깅을 위한 windbg 스크립트 공개 합니다. 

import sys 
import pykd 
import re 
from ctypes import *

PAGE_EXECUTE = 0x10
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_WRITECOPY = 0x80
PAGE_READWRITE = 0x04

PROCESS_VM_READ = 0x10 
PROCESS_VM_WRITE = 0x20
PROCESS_ALL_ACCESS = 0x1F0FFF

def getProcessName():
    moduleList = pykd.dbgCommand("!peb").split('Base TimeStamp                     Module')[1].strip().split('\n')
    return moduleList[0].split(' ')[-1]

def getPid():
    return int(pykd.dbgCommand("!teb").split("ClientId:")[1].split('\n')[0].strip().split(' . ')[0],16)
    
def getPageGuard():
    heap = pykd.dbgCommand("!address").split("\n")
    result = list()
    for h in heap:
        if( h.find("GUARD") >= 0):
            result.append(h)
    return result
    
def fixPageGuard(addr, size, attribute):
    org = pointer(c_int(0))
    r = cdll.kernel32.VirtualProtectEx(proc, addr, size, PAGE_READWRITE, org)
    if( r == 0 ):
        print("VirtualProtectEx Error! %d" % cdll.kernel32.GetLastError())
    return r

def openProcess():
    handle = cdll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, getPid())
    if( handle == 0 ):
        print('Error! %d' % cdll.kernel32.GetLastError())
    return handle 

proc = openProcess()
pageGuard = getPageGuard()
for p in pageGuard:
    print(p)
    memory = re.sub("[\s]+", " ", p)[1:].split(' ')
    address = int(memory[0],16)
    size = int(memory[2], 16)
    attribute = memory[5]
    r = fixPageGuard(address, size, attribute)

cdll.kernel32.CloseHandle(proc)

 

만약 더미다 라든지, code virtualizer 때문에 고생하는 분이 계시면 도움이 되면 좋을 것 같습니다.