[3주] 05장 - Immunity Debugger 공격코드에서 사용할 명령찾기

Posted by dw0rdptr
2015. 1. 26. 07:31 Study/파이썬 해킹 프로그래밍

Immunity 디버거의 파이썬 라이브러리를 이용하면 로드된 바이너리에서 원하는 명령을 쉽게 찾을 수 있다.



작성한 코드를 Immunity Debugger\PyCommands 폴더에 넣고 디버거 명령줄에 !findinstruction<찾을 명령>

을 입력하면 된다. jmp esp 명령을 찾아보려면

!findinstruction jmp esp

메뉴의 View->Log(단축키 Alt+L)로 확인 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
 
#findinstruction.py
#-*- coding: utf-8 -*-
from immlib import *
 
def main(args):
    imm = Debugger()
    search_code = " ".join(args)
    search_byte = imm.assemble(search_code)
    search_results = imm.search(search_byte)
 
    for hit in search_results:
        #메모리 페이지를 구하고 실행 가능한 것인지 확인
        code_page = imm.getMemoryPageByAddress(hit)
        access = code_page.getAccess(human = True)
 
        if "execute" in access.lower():
            imm.log("[*] Found : %s (0x%08x)" % (search_code, hit), address = hit)
 
    return "[*] Finish searching for instructions, check the Log window."
 
cs



'Study > 파이썬 해킹 프로그래밍' 카테고리의 다른 글

[3주] 05장~06장 후킹  (0) 2015.01.26
[3주] 05장 - 윈도우 DEP우회  (0) 2015.01.26
[3주] 04장 - 종합  (0) 2015.01.26
[3주] 04장 - 프로세스 스냅샷  (0) 2015.01.26
[3주] 04장 - 접근 위반 핸들러  (0) 2015.01.26

[3주] 04장 - 종합

Posted by dw0rdptr
2015. 1. 26. 06:36 Study/파이썬 해킹 프로그래밍

악용될 수 있는 소프트웨어 애플리케이션의 결함을 제거하는데 도움이 되는 유틸리티프로그램을 짜보자


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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#danger_track.py
#-*- coding: utf-8 -*-
from pydbg import *
from pydbg.defines import *
 
import utils
 
#접근 위반이 발생한 후에 조사할 명령의 최대 개수
MAX_INSTRUCTIONS = 10
 
 
#다음은 모든 위험한 한수에 포함하는 완벽한 리스트는 아니다.
dangerous_functions = { "strcpy" : "msvcrt.dll""strncpy" : "msvcrt.dll"
                                "sprintf" : "msvcrt.dll""vsprintf" : "msvcrt.dll"}
dangerous_functions_resolved = {}
crash_encountered = False
instruction_count = 0
 
def danger_handler(dbg):
    #스택의 내용을 출력한다.
    #일반적으로 몇 개의 파라미터만을 사용하기 때문에 ESP~ESP+20 내용만 출력해도됨
    esp_offset = 0
    print "[*] Hit %s" % dangerous_functions_resolved[dbg.context.Eip]
    print "============================================================"
 
    while esp_offset <=20:
        parameter = dbg.smart_dereference(dbg.context.Esp + esp_offset)
        print "[ESP + %d] => %s " % (esp_offset, parameter)
        esp_offset += 4
 
    print "============================================================"
 
    dbg.suspend_all_threads()
    dbg.process_snapshot()
    dbg.resume_all_threads()
 
    return DBG_CONTINUE
 
def access_violation_handler(dbg):
    global crash_encountered
 
    #접근 위반을 처리하고 프로세스를 마지막 위험한 함수가 호출된 시점으로 되돌림
    if dbg.dbg.u.Exception.dwFirstChance:
        return DBG_EXCEPTION_NOT_HANDLED
 
 
    crash_bin = utils.crash_binning.crash_binning()
    crash_bin.record_crash(dbg)
    print crash_bin.crash_synopsis()
 
    if crash_encountered == False:
        dbg.suspend_all_threads()
        dbg.process_restore()
        crash_encountered = True
 
        for thread_id in dbg.enumerate_threads():
            print "[*] Setting single step for thread: 0x%08x" % thread_id
            h_thread = dbg.open_thread(thread_id)
            dbg.single_step(True, h_thread)
            dbg.close_handle(h_thread)
 
        #단일 스탭 핸들러에게 제어권을 넘기기위해 프로세스를 다시 실행되게만든다
        dbg.resume_all_threads()
 
        return DBG_CONTINUE
    else:
        dbg.terminate_process()
 
    return DBG_EXCEPTION_NOT_HANDLED
 
def single_step_handler(dbg):
    global instruction_count
    global crash_encountered
 
    if crash_encountered:
        if instruction_count == MAX_INSTRUCTIONS:
                dbg.single_step(False)
                return DBG_CONTINUE
        else:
            #명령을 디스어셈블.
            instruction = dbg.disasm(dbg.context.Eip)
            print "#%d\t0x%08x : %s" % (instruction_count, dbg.context.Eip, instruction)
            instruction_count +=1
            dbg.single_step(True)
 
    return DBG_CONTINUE
 
dbg = pydbg()
pid = int(raw_input("Enter the PID you wish to monitor :"))
dbg.attach(pid)
 
#리스트의 모든 위험한 함수를 호출하고 브레이크포인트설정
 
for func in dangerous_functions.keys():
 
    func_address = dbg.func_resolve(dangerous_functions[func],func)
    print "[*] Resolved breakpoint: %s -> 0x%08x" % (func,func_address)
    dbg.bp_set(func_address, handler = danger_handler)
    dangerous_functions_resolved[func_address] = func
 
dbg.set_callback( EXCEPTION_ACCESS_VIOLATION, access_violation_handler)
dbg.set_callback(EXCEPTION_SINGLE_STEP, single_step_handler)
dbg.run()
 
 
cs


buffer_overflow.py에 붙인 결과


restore에서 자꾸 매개변수가 틀리다는 에러가뜨는데 왜그런지는 모르겠다


[3주] 04장 - 프로세스 스냅샷

Posted by dw0rdptr
2015. 1. 26. 06:02 Study/파이썬 해킹 프로그래밍

스냅샷은 대상 프로세스의 어떤 특정 시점을 저장한다.

스냅샷을 만든 이후에는 언제든지 프로세스의 상태를 스냅샷 생성 시점으로 되돌릴 수 있다.



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
65
66
67
68
69
70
71
72
73
74
75
76
#snapshot.py
#-*- coding: utf-8 -*-
from pydbg import *
from pydbg.defines import *
 
import threading
import time
import sys
 
class snapshotter(object):
 
    def __init__(self,exe_path):
 
        self.exe_path = exe_path
        self.pid      = None
        self.dbg      = None
        self.running  = True
 
        #디버거 스레드시작, 대상 프로세스의 PID가 설정될 떄까지 루프돔
        pydbg_thread = threading.Thread(target = self.start_debugger)
        pydbg_thread.setDaemon(0)
        pydbg_thread.start()
 
        while self.pid == None:
            time.sleep(1)
 
        #현재 PID가 설정된 상태이고 대상 프로세스가 실행중.
        #스냅샷을 위한 두 번째 스레드 실행
        monitor_thread = threading.Thread(target=self.monitor_debugger)
        monitor_thread.setDaemon(0)
        monitor_thread.start()
 
 
    #스냅샷을 만들것인지 복원할것인지 종료할것인지 명령입력
    def monitor_debugger(self):
        while self.running == True:
            input = raw_input("Enter: 'snap', 'restore' or 'quit' :")
            input = input.lower().strip()
 
            if input == "quit":
                print "[*] Exiting the snapshotter."
                self.running = False
                self.dbg.terminate_process()
 
            elif input == "snap":
                print "[*] Suspending all threads."
                self.dbg.suspend_all_threads()
 
                print "[*] Obtaining snapshot"
                self.dbg.process_snapshot()
 
                print "[*] Resuming operation."
                self.dbg.resume_all_threads()
 
            elif input == "restore":
                print "[*] Suspending all threads."
                self.dbg.suspend_all_threads()
 
                print "[*] Restoring snapshot."
                self.dbg.process_restore()
 
                print "[*] Resuming operation."
                self.dbg.resume_all_threads()
 
    def start_debugger(self):
        self.dbg = pydbg()
        pid = self.dbg.load(self.exe_path)
        self.pid = self.dbg.pid
 
        self.dbg.run()
 
exe_path = "C:\\Windows\\System32\\calc.exe"
snapshotter(exe_path)
 
 
 
cs

#계산기로 프로세스 스냅샷 기능이 동작하는 것을 확인 가능