Injection 기법및분석법 공개버전 2014.04.17 안랩시큐리티대응센터 (ASEC) 분석팀차민석책임연구원
Contents 01 02 03 04 05 06 07 왜 Injection 기법인가? Injection 기법배경지식 DLL Inection 기법 Code Injection 기법유용한도구 Case study 맺음말및과제
01 왜 Injection 기법인가?
악성코드의변화 플랫폼 - DOS -> Windows - Symbian OS -> Android - Linux, OS X - IoT (Internet of Things) 종류 - virus -> worm -> Trojan AhnLab, Inc. All rights reserved. 4
시스템에서악성코드찾기 다음중악성코드는? AhnLab, Inc. All rights reserved. 5
시스템에서악성코드찾기 다음중악성코드는? AhnLab, Inc. All rights reserved. 6
Injection 사전적의미 - 주입, 주사, 관장내용등 * source : http://dic.daum.net AhnLab, Inc. All rights reserved. 7
Injection 목적 일반적목적 - 추가기능 - bug Patch 등 악성코드의목적 - 악성코드발견을어렵게함 - 추가기능 (keylogger 등 ) - 보안프로그램 ( 방화벽등 ) 우회 - 분석지연혹은방해등 AhnLab, Inc. All rights reserved. 8
Injection 종류 DLL Injection LoadLibrary 를통한 Dll 파일주입 비교적쉽게제작 Injection 종류 Code Injection Code 주입 DLL Injection 보다어려움 Assembly 로제작된코드도많음 Bootkit을이용하면진짜 Fileless AhnLab, Inc. All rights reserved. 9
Windows 만의문제가아님 OS X 에서 Injection - Flashback 은 DYLD_INSERT_LIBRARIES 에악성코드를삽입해 Safari 의통신내용을가로챌수있음 - Windows 에서 AppInit_DLLs 에 DLL 추가하는방식과유사 * source : http://www.f-secure.com/v-descs/trojan-downloader_osx_flashback_i.shtml AhnLab, Inc. All rights reserved. 10
02 Injection 기법배경지식
DLL (Dynamic Link Library) DLL ( 동적링크라이브러리 ) * source : http://ko.wikipedia.org/wiki/ 동적 _ 링크 _ 라이브러리 AhnLab, Inc. All rights reserved. 12
DLL (Dynamic Link Library) DLL (Dynamic Link Library) - 응용프로그램의일부를동적으로링크할수있는라이브러리 목적 - 실행모듈만을로드하므로메모리사용량을줄일수있음 - 프로그램의특정부분을변경시키거나향상가능 - 특정모듈만을업그레이드가능 - 메모리에로딩하지않고매핑함으로써메모리절약 장점 - 실행메모리를절약 - 디스크공간절약 - 쉬운업그레이드가능 - 출시후지원가능 - 언어형식이다른여러프로그램지원 ( 함수호출규칙준수 ) - 국가별버전쉽게제작가능 AhnLab, Inc. All rights reserved. 13
DLL (Dynamic Link Library) 윈도우환경에서동작하는대부분의응용프로그램은 DLL 을사용한다. ex) 윈도우 7 x64 NOTEPAD.EXE 는약 10,617 개함수사용 AhnLab, Inc. All rights reserved.
DLL (Dynamic Link Library) AhnLab, Inc. All rights reserved. 15
DLL (Dynamic Link Library) Visual Studio 를이용하여 DLL 프로젝트를생성하면기본적으로생성되는코드 AhnLab, Inc. All rights reserved.
DLL (Dynamic Link Library) DLL 은어떻게구현되는가? -- PROCESS -- case DLL_PROCESS_ATTACH: case DLL_PROCESS_DETACH: -- THREAD -- case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: AhnLab, Inc. All rights reserved.
DLL (Dynamic Link Library) 암시적링킹 vs 명시적링킹 * 암시적 (Implicit) 링킹 DLL 제작시컴파일러에의해생성된 *.LIB 파일을이용하여사용할함수를링킹 실행바이너리링크단계에서 *.OBJ 파일과 *.LIB 파일을함께링크하여이정보를토대로 Runtime DLL 의함수코드를참조 프로그램실행전에필요한모든 DLL 을메모리에로딩 * 명시적 (Explicit) 링킹실행바이너리단계에서 DLL의함수정보가필요하지않음암시적로딩에비하여구현해야할코드가늘어남사용이필요한시점에필요한 DLL만로딩할수있으며분산로딩가능 AhnLab, Inc. All rights reserved.
DLL (Dynamic Link Library) DLL 사용 암시적 (Implicit) 연결을사용하여호출 사용하기는쉬우나사용하고자하는 DLL 의 import 라이브러리를프로젝트로포함시켜야함 (*.Lib) 명시적 (Explicit) 연결을사용하여호출 DLL 로딩과함수의위치, 사용후반환을위한 API호출이뤄짐 LoadLibrary(); GetProcAddress(); Execute_MyDLLFunc(); FreeLibrary(); AhnLab, Inc. All rights reserved.
Injection 관련 API OpenProcess - Process 접근 * source : http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx AhnLab, Inc. All rights reserved. 20
Injection 관련 API OpenProcess - Process 접근 AhnLab, Inc. All rights reserved. 21
Injection 관련 API VirtualAllocEx - memory 할당 * source : http://msdn.microsoft.com/en-us/library/windows/desktop/aa366890%28v=vs.85%29.aspx AhnLab, Inc. All rights reserved. 22
Injection 관련 API VirtualAllocEx - Memory Protection Constants * source : http://msdn.microsoft.com/en-us/library/windows/desktop/aa366786%28v=vs.85%29.aspx AhnLab, Inc. All rights reserved. 23
Injection 관련 API VirtualAllocEx - PAGE_EXECUTE_READWRITE AhnLab, Inc. All rights reserved. 24
Injection 관련 API WriteProcessMemory - Memory 쓰기 * soruce: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681674%28v=vs.85%29.aspx AhnLab, Inc. All rights reserved. 25
Injection 관련 API WriteProcessMemory - hprocess 와 lpbaseaddress 를중점적으로 AhnLab, Inc. All rights reserved. 26
Injection 관련 API CreateRemoteThread - 원격 Thread 생성 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms682437%28v=vs.85%29.aspx AhnLab, Inc. All rights reserved. 27
Injection 관련 API CreateRemoteThread - hprocess 와 lpstartaddress 를중점적 AhnLab, Inc. All rights reserved. 28
03 DLL Injection 기법
DLL Injection DLL Injection 과정 * source : http://resources.infosecinstitute.com/using-createremotethread-for-dll-injection-on-windows AhnLab, Inc. All rights reserved. 30
DLL Injection DLL Injection 과정 * source : http://www.reversecore.com/38 AhnLab, Inc. All rights reserved. 31
DLL Injection 종류 레지스트리조작을통한 DLL Injection 윈도우훅을이용하여 DLL Injection 원격스레드를이용하여 DLL Injection AhnLab, Inc. All rights reserved.
DLL Injection 종류 (1) AppInit_DLLs 등록 HKEY_LOCAL_MACHINE\ Software\Microsoft\Windows NT\ CurrentVersion\Windows\AppInit_DLLs HKEY_LOCAL_MACHINE\ Software\Microsoft\Windows NT\ CurrentVersion\Windows\LoadAppInit_DLLs User32.dll 의로딩특성을이용한인젝션방법 쉬운만큼단점도많아현재는많이쓰이지않음 AhnLab, Inc. All rights reserved.
DLL Injection 종류 (1) AppInit_DLLs 등록 [Application] Load User32.dll User32.DLL LoadLibrary(); DLL_PROCESS_ATTACH Regkey\...AppInit_DLLs MyDLL1.DLL MyDLL2.DLL MyDLL3.DLL... (DLL_PROCESS_ATTACH) AhnLab, Inc. All rights reserved.
DLL Injection 종류 (2) Windows Hook SetWindowsHookEx() API Idhook : 후킹하고자하는메시지의 ID(ex WH_KEYBOARD) lpfn : MyDLL.DLL 에지정된훅프로시저의주소값 -> GetProcAddress() hmod : MyDLL.DLL 의핸들 ( 이미 LoadLibrary() 시얻음 ) dwthreadid : 후킹할프로세스 (MyDLL.DLL) 을인젝션할 PID -> 0 : 전역훅 AhnLab, Inc. All rights reserved.
DLL Injection 종류 (2) Windows Hook Loader 구현 AhnLab, Inc. All rights reserved.
DLL Injection 종류 (2) Windows Hook MyDLL.DLL 구현 AhnLab, Inc. All rights reserved.
DLL Injection 종류 (3) Remote Thread 이용 가장유연성이뛰어난 DLL 인젝션기법중하나프로세스, 스레드, 동기화, 가상메모리, DLL, 유니코드에대한이해가필요 DLL 을삽입하고자하는대상프로세스의스레드가인젝션할 DLL 에대해 LoadLibrary 를수행 윈도우는 CreateRemoteThread() API 를통해다른프로세스내에새로운스레드를쉽게생성할수있는방법제공 AhnLab, Inc. All rights reserved.
DLL Injection 종류 (3) Remote Thread 이용 Chapter1 - Injection 을위한 Target Process 찾기!! DLL Path Chapter2 - Load 할 DLL 의 Path 구성 Target Process Chapter3 - DLL Path 구성을타겟프로세스에삽입 Chapter4 - Target Process 에 Thread 를생성하며, Thread 의시작주소및인자값넘겨주기 Thread 생성 DLL 로드 Chapter5 - DLL 로드 AhnLab, Inc. All rights reserved. 39
DLL Injection 종류 (3) Remote Thread 이용 Thread 의역할은단하나!!!!! DLL 을 LoadLibrary 함수로로드 AhnLab, Inc. All rights reserved. 40
DLL Injection 종류 (3) Remote Thread 이용 khandle = GetModuleHandleA("kernel32.dll"); getproc = (PTHREAD_START_ROUTINE)GetProcAddress(khandle,"LoadLibraryA"); AhnLab, Inc. All rights reserved. 41
DLL Injection 종류 (3) Remote Thread 이용 if(!(process=openprocess(process_all_access,false, pid))) { return FALSE; } Chapter1 - Injection 을위한 Target Process 찾기!! 미션!! 쓰레드의역할은단하나!!!!! DLL 을 LoadLibrary 함수를이용하여로드한다.!! AhnLab, Inc. All rights reserved. 42
DLL Injection 종류 (3) Remote Thread 이용 if(!(premotebuf = VirtualAllocEx(process,NULL,strlen(DllPath)+1,MEM_COMMIT,PAGE_READWRITE))) { return FALSE; Chapter1 } - Injection 을위한 Target Process 찾기!! Chapter2 - Load 할 DLL 의 Path 구성 미션!! 쓰레드의역할은단하나!!!!! DLL 을 LoadLibrary 함수를이용하여로드한다.!! AhnLab, Inc. All rights reserved. 43
DLL Injection 종류 (3) Remote Thread 이용 if(!(writeprocessmemory(process,premotebuf,dllpath,strlen(dllpath)+1,null))) { return FALSE; } Chapter1 - Injection 을위한 Target Process 찾기!! Chapter2 - Load 할 DLL 의 Path 구성 Chapter3 - DLL Path 구성을타겟프로세스에삽입 미션!! 쓰레드의역할은단하나!!!!! DLL 을 LoadLibrary 함수를이용하여로드한다.!! AhnLab, Inc. All rights reserved.
DLL Injection 종류 (3) Remote Thread 이용 thread = CreateRemoteThread(process,0,0,getproc,pRemotebuf,0,0); WaitForSingleObject(thread,INFINITE); Chapter1 - Injection 을위한 Target Process 찾기!! Chapter2 - Load 할 DLL 의 Path 구성 Chapter3 - DLL Path 구성을타겟프로세스에삽입 미션!! 쓰레드의역할은단하나!!!!! DLL 을 LoadLibrary 함수를이용하여로드한다.!! Chapter4 - Target Process 에 Thread 를생성하며, Thread 의시작주소및인자값넘겨주기 AhnLab, Inc. All rights reserved. 45
DLL Injection 종류 (3) Remote Thread 이용 thread = CreateRemoteThread(process,0,0,getproc,pRemotebuf,0,0); WaitForSingleObject(thread,INFINITE); 쓰레드동작시시작위치 ( 함수주소 ) 쓰레드동작시매개변수 AhnLab, Inc. All rights reserved. 46
DLL Injection 종류 (3) Remote Thread 이용 완성!! 이후 Load 된 DLL 의 DLL Main 함수가호출되며자유자재로동작 AhnLab, Inc. All rights reserved. 47
DLL Injection Demo DLL Injection - 대상 Process 선택 (notepad.exe) AhnLab, Inc. All rights reserved. 48
DLL Injection Demo DLL Injection - 대상 process 에 Dll injection AhnLab, Inc. All rights reserved. 49
DLL Injection Demo DLL Injection - 대상 DLL 을알면검색가능 AhnLab, Inc. All rights reserved. 50
04 Code Injection 기법
Code Injection Code Injection - Memory Injection 으로도불림 - 자신혹은다른프로세스에악성코드주입 - Private Data 영역을할당받아이용 - 보통 explorer.exe, svchost.exe 등시스템파일에코드를주입해방화벽우회시도 AhnLab, Inc. All rights reserved. 52
Code Injection 등장 Code Injection 등장 - 대략 2008 년부터악성코드에서이용시작 * soruce: http://blog.threatexpert.com/2008/02/malware-employs-microsofts-patent-on.html AhnLab, Inc. All rights reserved. 53
대상프로세스에따른분류 실행된프로세스 시스템프로세스 특정프로세스 실행된프로세스에메모리할당 실제코드는압축혹은암호화 Loader 역할하기도함 보안프로그램속이기위함목적 가장일반적인형태 특정목적수행 표적공격용으로가능 AhnLab, Inc. All rights reserved. 54
Code Injection 방법 (1) OpenProcess -> VirtualAllocEx -> WriteProcessMemory -> CreateRemoteThread SUSPENDED OpenProcess VirtualAllocEx Target Process Malware Malicious Code WriteProcessMemory Private Data CreateRemoteThread AhnLab, Inc. All rights reserved. 55
Code Injection 방법 (2) VirtualAllocEx -> InternetReadFile -> JMP VirtualAllocEx Malware JMP Malicious Code Private Data Malicious Code Private Data Malicious Code Private Data AhnLab, Inc. All rights reserved. 56
Code Injection 방법 (3) VirtualAllocEx -> WriteProcessMemory -> JMP(Call) or CreateThread Malware Packed (Encrypted) Malicious Code VirtualAllocEx JMP Malicious Code WriteProcessMemory Private Data AhnLab, Inc. All rights reserved. 57
CodeInjection Demo CodeInjection.exe - CodeInjection.exe pid - Notepad 에 injection AhnLab, Inc. All rights reserved. 58
CodeInjection Demo CodeInjection.exe - Notepad.exe 에서 MessgeBox AhnLab, Inc. All rights reserved. 59
CodeInjection Demo 실행불가상황 - 관리자권한으로실행 필요 - 이프로그램은 32 비트만가능 AhnLab, Inc. All rights reserved. 60
분석시간 실행준비 - notepad.exe 실행후 procexp 로프로세스번호확인 AhnLab, Inc. All rights reserved. 61
분석시간 Ollydbg - File -> Open 에서 CodeInjection.exe 선택 -Arguments 는 PID 값 ( 실행때마다달라짐 ) AhnLab, Inc. All rights reserved. 62
분석시간 Ollydbg - 디버깅시작 AhnLab, Inc. All rights reserved. 63
분석시간 Ollydbg - OpenProcess - ProcessID = 7FCh (2044) AhnLab, Inc. All rights reserved. 64
분석시간 Ollydbg - VirtualAllocEx - EAX = 009F0000 - WriteProcessMemory - EAX = 9F0000 AhnLab, Inc. All rights reserved. 65
분석시간 Ollydbg - CreateRemoteThread AhnLab, Inc. All rights reserved. 66
분석시간 Ollydbg 에 attach - File -> Attach 로 notepad.exe 선택 AhnLab, Inc. All rights reserved. 67
분석시간 Ollydbg 설정 - Options -> Debugging Options (Alt+O) 선택 - Events 에서 Break on new thread 선택후 F9 로실행 (Running 로변경됨 ) AhnLab, Inc. All rights reserved. 68
분석시간 실행 - codeinjection 실행해 injection 시도하면디버거안으로 AhnLab, Inc. All rights reserved. 69
분석시간 Ollydbg 설정 - BP 걸리지않으면 [Alt+M] 으로 Memory map 보기 -> RWE 속성가진 private data 영역찾기 - 대상 private data 영역에 [F2] ( 노란색반전 ) 후 [F9] 로다시실행 AhnLab, Inc. All rights reserved. 70
분석시간 Ollydbg - 마침내디버깅시작!!! AhnLab, Inc. All rights reserved. 71
분석시간 Ollydbg - [F7] 혹은 [F8] 로하나씩따라가면서의미파악 - 처음에는주석달면서분석해볼것! AhnLab, Inc. All rights reserved. 72
05 유용한도구
Procexp Process Explorer - dll 검색가능 AhnLab, Inc. All rights reserved. 74
PETools PE Tools - 프로세스뷰어, 덤프유틸리티 AhnLab, Inc. All rights reserved. 75
VMMap VMMap - 메모리보기 - String 확인 AhnLab, Inc. All rights reserved. 76
Ollydbg OllyDbg 에서 memory 덤프뜨기 - Memory map (Alt+M) 에서원하는 Address 선택 - Dump 창에서오른쪽마우스버튼 -> Backup -> Save backup to file AhnLab, Inc. All rights reserved. 77
Ollydbg OllyDbg plugin 으로 memory 덤프 - 파일로저장 AhnLab, Inc. All rights reserved. 78
06 Case study
07 맺음말및전망
DLL Injection vs Code Injection 구분 DLL Injection Code Injection DLL 사용유무 O X 흔적찾기 쉬움 어려움 사용목적 크고복잡한일 비교적간단한일 메모리사용크기 최소 DLL 크기이상 필요한만큼 구현난이도 쉬움 어려움 AhnLab, Inc. All rights reserved. 81
Injection 정리 - DLL Injection vs Code Injection - 원격 injection 은보통 OpenProcess-> VirtualAllocEx-> WriteProcessMemory-> CreateRemoteThread 순 - Key API : VirtualAllocEx, CreateRemotethread - 분석을위해서대상프로세스에미리 BP 걸어두기 AhnLab, Inc. All rights reserved. 82
To do Hooking - http://nagareshwar.securityxploded.com/2014/03/20/code-injection-and-api-hooking-techniques/ AhnLab, Inc. All rights reserved. 83
Q&A email : minseok.cha@ahnlab.com / mstoned7@gmail.com AhnLab, Inc. All rights reserved. 84
참고자료 김OO/ 안랩, 인젝션및후킹, 2013년고려대학교발표자료 이승원 / 안랩, Dll Injection, http://www.reversecore.com/38 이승원 / 안랩, Code Injection, 마이크로소프트웨어 2010년 8월호 (http://www.imaso.co.kr/?doc=bbs/gnuboard.php&bo_table=article&wr_id=35688) 허OO/ 안랩, DLL Injection, 2014 년안랩신규직원교육자료 AhnLab, Inc. All rights reserved. 85
D E S I G N Y O U R S E C U R I T Y