2016. 3. 24. 17:08 :: 애플리케이션 보안

안녕하세요~ Message 입니다.

 

API를 후킹하는 방법에는 2가지가 있습니다.

첫번째는 Debug를 이용하여 해당 프로세스에 Attach 한 뒤, 후킹 함수를 설치하는 방법이고

두번째는 DLL인젝션을 이용하여 대상 프로세스가 강제로 악성코드를 로딩 or 설치하게 만드는 방법입니다.

 

아래 소스코드는 Debug를 이용한 API 후킹 예제입니다.

Win32 API를 활용하기 쉽게 만든 디버거 모듈인 pydbg를 이용하여 kernel32.dll의 WriteFile API를 후킹합니다.

메모장에서 "I love you" 라고 작성한뒤 저장하면, "I hate you"로 변경되어 저장하도록 작성된 예제입니다.

 

1) 동작순서

① PID얻기 >  ② 명령어주소얻기 >  ③ 중단점설정 >  ④ 콜백함수등록 

   >  ⑤ 디버그이벤트대기 >  ⑥ 이벤트발생 >  ⑦ 콜백함수실행 >  ⑧ 프로세스복귀

2) 소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import utils, sys
from pydbg import *
from pydbg.defines import *
from _msi import PID_APPNAME
 
'''
BOOL WINAPI WriteFile(
_In_        HANDLE hFile,
_In_        LPCVOID lpBuffer,
_In_        DWORD nNumberOfBytesToWrite,
_Out_opt_   LPDWORD lpNumberOfBytesWritten,
_Inout_opt_ LPOVERLAPPED lpOverlapped
);
'''
 
dbg = pydbg()
isProcess = False
 
orgPattern = "love"
repPattern = "hate"
processName = "notepad.exe"
 
 
""" 디버그 이벤트가 발생할 때 호출할 콜백 함수 """
def replaceString(dbg, args):
    pbuffer = dbg.read_process_memory(args[1], args[2])
    
    if orgPattern in pbuffer:
        print "[APIHooking] Before : %s" % pbuffer
        pbuffer = pbuffer.replace(orgPattern, repPattern)
        replace = dbg.write_process_memory(args[1], pbuffer)
        print "[APIHooking] After : %s" % dbg.read_process_memory(args[1], args[2])
    return DBG_CONTINUE
 
 
""" for문을 이용하여 윈도우에서 실행되는 모든 프로세스 ID 리스트를 얻는다. """
for(pid, name) in dbg.enumerate_processes():
    print name
    if name.lower() == processName :
        isProcess = True
        hooks = utils.hook_container()
        
        """ 프로세스 핸들값 & 주소값 얻기 """
        dbg.attach(pid)
        print "Saves a process handle in self.h_process of pid[%d]" % pid
        hookAddress = dbg.func_resolve_debuggee("kernel32.dll""WriteFile")
        
        
        """ kernel32.dll의 WriteFile 함수에 중단점을 설정하고, 콜백함수 등록 """
        if hookAddress:
            hooks.add(dbg, hookAddress, 5, replaceString, None)
            print "sets a breakpoint at the designated address : 0x%08x" % hookAddress
            break
        else:
            print "[Error] : couldn't resolve hook address"
            sys.exit(-1)
        
if isProcess:
    print "wating for occurring debugger event"
    dbg.run()
else:
    print "[Error] : There in no process [%s]" % processName
    sys.exit(-1)
    
cs

 

3) 이슈노트

notepad.exe의 32bit/64bit 차이에 의해 DebugActiveProcess(13088) 에러가 발생하였습니다.

우리가 만든 프로그램은 32비트인데, Ctrl+R로 실행한 64비트 메모장을 디버깅 하려다 발생한 오류입니다.

내가 이클립스로 만든 프로그램이 32비트가 맞는건지 검색했으나 쉽게 나오지 않았습니다. (이래서 검색을 잘해야하는데..)

해결방법은 SysWOW64\notepad.exe 경로의 32bit 메모장을 실행시키면 오류가 발생하지 않습니다.

 

참고 : 파이썬 해킹 입문 / 조성문, 정영훈 지음

 

posted by Red_Message