├── LICENSE
├── README.md
├── assets
├── laptop-4152330_1920.jpg
└── laptop-4152330_640.jpg
├── gitbook
├── .gitignore
├── README.md
├── SUMMARY.md
├── chapters
│ ├── assembly
│ │ └── x86_assembly.md
│ ├── debugging
│ │ ├── rb_windbg.md
│ │ └── windows-debugging-internals.md
│ ├── malware_analysis
│ │ ├── dynamic_malware_analysis.md
│ │ ├── memory_dump_analysis.md
│ │ └── smc_malware_analysis.md
│ ├── pe
│ │ └── pe_file_format.md
│ ├── solutions
│ │ ├── crash_dump_analysis.md
│ │ ├── file_identification_analysis_i.md
│ │ ├── file_identification_analysis_ii.md
│ │ ├── malware_anti_analysis.md
│ │ ├── md5_code_section.md
│ │ ├── simple_process_injection.md
│ │ ├── stuxnet_memory_image.md
│ │ ├── win32_api_counting.md
│ │ └── zeus_memory_image.md
│ └── windows
│ │ ├── api_hooking.md
│ │ └── platform_overview.md
└── images
│ ├── api_hooking_detours.png
│ ├── api_hooking_example.png
│ ├── aspack_dbg1.png
│ ├── aspack_dbg2.png
│ ├── aspack_ida1.png
│ ├── aspack_ida2.png
│ ├── aspack_ida3.png
│ ├── aspack_scylla.png
│ ├── be2_driver_vt.png
│ ├── cff1.png
│ ├── crashdump_neohex1.png
│ ├── fileid_ida1.png
│ ├── fileid_ida2.png
│ ├── ida_main.png
│ ├── pe101.svg
│ ├── pe_headers_basic.png
│ ├── pe_headers_cff.png
│ ├── peid1.png
│ ├── peid2.png
│ ├── peid_sample2.png
│ ├── pi_dump_file.png
│ ├── pi_hidump.png
│ ├── pi_ida_sol.png
│ ├── pi_memory.png
│ ├── pi_wpm.png
│ ├── rbwindbg_sample.png
│ ├── sandboxie_bsa.png
│ ├── sandboxie_bsa_fakenet.png
│ ├── smc1.png
│ ├── smc10.png
│ ├── smc11.png
│ ├── smc2.png
│ ├── smc3.png
│ ├── smc4.png
│ ├── smc5.png
│ ├── smc6.png
│ ├── smc7.png
│ ├── smc8.png
│ ├── smc9.png
│ ├── stuxnet_Driver.png
│ ├── stuxnet_VT.png
│ ├── upx_before_oep.png
│ ├── upx_disasm1.png
│ ├── upx_disasm2.png
│ ├── upx_ollydump.png
│ ├── upx_scylla.png
│ ├── upx_unpack1.png
│ ├── upx_unpacked.png
│ ├── win32_api.png
│ ├── windows_arch.png
│ ├── winmd5.png
│ ├── x86_arch.png
│ ├── x86_cpu_rings.png
│ ├── x86_mm.png
│ └── zeus_VT.png
└── presentations
├── pdf
├── 001_Intro_RE.pdf
├── 002_A_Intro_Win32_Core_Platform.pdf
├── 003_B_Win32_API_Hooking.pdf
├── 004_Intro_PortalExecutable.pdf
├── 005_A_Intro_X86_ASM.pdf
├── 008_B_Malware_Analysis_Memory_Forensics.pdf
├── 009_A_Packers_Crypters.pdf
├── ASPAck229_Manual_Unpacking.pdf
├── HackIM2014_RE_Hard_SMC.pdf
└── Windows_Process_Injection.pdf
└── ppt
└── EMPTY
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Abhisek Datta
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Reverse Engineering and Malware Analysis 101
2 | Course content and slides from my **ancient** training on Reverse Engineering & Malware Analysis (101 Getting Started)
3 |
4 | 
5 |
6 | > Image by mohamed Hassan from Pixabay
7 |
8 | ## Content
9 |
10 | * [Gitbook](gitbook/)
11 | * [Presentations](presentations/)
12 |
13 | ## Using Gitbook
14 |
15 | Install
16 |
17 | ```
18 | npm install -g gitbook-cli
19 | ```
20 |
21 | Run locally
22 |
23 | ```
24 | cd gitbook
25 | gitbook serve
26 | ```
27 |
28 | ## License
29 |
30 | ```
31 | MIT License
32 |
33 | Copyright (c) 2019 Abhisek Datta
34 |
35 | Permission is hereby granted, free of charge, to any person obtaining a copy
36 | of this software and associated documentation files (the "Software"), to deal
37 | in the Software without restriction, including without limitation the rights
38 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39 | copies of the Software, and to permit persons to whom the Software is
40 | furnished to do so, subject to the following conditions:
41 |
42 | The above copyright notice and this permission notice shall be included in all
43 | copies or substantial portions of the Software.
44 |
45 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
51 | SOFTWARE.
52 | ```
53 |
--------------------------------------------------------------------------------
/assets/laptop-4152330_1920.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/assets/laptop-4152330_1920.jpg
--------------------------------------------------------------------------------
/assets/laptop-4152330_640.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/assets/laptop-4152330_640.jpg
--------------------------------------------------------------------------------
/gitbook/.gitignore:
--------------------------------------------------------------------------------
1 | _book
2 |
--------------------------------------------------------------------------------
/gitbook/README.md:
--------------------------------------------------------------------------------
1 | # Reverse Engineering and Malware Analysis
2 |
3 | ## Objective
4 |
5 | The objective of this training program is to introduce participants with basic knowledge of *programming*, *debugging* and *x86 assembly language* to the art of Software Reverse Engineering and Malware Analysis. Various use-cases for Reverse Engineering and Malware Analysis along with live examples will be demonstrated during the session in order to impart a practical and result oriented training to the participants. The entire session will focus only on Win32 Platform however most of the techniques discussed are applicable for Win64 platform as well and some of them even for Linux or other Operating System platforms. Multiple CTF like challenges will be provided during the workshop in order to encourage the participants to try out various tools and techniques discussed during the session.
6 |
7 |
8 | ## Course Structure
9 |
10 | * Introduction to Windows Platform
11 | * Platform Overview
12 | * Process Tracing and Analysis (Sysinternals Suite)
13 | * Debugging Tools for Windows
14 | * API Hooking
15 |
16 | * Portable Executable (PE) File Format
17 | * PE File Format Internals
18 | * PE Loader Process
19 |
20 | * Introduction to x86 Assembly Language
21 | * Overview of x86 Architecture & Instruction Set
22 | * Program Disassembly and Analysis
23 | * Static Analysis using IDA Pro
24 |
25 | * Introduction to Malware Analysis
26 | * Malware Behaviour and Classification
27 | * Using Online Malware Analysis Services
28 | * Dynamic Analysis of Malware Behaviour
29 | * Building Malware Analysis Sandbox
30 |
31 | * Advanced Malware Analysis
32 | * Introduction to Packers and Crypters
33 | * Manual Unpacking of Malware
34 | * Process Injection Techniques and Analysis
35 | * Malware Anti-analysis Techniques and Evasion
36 |
37 | * Malware Analysis using Memory Forensics
38 | * Live Memory Acquisition Tools and Techniques
39 | * Memory Image Analysis using Volatility
40 | * Kernel Rootkit Analysis using Volatility
41 |
--------------------------------------------------------------------------------
/gitbook/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Summary
2 |
3 | * Introduction to Windows Platform
4 | * [Platform Overview](chapters/windows/platform_overview.md)
5 | * [Windows Debugging Internals](chapters/debugging/windows-debugging-internals.md)
6 | * [RbWinDBG](chapters/debugging/rb_windbg.md)
7 | * [API Hooking](chapters/windows/api_hooking.md)
8 | * [Portable Executable File Format](chapters/pe/pe_file_format.md)
9 | * [x86 Assembly Language](chapters/assembly/x86_assembly.md)
10 | * Malware Analysis
11 | * [Dynamic Malware Analysis](chapters/malware_analysis/dynamic_malware_analysis.md)
12 | * [Memory Dump Analysis](chapters/malware_analysis/memory_dump_analysis.md)
13 | * [Analysing SMC Malware](chapters/malware_analysis/smc_malware_analysis.md)
14 |
15 | * Lab Solutions
16 | * [API Counting](chapters/solutions/win32_api_counting.md)
17 | * [MD5 Hash of Code Section](chapters/solutions/md5_code_section.md)
18 | * [File Identification and Analysis I](chapters/solutions/file_identification_analysis_i.md)
19 | * [Crash Dump Analysis](chapters/solutions/crash_dump_analysis.md)
20 | * [File Identification and Analysis II](chapters/solutions/file_identification_analysis_ii.md)
21 | * [Analysing Process Injection](chapters/solutions/simple_process_injection.md)
22 | * [Zeus Infected Memory Analysis](chapters/solutions/zeus_memory_image.md)
23 | * [Stuxnet Infected Memory Analysis](chapters/solutions/stuxnet_memory_image.md)
24 |
25 |
26 |
--------------------------------------------------------------------------------
/gitbook/chapters/assembly/x86_assembly.md:
--------------------------------------------------------------------------------
1 | # Assembly Language
2 |
3 | An assembly (or assembler) language often abbreviated asm, is a low-level programming language for a computer, or other programmable device, in which there is a very strong (generally one-to-one) correspondence between the language and the architecture's machine code instructions. Each assembly language is specific to a particular computer architecture. In contrast, most high-level programming languages are generally portable across multiple architectures but require interpreting or compiling. Assembly language may also be called symbolic machine code.
4 |
5 | ```c
6 | #include
7 |
8 | int main()
9 | {
10 | printf("Hello World\n");
11 | return 0;
12 | }
13 | ```
14 |
15 | ```bash
16 | $ gcc -m32 -S hello.c
17 | $ cat hello.s
18 | .section __TEXT,__text,regular,pure_instructions
19 | .macosx_version_min 10, 10
20 | .globl _main
21 | .align 4, 0x90
22 | _main: ## @main
23 | ## BB#0:
24 | pushl %ebp
25 | movl %esp, %ebp
26 | subl $24, %esp
27 | calll L0$pb
28 | L0$pb:
29 | popl %eax
30 | leal L_.str-L0$pb(%eax), %eax
31 | movl $0, -4(%ebp)
32 | movl %eax, (%esp)
33 | calll _printf
34 | xorl %ecx, %ecx
35 | movl %eax, -8(%ebp) ## 4-byte Spill
36 | movl %ecx, %eax
37 | addl $24, %esp
38 | popl %ebp
39 | retl
40 |
41 | .section __TEXT,__cstring,cstring_literals
42 | L_.str: ## @.str
43 | .asciz "Hello World\n"
44 |
45 |
46 | .subsections_via_symbols
47 | ```
48 |
49 | ## x86 Architecture and Assembly Language
50 |
51 | The set of instructions supported by the [x86 architecture](https://en.wikipedia.org/wiki/X86) is called the x86 instruction set and the corresponding assembly language is the x86 assembly language. It is a [CISC](https://en.wikipedia.org/wiki/Complex_instruction_set_computing) design based microprocessor architecture. It provides various instructions for data, function, stack, memory and other executive operations required by any modern operating system.
52 |
53 |
54 |
55 | The x86 architecture can operate in any of the following mode:
56 |
57 | * Real
58 | * Protected
59 | * Virtual 8086
60 | * Long
61 |
62 | Any x86 based CPU, old or new always initialises in the 16 bit *Real* mode in which the boot sector software is loaded and executed through the *BIOS* or *UEFI*. The boot loader software in turn locates and load the operating system which in turn setup appropriate operating mode for the CPU. Modern multi-tasking operating system requires the CPU to operate in *Protected* mode so that protected virtual memory, multi-tasking and other required CPU features are available. For CPUs that support the *Long* mode, a 64 bit capable operating system can enable this mode to use 64 bit addressing extension in the CPU.
63 |
64 |
65 |
66 | The x86 architecture supports *privilege rings* so as to enable clear distinction between an executive software such as the OS kernel and a user application such as a browser launched by a user of the operating system. The processor supports specific mechanism such as [call gates][1] or special [system call](https://en.wikipedia.org/wiki/System_call) instructions for changing the privilege level of the CPU. The privilege levels help restrict access to privileged instructions such as those that can change the global state of the system to executive software only.
67 |
68 | ### Memory Management
69 |
70 |
71 |
72 | x86 based CPU operating in *protected* mode uses [Virtual Memory](https://en.wikipedia.org/wiki/Virtual_memory). Any address used to reference the virtual memory is called a virtual address. The memory management unit of the CPU is responsible for translating a virtual address to linear or physical address based on information and support provided by the operating system kernel. The linear or physical address is used to reference any storage unit in the [RAM](https://en.wikipedia.org/wiki/Random-access_memory). This ensures virtual address space for each process in a running system and prevents intended or unintended tampering of each other's memory content by different processes. Operating Systems written for the x86 architecture uses a combination of [Segmentation](https://en.wikipedia.org/wiki/Memory_segmentation) and [Paging](https://en.wikipedia.org/wiki/Paging) for virtual memory management.
73 |
74 | ## Disassembler (IDA Pro)
75 |
76 | A disassembler is a computer program that translates machine language into assembly language—the inverse operation to that of an assembler. A disassembler differs from a decompiler, which targets a high-level language rather than an assembly language. Disassembly, the output of a disassembler, is often formatted for human-readability rather than suitability for input to an assembler, making it principally a reverse-engineering tool.
77 |
78 | [IDA Pro](https://www.hex-rays.com/products/ida/) is the most popular multi-platform multi-architecture disassembler used for professional reverse engineering and malware analysis. The default disassembly of x86 PE File looks as below:
79 |
80 |
81 |
82 |
83 |
84 | # Reference
85 |
86 | *
87 | *
88 | *
89 | *
90 | *
91 | *
92 | *
93 | *
94 |
95 |
96 | [1]:https://en.wikipedia.org/wiki/Call_gate_(Intel)
97 |
98 |
99 |
--------------------------------------------------------------------------------
/gitbook/chapters/debugging/rb_windbg.md:
--------------------------------------------------------------------------------
1 | # RbWinDBG
2 |
3 | *Win32 scriptable debugger in Ruby using Metasm API.*
4 |
5 | **RbWinDBG** is a scriptable debugging written in *Ruby* programming language. It uses *Windows API* and *Metasm* library to provide an easy to use abstract interface to the Windows Debugging functionalities.
6 |
7 | ## Usage
8 |
9 | Basic familiarity with Ruby programming language is required in order to use *RbWinDBG* effectively.
10 |
11 | A script using *RbWinDBG* must load the library first and initialize it:
12 |
13 | ```ruby
14 | require 'rbWinDBG'
15 |
16 | RbWinDBG.init()
17 | ```
18 |
19 | A debugger object can be created using the following code:
20 |
21 | ```ruby
22 | dbg = RbWinDBG.start("C:\\Windows\\System32\\notepad.exe")
23 | ```
24 |
25 | The above code initializes the RbWinDBG instance and internally creates the target process using [CreateProcess][1] API with [DEBUG_PROCESS][2] flag. This means that the target process is created in a suspended state till the debugger instructs the Operating System to continue execution of the process.
26 |
27 | ### Event Callbacks
28 |
29 | Due to the nature of event driven interface of Windows Debugging APIs, RbWinDBG follows event driven programming paradigm. This means scripts using RbWinDBG must define callback code blocks (functions) that will be called when specific events occur in the debugee (target) process.
30 |
31 | #### Event: On Entrypoint
32 |
33 | ```ruby
34 | dbg.on_entrypoint do
35 | ...
36 | end
37 | ```
38 |
39 | #### Event: On Load Library
40 |
41 | ```ruby
42 | dbg.on_library_load do |lib|
43 | ...
44 | end
45 | ```
46 |
47 | #### Event: On Exception
48 |
49 | ```ruby
50 | dbg.on_exception do |exception|
51 | ...
52 | end
53 | ```
54 |
55 | #### Event: Breakpoint Callback
56 |
57 | ```ruby
58 | dbg.bpx(addr) do
59 | ...
60 | end
61 | ```
62 |
63 | ## Sample Debugger using RbWinDBG
64 |
65 | ```ruby
66 | require 'RbWinDBG'
67 |
68 | if __FILE__ == $0
69 | RbWinDBG.init()
70 |
71 | dbg = RbWinDBG.start("C:\\Windows\\System32\\notepad.exe")
72 |
73 | puts "Process Handle: 0x%08x" % [dbg.process.handle]
74 | puts "EP: 0x%08x" % [dbg.entrypoint]
75 |
76 | dbg.on_entrypoint do
77 | puts "Exe Path: " + dbg.process.modules[0].path
78 | puts "Current EIP: 0x%08x" % dbg.get_reg_value(:eip)
79 |
80 | puts 'Kernel32.DLL path: ' + dbg.resolve_lib_path('kernel32.dll')
81 |
82 | puts "CreateFileW: 0x%08x" % dbg.resolve_name('kernel32.dll!CreateFileW')
83 | puts "GetMessageA: 0x%08x" % dbg.resolve_name('user32.dll!GetMessageA')
84 |
85 | puts "VirtualAlloc(0x60): 0x%08x" % [dbg.virtual_alloc(0x60)]
86 |
87 | dbg.bpx(dbg.resolve_name('kernel32.dll!CreateFileW')) do
88 | puts 'CreateFileW: %s' % [dbg.utils.read_wstring(dbg.utils.ptr_at(dbg.get_reg_value(:esp) + 4))]
89 | end
90 |
91 | dbg.on_library_load do |lib|
92 | puts 'LoadLibrary: ' + lib.to_s
93 | end
94 |
95 | dbg.on_exception do |ei|
96 | puts "Process Exception: #{ei[:type]}"
97 | end
98 |
99 | dbg.on_thread_start do |ei|
100 | puts "New Thread Created #{ei.inspect}"
101 | end
102 |
103 | dbg.on_thread_exit do |ei|
104 | puts "Thread Exit #{ei.inspect}"
105 | end
106 | end
107 |
108 | dbg.start
109 | end
110 | ```
111 |
112 | This sample can be run using the following command, assuming RbWinDBG is available in current directory and the script is in samples\BasicTest.rb:
113 |
114 | ```
115 | ruby -I . samples\BasicTest.rb
116 | ```
117 |
118 | 
119 |
120 |
121 |
122 | # Reference
123 |
124 | * [Ruby - Pragmatic Programmers Guide](http://ruby-doc.com/docs/ProgrammingRuby/)
125 | * [RbWinDBG GIT](https://github.com/abhisek/RandomCode/tree/master/RbWinDBG)
126 |
127 |
128 | [1]:
129 |
130 | [2]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
131 |
132 |
--------------------------------------------------------------------------------
/gitbook/chapters/debugging/windows-debugging-internals.md:
--------------------------------------------------------------------------------
1 | # Windows Debugging Internals
2 |
3 | A debugger program essentially leverages Operating System provided programming interfaces to perform certain basic operation on a target process such as:
4 |
5 | * Read or write process memory
6 | * Change process context (registers)
7 | * Receive and respond to debugging events
8 | * Process creation
9 | * Thread creation
10 | * Module Load
11 | * Exception
12 | * etc.
13 |
14 | These fundamental operations supported by an Operating System through appropriate [API][1] allows higher level debugger programs to be written. Higher level abstractions and GUI for reading or writing memory, reading or writing register value, viewing disassembled instructions, setting breakpoints etc. can be implemented using these fundamental APIs.
15 |
16 | ## Breakpoint
17 |
18 | A breakpoint is logically an address of an instruction or data in a debugged process which when set will trigger certain exception and pause or halt the process till it receives a *continue* event from the debugger process. This allows a debugger to pause a process at specific location and analyse process context and in-memory data.
19 |
20 | ## Sample Debugger using Windows API
21 |
22 | ### Debugger Process Privileges
23 |
24 | ```c
25 | static
26 | BOOL DbgEnablePrivilege()
27 | {
28 | HANDLE hToken;
29 | LUID SeDebugNameValue;
30 | TOKEN_PRIVILEGES TokenPrivileges;
31 | BOOL bRet = FALSE;
32 |
33 | if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
34 | {
35 | if(LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &SeDebugNameValue))
36 | {
37 | TokenPrivileges.PrivilegeCount = 1;
38 | TokenPrivileges.Privileges[0].Luid = SeDebugNameValue;
39 | TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
40 |
41 | if(AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
42 | {
43 | CloseHandle(hToken);
44 | bRet = TRUE;
45 | }
46 |
47 | }
48 | }
49 |
50 | return bRet;
51 | }
52 | ```
53 |
54 | ### Starting Target with Debugger Attached
55 |
56 | ```c
57 | BOOL DebugRunProgA(CHAR *szPath, DEBUG_EVENT_HANDLERS *pHandlers)
58 | {
59 | STARTUPINFOA si;
60 | PROCESS_INFORMATION pi;
61 |
62 | DbgEnablePrivilege();
63 |
64 | ZeroMemory(&si, sizeof(si));
65 | si.cb = sizeof(si);
66 | ZeroMemory(&pi, sizeof(pi));
67 |
68 | if(!CreateProcessA(szPath, NULL, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi)) {
69 | DMSG("CreateProcess failed!");
70 | return FALSE;
71 | }
72 |
73 | return DbgEventLoop(pHandlers);
74 | }
75 | ```
76 |
77 | ### The Debugger Loop
78 |
79 | ```c
80 | static
DWORD DbgHandleLoadDll(DEBUG_EVENT *e, DEBUG_EVENT_HANDLERS *pHandlers)
{
LOAD_DLL_DEBUG_INFO *li = &(e->u.LoadDll);
DMSG("DLL Loaded - Handle: 0x%08x BaseAddress: 0x%08x", li->hFile, li->lpBaseOfDll);
return 0;
}
static
BOOL DbgEventLoop(DEBUG_EVENT_HANDLERS *pHandlers)
{
DEBUG_EVENT debug_event;
BOOL bProcExit = FALSE;
while(!bProcExit) {
if(!WaitForDebugEvent(&debug_event, INFINITE))
break;
DMSG("Processing Debug Event: %d", debug_event.dwDebugEventCode);
switch(debug_event.dwDebugEventCode) {
case CREATE_PROCESS_DEBUG_EVENT:
break;
case EXIT_PROCESS_DEBUG_EVENT:
bProcExit = TRUE;
break;
case CREATE_THREAD_DEBUG_EVENT:
break;
case EXIT_THREAD_DEBUG_EVENT:
break;
case LOAD_DLL_DEBUG_EVENT:
DbgHandleLoadDll(&debug_event, pHandlers);
break;
case UNLOAD_DLL_DEBUG_EVENT:
break;
case EXCEPTION_DEBUG_EVENT:
break;
case OUTPUT_DEBUG_STRING_EVENT:
break;
default:
DMSG("Unhandled DebugEvent: 0x%08x", debug_event.dwDebugEventCode);
}
ContinueDebugEvent(debug_event.dwProcessId,
debug_event.dwThreadId, DBG_CONTINUE);
}
return FALSE;
}
81 | ```
82 |
83 |
84 | [1]: https://msdn.microsoft.com/en-in/library/windows/desktop/ff818516(v=vs.85).aspx
--------------------------------------------------------------------------------
/gitbook/chapters/malware_analysis/dynamic_malware_analysis.md:
--------------------------------------------------------------------------------
1 | # Dynamic Malware Analysis
2 |
3 | Dynamic malware analysis is the process of running a malicious sample in a *contained* environment while observing its various behavioural activity. This can be as simple as running a malicious sample in a virtual machine with [Procmon](https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx) or as complex as building a custom container with kernel mode instrumentation for logging behavioural activity of a given sample.
4 |
5 | ## Containment
6 |
7 | Malware analysis environment must ensure that it is segregated from other network and systems. Any malware activity must be contained within the analysis environment. For this reason, it is important to setup a sandbox or VM based contained environment that can be easily configured to emulate required platform.
8 |
9 | ## Malware Analysis with Sandboxie and Fakenet
10 |
11 | [Sandboxie](http://www.sandboxie.com/) is a user space sandboxing tool for applications. It can be used to contain all file system changes by a sandboxed application within the sandbox to prevent any actual change in the operating system. Sandboxie provides the required containment for malware analysis purpose. Along with [Buster Sandbox Analyzer](http://bsa.isoftware.nl/), a user mode dynamic malware analysis environment can be setup easily. For network access simulation within our contained environment, we will use the [Fakenet](https://practicalmalwareanalysis.com/fakenet/) program.
12 |
13 | ### Installation
14 |
15 | * Install Sandboxie
16 | * Install BSA by extracting provided *rar* to C:\BSA
17 | * Copy LOG_API.DLL from architecture specific directory to *C:\BSA\LOG_API.DLL*
18 | * Copy C:\BSA\LOG_API\32\LOG_API.DLL to C:\BSA\LOG_API.DLL
19 | * Edit Sandboxie configuration file to create a new sandbox configuration:
20 |
21 | ```
22 | [BSABOX]
23 |
24 | Enabled=y
25 | ConfigLevel=7
26 | BorderColor=#00FFFF,off
27 | InjectDll=C:\BSA\LOG_API.DLL
28 | OpenWinClass=TFormBSA
29 | NotifyDirectDiskAccess=y
30 | ProcessLimit1=20
31 | ProcessLimit2=30
32 | SbieCtrl_HideMessage=*
33 | BoxNameTitle=n
34 | CopyLimitKb=102400
35 | CopyLimitSilent=y
36 | ```
37 |
38 | * Run notepad.exe in the new sandbox to initialise directory structure
39 | * Copy path to new sandbox directory to BSA
40 |
41 |
42 |
43 | ### Workflow
44 |
45 | * Run Sandboxie
46 | * Run BSA
47 | * Start BSA Analysis
48 | * Run Fakenet
49 | * Run Sample in BSA configured Sandbox
50 |
51 |
52 |
53 | ## Malware Analysis with Cuckoo Sandbox
54 |
55 | The [Cuckoo Sandbox](https://github.com/cuckoosandbox/cuckoo) provides an automated analysis environment for malware analysis. It can use [VirtualBox]() or [VMware]() as the virtual environment to run malware samples while tracing its behaviour.
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/gitbook/chapters/malware_analysis/memory_dump_analysis.md:
--------------------------------------------------------------------------------
1 | # Memory Dump Analysis
2 |
3 | Malware analysis tools largely depends on the underlying operating system especially the kernel to provide accurate information. If the integrity of the operating system kernel is compromised then results produced by various conventional malware analysis tools will be inaccurate.
4 |
5 | Advanced malwares such as [Stuxnet](https://www.wired.com/2014/11/countdown-to-zero-day-stuxnet/) or [Duqu](https://securelist.com/blog/research/70641/the-duqu-2-0-persistence-module/) may attack the kernel of the infected OS which in turn may produce incorrect information to user-space tools including those used for malware analysis.
6 |
7 | Memory dump analysis is a reliable approach towards malware analysis particularly in scenarios where the infected system cannot be trusted to produce appropriate information to user-space malware analysis tools.
8 |
9 | ## Live Memory Acquisition
10 |
11 | Live memory acquisition is the process of obtaining the memory snapshot of a live system with minimum intervention to the running system. The objective is to acquire full contents of the physical memory including user data, system data and operating system data structures. This process is particularly useful during forensic analysis so as to preserve all evidences at the time of snapshot.
12 |
13 | While there are multiple tools for live memory acquisition for Windows and Linux based Operating System, for the purpose of malware analysis, we can use VMware VMem files that contain the physical memory snapshot of a virtual machine at any point while the VM is running.
14 |
15 | ## Memory Dump Analysis with Volatility
16 |
17 | [Volatility](https://github.com/volatilityfoundation/volatility) is one of the most popular free and open source tools for memory dump analysis. The tool supports multiple version of popular operating systems such as Windows, Linux, OSX.
18 |
19 | ### Volatility Usage
20 |
21 | Identify the operating system of the image so as to use a suitable OS profile:
22 |
23 | ```bash
24 | $ vol.py -f be2.vmem imageinfo
25 | Volatility Foundation Volatility Framework 2.5
26 | INFO : volatility.debug : Determining profile based on KDBG search...
27 | Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)
28 | AS Layer1 : IA32PagedMemoryPae (Kernel AS)
29 | AS Layer2 : FileAddressSpace (/Volumes/SSD1/REMA/Memory Images/be2.vmem)
30 | PAE type : PAE
31 | DTB : 0x319000L
32 | KDBG : 0x80544ce0L
33 | Number of Processors : 1
34 | Image Type (Service Pack) : 2
35 | KPCR for CPU 0 : 0xffdff000L
36 | KUSER_SHARED_DATA : 0xffdf0000L
37 | Image date and time : 2010-08-15 19:22:11 UTC+0000
38 | Image local date and time : 2010-08-15 15:22:11 -0400
39 | ```
40 |
41 | Once a suitable profile has been identified, all subsequent commands must be run with the appropriate profile set.
42 |
43 | #### Enumerate network connections
44 |
45 | ```bash
46 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 connections
47 | Volatility Foundation Volatility Framework 2.5
48 | Offset(V) Local Address Remote Address Pid
49 | ---------- ------------------------- ------------------------- ---
50 | ```
51 |
52 | ```bash
53 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 connscan
54 | Volatility Foundation Volatility Framework 2.5
55 | Offset(P) Local Address Remote Address Pid
56 | ---------- ------------------------- ------------------------- ---
57 | 0x02214988 172.16.176.143:1034 131.107.115.254:80 1260
58 | 0x06015ab0 172.16.176.143:1037 131.107.115.254:443 1260
59 | ```
60 |
61 | #### Process Enumeration
62 |
63 | ```bash
64 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 pslist
65 | Volatility Foundation Volatility Framework 2.5
66 | Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit
67 | ---------- -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------
68 | 0x810b1660 System 4 0 59 179 ------ 0
69 | 0xff2ab020 smss.exe 544 4 3 21 ------ 0 2010-08-11 06:06:21 UTC+0000
70 | 0xff1ecda0 csrss.exe 608 544 11 400 0 0 2010-08-11 06:06:23 UTC+0000
71 | 0xff1ec978 winlogon.exe 632 544 22 519 0 0 2010-08-11 06:06:23 UTC+0000
72 | 0xff247020 services.exe 676 632 16 268 0 0 2010-08-11 06:06:24 UTC+0000
73 | 0xff255020 lsass.exe 688 632 22 348 0 0 2010-08-11 06:06:24 UTC+0000
74 | 0xff218230 vmacthlp.exe 844 676 1 24 0 0 2010-08-11 06:06:24 UTC+0000
75 | 0x80ff88d8 svchost.exe 856 676 19 321 0 0 2010-08-11 06:06:24 UTC+0000
76 | 0xff217560 svchost.exe 936 676 9 261 0 0 2010-08-11 06:06:24 UTC+0000
77 | 0x80fbf910 svchost.exe 1028 676 87 1394 0 0 2010-08-11 06:06:24 UTC+0000
78 | [...]
79 | ```
80 |
81 | ```bash
82 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 psscan
83 | Volatility Foundation Volatility Framework 2.5
84 | Offset(P) Name PID PPID PDB Time created Time exited
85 | ------------------ ---------------- ------ ------ ---------- ------------------------------ ------------------------------
86 | 0x000000000107e020 cmd.exe 1572 476 0x06cc0320 2010-08-15 19:21:27 UTC+0000 2010-08-15 19:21:27 UTC+0000
87 | 0x00000000010c3da0 wuauclt.exe 1732 1028 0x06cc02c0 2010-08-11 06:07:44 UTC+0000
88 | 0x00000000010f7588 wuauclt.exe 468 1028 0x06cc0180 2010-08-11 06:09:37 UTC+0000
89 | 0x0000000001122910 svchost.exe 1028 676 0x06cc0120 2010-08-11 06:06:24 UTC+0000
90 | 0x000000000115b8d8 svchost.exe 856 676 0x06cc00e0 2010-08-11 06:06:24 UTC+0000
91 | [...]
92 | ```
93 |
94 | ```bash
95 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 pstree
96 | [...]
97 | 0xff3865d0:explorer.exe 1724 1708 13 309 2010-08-11 06:09:29 UTC+0000
98 | . 0xff374980:VMwareUser.exe 452 1724 8 203 2010-08-11 06:09:32 UTC+0000
99 | . 0xff3667e8:VMwareTray.exe 432 1724 1 49 2010-08-11 06:09:31 UTC+0000
100 | . 0xff1f6da0:1e0f1b9b697ab49 476 1724 0 ------ 2010-08-15 19:21:25 UTC+0000
101 | .. 0x80f1b020:cmd.exe 1572 476 0 ------ 2010-08-15 19:21:27 UTC+0000
102 | ```
103 |
104 | #### SSDT Enumeration
105 |
106 | The [System Service Dispatcher Table](https://en.wikipedia.org/wiki/System_Service_Descriptor_Table) is a kernel data structure used to map system calls with their handler function. Usually all system call handlers are located in the core Windows kernel components such as *win32k.sys* or *ntoskrnl.exe* except if they are hooked by any malicious driver:
107 |
108 | ```bash
109 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 ssdt | grep -v win32k.sys | grep -v ntoskrnl.exe
110 |
111 | Volatility Foundation Volatility Framework 2.5
112 | [x86] Gathering all referenced SSDTs from KTHREADs...
113 | Finding appropriate address space for tables...
114 | SSDT[0] at ff3aab90 with 284 entries
115 | Entry 0x0041: 0xff0d2487 (NtDeleteValueKey) owned by 00004A2A
116 | Entry 0x0047: 0xff0d216b (NtEnumerateKey) owned by 00004A2A
117 | Entry 0x0049: 0xff0d2267 (NtEnumerateValueKey) owned by 00004A2A
118 | Entry 0x0077: 0xff0d20c3 (NtOpenKey) owned by 00004A2A
119 | Entry 0x007a: 0xff0d1e93 (NtOpenProcess) owned by 00004A2A
120 | Entry 0x0080: 0xff0d1f0b (NtOpenThread) owned by 00004A2A
121 | Entry 0x0089: 0xff0d2617 (NtProtectVirtualMemory) owned by 00004A2A
122 | Entry 0x00ad: 0xff0d1da0 (NtQuerySystemInformation) owned by 00004A2A
123 | Entry 0x00ba: 0xff0d256b (NtReadVirtualMemory) owned by 00004A2A
124 | Entry 0x00d5: 0xff0d2070 (NtSetContextThread) owned by 00004A2A
125 | Entry 0x00f7: 0xff0d2397 (NtSetValueKey) owned by 00004A2A
126 | Entry 0x00fe: 0xff0d201d (NtSuspendThread) owned by 00004A2A
127 | Entry 0x0102: 0xff0d1fca (NtTerminateThread) owned by 00004A2A
128 | Entry 0x0115: 0xff0d25c1 (NtWriteVirtualMemory) owned by 00004A2A
129 | SSDT[0] at 80f162d0 with 284 entries
130 | Entry 0x0041: 0xff0d2487 (NtDeleteValueKey) owned by 00004A2A
131 | Entry 0x0047: 0xff0d216b (NtEnumerateKey) owned by 00004A2A
132 | Entry 0x0049: 0xff0d2267 (NtEnumerateValueKey) owned by 00004A2A
133 | Entry 0x0077: 0xff0d20c3 (NtOpenKey) owned by 00004A2A
134 | Entry 0x007a: 0xff0d1e93 (NtOpenProcess) owned by 00004A2A
135 | Entry 0x0080: 0xff0d1f0b (NtOpenThread) owned by 00004A2A
136 | Entry 0x0089: 0xff0d2617 (NtProtectVirtualMemory) owned by 00004A2A
137 | Entry 0x00ad: 0xff0d1da0 (NtQuerySystemInformation) owned by 00004A2A
138 | Entry 0x00ba: 0xff0d256b (NtReadVirtualMemory) owned by 00004A2A
139 | Entry 0x00d5: 0xff0d2070 (NtSetContextThread) owned by 00004A2A
140 | Entry 0x00f7: 0xff0d2397 (NtSetValueKey) owned by 00004A2A
141 | Entry 0x00fe: 0xff0d201d (NtSuspendThread) owned by 00004A2A
142 | Entry 0x0102: 0xff0d1fca (NtTerminateThread) owned by 00004A2A
143 | Entry 0x0115: 0xff0d25c1 (NtWriteVirtualMemory) owned by 00004A2A
144 | SSDT[0] at 80501030 with 284 entries
145 | SSDT[1] at bf997600 with 667 entries
146 | ```
147 |
148 | List the base address of the possibly malicious kernel driver:
149 |
150 | ```bash
151 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 modules
152 | [...]
153 | 0x80fb16c0 wdmaud.sys 0xf3147000 0x15000 \SystemRoot\system32\drivers\wdmaud.sys
154 | 0xff381bd8 sysaudio.sys 0xf337d000 0xf000 \SystemRoot\system32\drivers\sysaudio.sys
155 | 0x80fae8b0 kmixer.sys 0xf2fe0000 0x2a000 \SystemRoot\system32\drivers\kmixer.sys
156 | 0xff2837e8 Fastfat.SYS 0xf2ef5000 0x23000 \SystemRoot\System32\Drivers\Fastfat.SYS
157 | 0xff375b08 00004A2A 0xff0d1000 0x8361 00004A2A
158 | ```
159 |
160 | Extract the possibly malicious kernel driver:
161 |
162 | ```bash
163 | $ vol.py -f be2.vmem --profile=WinXPSP2x86 moddump -b 0xff0d1000 -D /tmp/
164 | Volatility Foundation Volatility Framework 2.5
165 | Module Base Module Name Result
166 | ----------- -------------------- ------
167 | 0x0ff0d1000 00004A2A OK: driver.ff0d1000.sys
168 | ```
169 |
170 | We then upload the extracted driver to [VirusTotal](http://www.virustotal.com) for a multi-AV scan:
171 |
172 |
173 |
174 | ### Inference
175 |
176 | In the above example, we start by looking at possibly malicious network connections. However in *connscan* the only network connection we find was made to 131.107.115.254. A *whois* lookup on this IP address reveals that the network range is owned by Microsoft which makes it an unlikely C&C controller IP address.
177 |
178 | Then we attempt to find possibly malicious process. Unable to find any malicious activity in user-mode, we continue our investigation for malicous code running as part of the kernel.
179 |
180 | One of the most common kernel rootkit technique on Windows playform is [SSDT Hooking](http://resources.infosecinstitute.com/hooking-system-service-dispatch-table-ssdt/). In this technique, a malicious driver can hook important system functions by redirecting them at SSDT. We use the heuristic that all SSDT functions will by default point to core Windows kernel components such as win32k.sys or ntoskrnl.exe. Any SSDT function pointing outside core Windows kernel is possibly hooked. Using this heuristic we find a malicious driver which when extracted and submitted to VirusTotal confirms our assumption.
181 |
182 |
183 | # References
184 |
185 |
186 |
187 |
188 |
189 |
190 |
--------------------------------------------------------------------------------
/gitbook/chapters/malware_analysis/smc_malware_analysis.md:
--------------------------------------------------------------------------------
1 | # SMC Malware Analysis
2 |
3 | Self-modifying-code (SMC) is a common technique applied by advanced malware to evade static or signature based detection. These malware heavily obfuscate its original code under husks in order to make analysis difficult and time consuming process.
4 |
5 | While custom tools or scripts may be required in order to analyse such malware, however the generic approach can be used against most samples:
6 |
7 | * Identify decoder code
8 | * Identify decoded code
9 | * Extract decoded code at the time of execution
10 |
11 | For our sample, we start by inspecting it in [CFF Explorer]():
12 |
13 |
14 |
15 | We then load the executable in IDA pro to inspect its functionality statically:
16 |
17 |
18 |
19 |
20 |
21 |
22 | The executable appears to open a [HANDLE]() to *explorer.exe* process and if found, inject and execute some code into it.
23 |
24 |
25 |
26 | We use [HiDump](https://github.com/abhisek/RandomCode/tree/master/Malware/HiDump) tool to dynamically extract the injected code from the sample:
27 |
28 |
29 |
30 | While the injected code must be native architecture specific code, there is no requirement for it to be a PE executable. The injected code can be any [PIC](https://en.wikipedia.org/wiki/Position-independent_code) that can run on the target architecture and OS platform. This is what we find when we load the extracted code into [IDA Pro]().
31 |
32 |
33 |
34 | After manual fixup, we can read the x86 assembly of the injected code:
35 |
36 |
37 |
38 | In order to dynamically analyse the injected code in a debugger, we develop a small script that can load and execute the injected code in memory while giving us control through a debugger:
39 |
40 | ```ruby
41 | print "[*] Press [enter] to continue .."
42 | $stdin.gets
43 |
44 | code = File.binread(ARGV[0])
45 | code = "\xcc" + code
46 |
47 | process = ::Metasm::WinOS::Process.new(::Metasm::WinAPI.getcurrentprocessid)
48 | ::Metasm::WinOS.inject_run_shellcode(process, code)
49 |
50 | puts "[*] Shellcode executed.. "
51 | loop do
52 | puts "[*] Sleeping .."
53 | sleep(5)
54 | end
55 | ```
56 |
57 | The above Ruby script with execute the supplied code from file with a [int3](https://en.wikipedia.org/wiki/INT_(x86_instruction)) software interrupt instruction prepended. This will ensure that we get control in attached debugger immediately before the extracted code is executed. Once we are in debugger control, we can manually single-step or trace execution to identify the actual code.
58 |
59 | We identify two types of encoders while stepping through the injected code in debugger:
60 |
61 |
62 |
63 | At some point, we identify that the decoded code has a valid PE header:
64 |
65 |
66 |
67 | We dump the data from memory where we identified valid PE header:
68 |
69 |
70 |
71 | Finally we open the dumped PE file which when analysed in [IDA Pro]() reveals the true form of the injected code:
72 |
73 |
--------------------------------------------------------------------------------
/gitbook/chapters/pe/pe_file_format.md:
--------------------------------------------------------------------------------
1 | # Portable Executable (PE) File Format
2 |
3 | ## Background
4 |
5 | The Portable Executable (PE) format is a file format for executables, object code, DLLs, FON Font files, and others used in 32-bit and 64-bit versions of Windows operating systems. The PE format is a data structure that encapsulates the information necessary for the Windows OS loader to manage the wrapped executable code. This includes dynamic library references for linking, API export and import tables, resource management data and thread-local storage (TLS) data. On NT operating systems, the PE format is used for EXE, DLL, SYS (device driver), and other file types.
6 |
7 | ## Headers
8 |
9 |
10 | 
11 | Source
12 |
13 |
14 | The [CFF Explorer](http://www.ntcore.com/exsuite.php) tool can be used to visualize PE Header and perform multiple operation including editing or dumping PE section to disk, scanning for packer signatures etc.
15 |
16 | ## Loading Process
17 |
18 | The PE File Format defines a specification for code and data along with meta-information that is required by the PE loader to correctly load and prepare the executable in memory. The loading process as peformed by the PE Loader is as follows:
19 |
20 | * Header Processing
21 | * Section Mapping
22 | * IAT Resolution
23 | * Relocation
24 | * Execute Entrypoint
25 |
26 | ## Developing a Custom PE Loader
27 |
28 | A custom PE Loader is useful in various scenarios including:
29 |
30 | * Dynamic Analysis
31 | * Crypter / Loader Development
32 | * Runtime Instrumentation
33 |
34 | In order to develop a custom PE loader, the loader program must perform all the preparation and initialization tasks as performed by the original system PE Loader.
35 |
36 | A proof of concept implementation of PE Loader is available at [Github](https://github.com/abhisek/Pe-Loader-Sample).
37 |
38 | ## Scripting PE File Format
39 |
40 | The [Metasm](https://github.com/jjyg/metasm) library can be used for scripting the PE File Format in [Ruby](http://www.ruby-lang.org).
41 |
42 | ```ruby
43 | $:.unshift("C:\\Lib\\metasm")
44 | require 'metasm'
45 |
46 | def dump_pe(arg)
47 | pe = Metasm::PE.decode_file(arg)
48 |
49 | puts "----- PE Headers ------"
50 | puts "Machine: " + pe.header.machine
51 | puts "Number of Sections: " + pe.header.num_sect.to_s
52 | puts "Number of Symbols: " + pe.header.num_sym.to_s
53 | puts "Characteristics: " + pe.header.characteristics.inspect
54 | puts ""
55 | puts "Image Base: 0x%08x" % [pe.optheader.image_base]
56 | puts "Image Size: 0x%08x" % [pe.optheader.image_size]
57 | puts "Address of Entry Point: 0x%08x" % [pe.optheader.entrypoint]
58 | puts "Base of Code: 0x%08x" % [pe.optheader.base_of_code]
59 | puts "Base of Data: 0x%08x" % [pe.optheader.base_of_data]
60 | puts "File Alignment: 0x%08x" % [pe.optheader.file_align]
61 | puts "Section Alignment: 0x%08x" % [pe.optheader.sect_align]
62 | puts "-----------------------"
63 | puts ""
64 | puts "---- PE Sections --------"
65 | pe.sections.each do |section|
66 | puts " Name: " + section.name
67 | puts " Raw Address: 0x%08x" % [section.rawaddr]
68 | puts " Raw Size: 0x%08x" % [section.rawsize]
69 | puts " Virtual Address: 0x%08x" % [section.virtaddr]
70 | puts " Virtual Size: 0x%08x" % [section.virtsize]
71 | puts ""
72 | end
73 | puts "-------------------------"
74 | puts "------ PE Imports -------"
75 | pe.imports.each do |import|
76 | puts " Library: " + import.libname
77 | import.imports.each do |imp|
78 | puts " " + (imp.name || imp.target)
79 | end
80 | puts ""
81 | end unless pe.imports.nil?
82 | puts "-------------------------"
83 | puts "------ PE Exports -------"
84 | pe.export.exports.each do |exp|
85 | puts " ORD: #{exp.ordinal} RAV: 0x%08x NAME: #{exp.name}" % [exp.target_rva]
86 | end unless pe.export.nil?
87 | puts "-------------------------"
88 | end
89 |
90 | if __FILE__ == $0
91 | if ARGV.size < 1
92 | puts "Usage: "
93 | puts "#{$0} [PE]"
94 | puts ""
95 | exit
96 | end
97 |
98 | dump_pe(ARGV[0].to_s)
99 | end
100 | ```
101 |
102 |
103 | ## Reference
104 |
105 | *
106 | *
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/crash_dump_analysis.md:
--------------------------------------------------------------------------------
1 | # Crash Dump Analysis
2 |
3 | ## Description
4 |
5 | A crash dump file is provided as input which was generated when an executable program crashed during runtime. The task requires extracting the executable from the crash dump and avoiding the cause of crash.
6 |
7 | ## Solution
8 |
9 | In order to process the crash dump, it is first required to identify the file format for the crash dump. This was done by using a hex editor to visualize the first few bytes of the crash dump file:
10 |
11 | ```bash
12 | $ xxd crash.dmp | head -n 10
13 | 0000000: 4d44 4d50 93a7 016b 0d00 0000 2000 0000 MDMP...k.... ...
14 | 0000010: 0000 0000 fe5c 094f 2618 0400 0000 0000 .....\.O&.......
15 | 0000020: 0300 0000 3400 0000 8402 0000 1100 0000 ....4...........
16 | 0000030: 4c00 0000 b802 0000 0400 0000 2002 0000 L........... ...
17 | 0000040: 0403 0000 1300 0000 a002 0000 2405 0000 ............$...
18 | 0000050: 0900 0000 3003 0000 9c22 0000 1000 0000 ....0...."......
19 | 0000060: a00f 0000 fc12 0000 0600 0000 a800 0000 ................
20 | 0000070: dc01 0000 0700 0000 3800 0000 bc00 0000 ........8.......
21 | 0000080: 0f00 0000 e800 0000 f400 0000 0c00 0000 ................
22 | 0000090: 7801 0000 8411 0000 0000 0000 0000 0000 x...............
23 |
24 | ```
25 |
26 | The **MDMP** magic keyword indicates that the file is in [WinDBG][1] Minidump format. This file can be opened in WinDBG and the executable that crashed can be extracted using relevant WinDBG commands.
27 |
28 | List loaded modules including executable:
29 |
30 | ```
31 | 0:000> lm
32 | start end module name
33 | 00400000 0040e000 Stub (deferred)
34 | 77f10000 77f59000 gdi32 (deferred)
35 | 7c800000 7c8f6000 kernel32 (deferred)
36 | 7c900000 7c9af000 ntdll (pdb symbols) c:\symbols\ntdll.pdb\1751003260CA42598C0FB326585000ED2\ntdll.pdb
37 | 7e410000 7e4a1000 user32 (deferred)
38 | ```
39 |
40 | The start and end address of the executable in crash dump can be identified as *0x00400000* and *0x0040e000*
41 |
42 | In order to reconstruct the executable, we need to extract the content of this memory range from the crash dump file:
43 |
44 | ```
45 | 0:000> .writemem C:\tmp\1.mem 00400000 0040e000
46 | Writing e001 bytes............................
47 | ```
48 |
49 | Additionally the cause of the crash can be identified as *Access Violation* due to invalid address loaded in the [Instruction Pointer][2] EIP register.
50 |
51 | ```
52 | (a60.73c): Access violation - code c0000005 (first/second chance not available)
53 | eax=0000978f ebx=00000001 ecx=a1840000 edx=82839b00 esi=00000000 edi=fffffffe
54 | eip=deadbabe esp=0012feec ebp=0012ff30 iopl=0 nv up ei ng nz na pe nc
55 | cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286
56 | deadbabe ?? ???
57 |
58 | 0:000> r @eip
59 | eip=deadbabe
60 | ```
61 |
62 | ### PE File Reconstruction from Memory Image
63 |
64 | The extracted memory content can be verified to be a valid PE executable image using a hex editor and inspecting the header bytes or by using a tool such as CFF Explorer that recognizes the PE file format:
65 |
66 | 
67 |
68 | However this memory content cannot be run as a PE executable directly as it is in a form known as **Loaded PE**. This means the memory content is processed by the Operating System's PE Loader and loaded as per *VirtualAddress* offset of section headers. The PE section data for each section is at a distance of *VirtualAddress* bytes from the base as defined in its section header. However for a PE executable file, the section data should be *PointerToRawData* bytes from the start of the file. In order to *fix* this image we need to move PE section data for each section from *VirtualAddress* offset from base to *PointerToRawData* offset from base of file. This can be done either by writing a C program or using a library that understands PE file format such as [Metasm][3].
69 |
70 | The following Ruby script can fix the extracted file and prepare a *runnable* executable from it.
71 |
72 | ```ruby
73 | $:.unshift("C:\\Lib\\metasm")
74 | require 'metasm'
75 |
76 | if __FILE__ == $0
77 | pe = Metasm::LoadedPE.load(File.binread(ARGV[0]), 0x00400000)
78 | pe.decode_header
79 | pe.decode_imports
80 |
81 | pe.cpu # CPU needs a reference to initialize correctly
82 | pe.invalidate_header
83 | pe.encode_file("1.exe")
84 | end
85 | ```
86 |
87 |
88 | [1]:
89 |
90 | [2]:
91 |
92 | [3]:
32 |
33 | We see that the entrypoint saves value of all registers using the *pusha* instruction. In order to find an appropriate epilogue, we search for *popa* instruction assuming that at somepoint in code, the saved values will be restored before transferring control to Original Entrypoint (OEP). We set a breakpoint at the *popa* instruction and execute the sample till the breakpoint is hit:
34 |
35 |
36 |
37 | On breakpoint hit, we can see the subsequent *jmp* instruction points to newly generated code which should be the unpacked code we are looking for:
38 |
39 |
40 |
41 | We then single-step to the OEP code and create a new executable from memory using [OllyDumpEx](https://low-priority.appspot.com/ollydumpex/) plugin:
42 |
43 |
44 |
45 | Finally we fix the Import Address Table (IAT) of the dumped executable using the [Scylla](https://github.com/NtQuery/Scylla) plugin:
46 |
47 |
48 |
49 | At this point we have successfully unpacked the UPX packed executable manually. This can be verified by loading the newly created executable in IDA pro:
50 |
51 |
52 |
53 |
54 | [1]:
55 |
56 | [2]:
57 |
58 | [3]:
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/file_identification_analysis_ii.md:
--------------------------------------------------------------------------------
1 | # File Identification and Analysis - II
2 |
3 | ## Description
4 |
5 | A compressed PE executable is provided. The task involves decompressing the executable to find a hidden string inside the executable.
6 |
7 | ## Solution
8 |
9 | Similar to previous compressed executable analysis, we start by identifying the packer/compressor used in the sample using [PEiD][1] tool.
10 |
11 |
12 |
13 | The [PEiD][1] tools suggests that the sample is packed with [ASPack](http://www.aspack.com/). Unlike UPX, ASPack does not support decompression or unpacking of executable by itself. For this reason, we will have to manually unpack the executable. We will follow a _dynamic_ approach to unpack the sample and obtain the original executable. The approach can be summarized as:
14 |
15 | * Identify loader code
16 | * Identify Original Entry Point (OEP)
17 | * Run sample in debugger while breaking in code that transitions to OEP
18 | * Re-construct PE image from memory
19 |
20 | Additionally we identify that the sample has two non-standard PE sections named *.aspack* and *.adata*. The *Entrypoint* in PE header points to *.aspack* section. This indicates that the *.aspack* section possibly contains the packer generated loader code that is responsibile for unpacking or decompressing original code before transferring control to it.
21 |
22 | We start by disassembling the sample in [IDA Pro](https://www.hex-rays.com/products/ida/):
23 |
24 |
25 |
26 |
27 | The procedure prelog starts with a _pusha_ instruction that pushes the value of all registers to the stack. We manually analyse the loader code to identify a possible _popa_ instruction that should restore the register values from stack. This *may* indicate the epilogue of the loader code. We find a very interesting sequence of instructions near the expected epilogue:
28 |
29 |
30 |
31 |
32 |
33 | ```asm
34 | push 0
35 | ret
36 | ```
37 |
38 | The above two instructions, when execution, should result in a process crash with _EIP_ register set to 0 (NULL) which in most cases and definitely in case of our sample points to unmapped memory.
39 |
40 | In order to identify what happens at runtime, we debug the sample in [x64Dbg](http://x64dbg.com/) with [OllyDumpEx](https://low-priority.appspot.com/ollydumpex/) plugin. We set a breakpoint at 0x0040F420 which is the address of *push 0* instruction. On breakpoint hit, it was found that the NULL value is overwritten with a address of valid instruction that will be executed when the *ret* instruction follows:
41 |
42 |
43 |
44 | We manually single-step instructions till the newly discovered address is reached. At this point we reconstruct a new PE image from memory of our target process using
45 | [OllyDumpEx](https://low-priority.appspot.com/ollydumpex/) plugin:
46 |
47 |
48 |
49 | While the newly created PE image may be recognized by IDA pro, it will probably not run correctly due to a broken import address table (IAT). We will need to rebuild the IAT so that the newly dumped executable can run correctly. This can be done using the [Scylla](https://github.com/NtQuery/Scylla) tool integrated with [x64Dbg](http://x64dbg.com/):
50 |
51 |
52 |
53 | At this point, we have fully recovered the original executable by identifying the OEP and reconstructing unpacked executable from the memory of the packed executable at runtime. This can be confirmed by loading the reconstructed executable in IDA pro:
54 |
55 |
56 |
57 |
58 | [1]:
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/malware_anti_analysis.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/chapters/solutions/malware_anti_analysis.md
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/md5_code_section.md:
--------------------------------------------------------------------------------
1 | # MD5 Hash of Code Section
2 |
3 | ## Description
4 |
5 | An executable file is provided as input. The task is to compute MD5 checksum of only the code section of the input file.
6 |
7 | ## Solution
8 |
9 | A [Portable Executable](#) file is organized in terms of multiple sections. As a convention, most compilers use *.text* as the name for the text section in a PE file. It is possible to view and dump the contents of only *.text* section using [CFF Explorer Suite][1].
10 |
11 | 
12 |
13 | Once the contents of the *.text* section is dumped to file, it is possible to compute the MD5 checksum of the content using [WinMD5][2] tool or any other appropriate checksum computation tool:
14 |
15 | 
16 |
17 |
18 | [1]:
19 | [2]:
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/simple_process_injection.md:
--------------------------------------------------------------------------------
1 | # Simple Process Injection
2 |
3 | ## Description
4 |
5 | An executable is provided. This executable injects code into some other process. The objective is to analyse the injected code and find the solution *key*.
6 |
7 | ## Solution
8 |
9 | There are multiple [process injection techniques](http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces) using which a process can inject and execute code from another process on Windows platform. One of the most common technique involves:
10 |
11 | * Open a [handle][1] to the target process.
12 | * Allocate memory in the target process using [VirtualAllocEx][2].
13 | * Write injected code in the newly allocated memory using [WriteProcessMemory][3].
14 | * Execute injected code using [CreateRemoteThread][4].
15 |
16 | If a given sample uses this method of process injection, then the injected code can be extracted from memory at the time it is being written to the target process.
17 |
18 | We set a breakpoint in *kernel32!WriteProcessMemory*, when the breakpoint is triggered, we can identify the address and size of data being written to target process:
19 |
20 |
21 |
22 | The content of the inject data indicates that a PE file is being injected into the remote process:
23 |
24 |
25 |
26 | At this point, all we need to do is to dump the content of memory from where code is being injected to the target process:
27 |
28 |
29 |
30 | The dumped file was found to be a valid PE (DLL) file. We can analyse this file in IDA pro to identify the solution:
31 |
32 |
33 |
34 | ## Automated Extraction using HiDump
35 |
36 | The process for manual extraction of injected code described above is automated in [HiDump](https://github.com/abhisek/RandomCode/tree/master/Malware/HiDump) tool. This tool can be used to extract injected code through dynamic anaysis:
37 |
38 |
39 |
40 |
41 | [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724457(v=vs.85).aspx
42 | [2]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366890(v=vs.85).aspx
43 | [3]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681674(v=vs.85).aspx
44 | [4]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682437(v=vs.85).aspx
45 |
46 |
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/stuxnet_memory_image.md:
--------------------------------------------------------------------------------
1 | # Stuxnet Infected Memory Dump Analysis
2 |
3 | ## Description
4 |
5 | A memory image of a live system infected with Stuxnet malware is provided. The objective is to analyse and identify IOC.
6 |
7 | ## Solution
8 |
9 | We start by identifying a suitable profile for the memory image:
10 |
11 | ```bash
12 | $ vol.py -f stuxnet.vmem imageinfo
13 | Volatility Foundation Volatility Framework 2.5
14 | INFO : volatility.debug : Determining profile based on KDBG search...
15 | Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)
16 | AS Layer1 : IA32PagedMemoryPae (Kernel AS)
17 | AS Layer2 : FileAddressSpace (/Volumes/SSD1/REMA/Memory Images/stuxnet.vmem)
18 | PAE type : PAE
19 | DTB : 0x319000L
20 | KDBG : 0x80545ae0L
21 | Number of Processors : 1
22 | Image Type (Service Pack) : 3
23 | KPCR for CPU 0 : 0xffdff000L
24 | KUSER_SHARED_DATA : 0xffdf0000L
25 | Image date and time : 2011-06-03 04:31:36 UTC+0000
26 | Image local date and time : 2011-06-03 00:31:36 -0400
27 | ```
28 |
29 | We then try to identify possible connections to any command and control infrastructure:
30 |
31 | ```bash
32 | $ vol.py -f stuxnet.vmem connections
33 | Volatility Foundation Volatility Framework 2.5
34 | Offset(V) Local Address Remote Address Pid
35 | ---------- ------------------------- ------------------------- ---
36 | $ vol.py -f stuxnet.vmem connscan
37 | Volatility Foundation Volatility Framework 2.5
38 | Offset(P) Local Address Remote Address Pid
39 | ---------- ------------------------- ------------------------- ---
40 | ```
41 |
42 | We then enumerate the processes looking for a possibly malicious process:
43 |
44 | ```bash
45 | $ vol.py -f stuxnet.vmem pslist
46 | Volatility Foundation Volatility Framework 2.5
47 | Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit
48 | ---------- -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------
49 | 0x823c8830 System 4 0 59 403 ------ 0
50 | 0x820df020 smss.exe 376 4 3 19 ------ 0 2010-10-29 17:08:53 UTC+0000
51 | 0x821a2da0 csrss.exe 600 376 11 395 0 0 2010-10-29 17:08:54 UTC+0000
52 | 0x81da5650 winlogon.exe 624 376 19 570 0 0 2010-10-29 17:08:54 UTC+0000
53 | 0x82073020 services.exe 668 624 21 431 0 0 2010-10-29 17:08:54 UTC+0000
54 | 0x81e70020 lsass.exe 680 624 19 342 0 0 2010-10-29 17:08:54 UTC+0000
55 | 0x823315d8 vmacthlp.exe 844 668 1 25 0 0 2010-10-29 17:08:55 UTC+0000
56 | 0x81db8da0 svchost.exe 856 668 17 193 0 0 2010-10-29 17:08:55 UTC+0000
57 | 0x81e61da0 svchost.exe 940 668 13 312 0 0 2010-10-29 17:08:55 UTC+0000
58 | 0x822843e8 svchost.exe 1032 668 61 1169 0 0 2010-10-29 17:08:55 UTC+0000
59 | 0x81e18b28 svchost.exe 1080 668 5 80 0 0 2010-10-29 17:08:55 UTC+0000
60 | 0x81ff7020 svchost.exe 1200 668 14 197 0 0 2010-10-29 17:08:55 UTC+0000
61 | 0x81fee8b0 spoolsv.exe 1412 668 10 118 0 0 2010-10-29 17:08:56 UTC+0000
62 | 0x81e0eda0 jqs.exe 1580 668 5 148 0 0 2010-10-29 17:09:05 UTC+0000
63 | 0x81fe52d0 vmtoolsd.exe 1664 668 5 284 0 0 2010-10-29 17:09:05 UTC+0000
64 | 0x821a0568 VMUpgradeHelper 1816 668 3 96 0 0 2010-10-29 17:09:08 UTC+0000
65 | 0x8205ada0 alg.exe 188 668 6 107 0 0 2010-10-29 17:09:09 UTC+0000
66 | 0x820ec7e8 explorer.exe 1196 1728 16 582 0 0 2010-10-29 17:11:49 UTC+0000
67 | 0x820ecc10 wscntfy.exe 2040 1032 1 28 0 0 2010-10-29 17:11:49 UTC+0000
68 | 0x81e86978 TSVNCache.exe 324 1196 7 54 0 0 2010-10-29 17:11:49 UTC+0000
69 | 0x81fc5da0 VMwareTray.exe 1912 1196 1 50 0 0 2010-10-29 17:11:50 UTC+0000
70 | 0x81e6b660 VMwareUser.exe 1356 1196 9 251 0 0 2010-10-29 17:11:50 UTC+0000
71 | 0x8210d478 jusched.exe 1712 1196 1 26 0 0 2010-10-29 17:11:50 UTC+0000
72 | 0x82279998 imapi.exe 756 668 4 116 0 0 2010-10-29 17:11:54 UTC+0000
73 | 0x822b9a10 wuauclt.exe 976 1032 3 133 0 0 2010-10-29 17:12:03 UTC+0000
74 | 0x81c543a0 Procmon.exe 660 1196 13 189 0 0 2011-06-03 04:25:56 UTC+0000
75 | 0x81fa5390 wmiprvse.exe 1872 856 5 134 0 0 2011-06-03 04:25:58 UTC+0000
76 | 0x81c498c8 lsass.exe 868 668 2 23 0 0 2011-06-03 04:26:55 UTC+0000
77 | 0x81c47c00 lsass.exe 1928 668 4 65 0 0 2011-06-03 04:26:55 UTC+0000
78 | 0x81c0cda0 cmd.exe 968 1664 0 -------- 0 0 2011-06-03 04:31:35 UTC+0000 2011-06-03 04:31:36 UTC+0000
79 | 0x81f14938 ipconfig.exe 304 968 0 -------- 0 0 2011-06-03 04:31:35 UTC+0000 2011-06-03 04:31:36 UTC+0000
80 | ```
81 |
82 | We identify that an additiona *lsass.exe* process is running in the system. We can use the *pstree* command to identify parent-child relation for processes:
83 |
84 | ```bash
85 | $ vol.py -f stuxnet.vmem pstree
86 | Volatility Foundation Volatility Framework 2.5
87 | Name Pid PPid Thds Hnds Time
88 | -------------------------------------------------- ------ ------ ------ ------ ----
89 | 0x823c8830:System 4 0 59 403 1970-01-01 00:00:00 UTC+0000
90 | . 0x820df020:smss.exe 376 4 3 19 2010-10-29 17:08:53 UTC+0000
91 | .. 0x821a2da0:csrss.exe 600 376 11 395 2010-10-29 17:08:54 UTC+0000
92 | .. 0x81da5650:winlogon.exe 624 376 19 570 2010-10-29 17:08:54 UTC+0000
93 | ... 0x82073020:services.exe 668 624 21 431 2010-10-29 17:08:54 UTC+0000
94 | .... 0x81fe52d0:vmtoolsd.exe 1664 668 5 284 2010-10-29 17:09:05 UTC+0000
95 | ..... 0x81c0cda0:cmd.exe 968 1664 0 ------ 2011-06-03 04:31:35 UTC+0000
96 | ...... 0x81f14938:ipconfig.exe 304 968 0 ------ 2011-06-03 04:31:35 UTC+0000
97 | .... 0x822843e8:svchost.exe 1032 668 61 1169 2010-10-29 17:08:55 UTC+0000
98 | ..... 0x822b9a10:wuauclt.exe 976 1032 3 133 2010-10-29 17:12:03 UTC+0000
99 | ..... 0x820ecc10:wscntfy.exe 2040 1032 1 28 2010-10-29 17:11:49 UTC+0000
100 | .... 0x81e61da0:svchost.exe 940 668 13 312 2010-10-29 17:08:55 UTC+0000
101 | .... 0x81db8da0:svchost.exe 856 668 17 193 2010-10-29 17:08:55 UTC+0000
102 | ..... 0x81fa5390:wmiprvse.exe 1872 856 5 134 2011-06-03 04:25:58 UTC+0000
103 | .... 0x821a0568:VMUpgradeHelper 1816 668 3 96 2010-10-29 17:09:08 UTC+0000
104 | .... 0x81fee8b0:spoolsv.exe 1412 668 10 118 2010-10-29 17:08:56 UTC+0000
105 | .... 0x81ff7020:svchost.exe 1200 668 14 197 2010-10-29 17:08:55 UTC+0000
106 | .... 0x81c47c00:lsass.exe 1928 668 4 65 2011-06-03 04:26:55 UTC+0000
107 | .... 0x81e18b28:svchost.exe 1080 668 5 80 2010-10-29 17:08:55 UTC+0000
108 | .... 0x8205ada0:alg.exe 188 668 6 107 2010-10-29 17:09:09 UTC+0000
109 | .... 0x823315d8:vmacthlp.exe 844 668 1 25 2010-10-29 17:08:55 UTC+0000
110 | .... 0x81e0eda0:jqs.exe 1580 668 5 148 2010-10-29 17:09:05 UTC+0000
111 | .... 0x81c498c8:lsass.exe 868 668 2 23 2011-06-03 04:26:55 UTC+0000
112 | .... 0x82279998:imapi.exe 756 668 4 116 2010-10-29 17:11:54 UTC+0000
113 | ... 0x81e70020:lsass.exe 680 624 19 342 2010-10-29 17:08:54 UTC+0000
114 | 0x820ec7e8:explorer.exe 1196 1728 16 582 2010-10-29 17:11:49 UTC+0000
115 | . 0x81c543a0:Procmon.exe 660 1196 13 189 2011-06-03 04:25:56 UTC+0000
116 | . 0x81e86978:TSVNCache.exe 324 1196 7 54 2010-10-29 17:11:49 UTC+0000
117 | . 0x81e6b660:VMwareUser.exe 1356 1196 9 251 2010-10-29 17:11:50 UTC+0000
118 | . 0x8210d478:jusched.exe 1712 1196 1 26 2010-10-29 17:11:50 UTC+0000
119 | . 0x81fc5da0:VMwareTray.exe 1912 1196 1 50 2010-10-29 17:11:50 UTC+0000
120 | ```
121 |
122 | It appears there are 2 *lsass.exe* started by *services.exe* while normally it should be a single instance. We then look for possibly injected code in these *lsass.exe* process:
123 |
124 | ```bash
125 | $ vol.py -f stuxnet.vmem malfind -p 1928 -D ./dump/
126 | Volatility Foundation Volatility Framework 2.5
127 | Process: lsass.exe Pid: 1928 Address: 0x80000
128 | Vad Tag: Vad Protection: PAGE_EXECUTE_READWRITE
129 | Flags: Protection: 6
130 |
131 | $ file dump/*
132 | dump/process.0x81c47c00.0x1000000.dmp: PE32 executable for MS Windows (GUI) Intel 80386 32-bit
133 | dump/process.0x81c47c00.0x680000.dmp: data
134 | dump/process.0x81c47c00.0x6f0000.dmp: data
135 | dump/process.0x81c47c00.0x80000.dmp: PE32 executable for MS Windows (DLL) (GUI) Intel 80386 32-bit
136 | dump/process.0x81c47c00.0x870000.dmp: PE32 executable for MS Windows (DLL) (GUI) Intel 80386 32-bit
137 | ```
138 |
139 | The *malfind* plugin dumps multiple possible malicious code injected into *lsass.exe* process with PID *1928*. One of the injected module was found to be malicious:
140 |
141 |
142 |
143 | ### Kernel Rootkit Identification
144 |
145 | The [Stuxnet](https://en.wikipedia.org/wiki/Stuxnet) worm is known to employ multiple kernel drivers in order to hide its presence. To detect such malicious drivers, we first enumerate the SSDT to look for possible system call hooks:
146 |
147 | ```bash
148 | $ vol.py -f stuxnet.vmem ssdt | grep -v ntoskrnl.exe | grep -v win32k.sys
149 | Volatility Foundation Volatility Framework 2.5
150 | [x86] Gathering all referenced SSDTs from KTHREADs...
151 | Finding appropriate address space for tables...
152 | SSDT[0] at 80501b8c with 284 entries
153 | Entry 0x0019: 0xb240f80e (NtClose) owned by PROCMON20.SYS
154 | Entry 0x0029: 0xb240f604 (NtCreateKey) owned by PROCMON20.SYS
155 | Entry 0x003f: 0xb240f4ac (NtDeleteKey) owned by PROCMON20.SYS
156 | Entry 0x0041: 0xb240f4f2 (NtDeleteValueKey) owned by PROCMON20.SYS
157 | Entry 0x0047: 0xb240f3f2 (NtEnumerateKey) owned by PROCMON20.SYS
158 | Entry 0x0049: 0xb240f34e (NtEnumerateValueKey) owned by PROCMON20.SYS
159 | Entry 0x004f: 0xb240f446 (NtFlushKey) owned by PROCMON20.SYS
160 | Entry 0x0062: 0xb240f972 (NtLoadKey) owned by PROCMON20.SYS
161 | Entry 0x0077: 0xb240f7d0 (NtOpenKey) owned by PROCMON20.SYS
162 | Entry 0x00a0: 0xb240f03e (NtQueryKey) owned by PROCMON20.SYS
163 | Entry 0x00b1: 0xb240f166 (NtQueryValueKey) owned by PROCMON20.SYS
164 | Entry 0x00f7: 0xb240f28a (NtSetValueKey) owned by PROCMON20.SYS
165 | Entry 0x0107: 0xb240fac2 (NtUnloadKey) owned by PROCMON20.SYS
166 | SSDT[1] at bf999b80 with 667 entries
167 | ```
168 |
169 | We identify SSDT hooking however the hook functions appears to be belong to *PROCMON20.SYS* driver which is part of [Procmon](https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx) tool.
170 |
171 | We then look for another vector through kernel functions can be intercepted for malicious activity by rootkits:
172 |
173 | ```bash
174 | $ vol.py -f stuxnet.vmem callbacks
175 | [...]
176 | IoRegisterFsRegistrationChange 0xb21d89ec mrxnet.sys -
177 | GenericKernelCallback 0xf895ad06 mrxcls.sys -
178 | PsSetLoadImageNotifyRoutine 0xf895ad06 mrxcls.sys -
179 | [...]
180 | ```
181 |
182 | After manual analysis of results, the above modules were found to be non-standard and possibly malicious. We can verify by dumping them to disk:
183 |
184 | ```bash
185 | $ vol.py -f stuxnet.vmem modules | grep mrx
186 | Volatility Foundation Volatility Framework 2.5
187 | 0x81f8cb60 mrxcls.sys 0xf895a000 0x5000 \??\C:\WINDOWS\system32\Drivers\mrxcls.sys
188 | 0x81c2a530 mrxnet.sys 0xb21d8000 0x3000 \??\C:\WINDOWS\system32\Drivers\mrxnet.sys
189 | ```
190 |
191 | ```bash
192 | $ vol.py -f stuxnet.vmem moddump -b 0xf895a000 -D ./dump/
193 | Volatility Foundation Volatility Framework 2.5
194 | Module Base Module Name Result
195 | ----------- -------------------- ------
196 | 0x0f895a000 mrxcls.sys OK: driver.f895a000.sys
197 | $ vol.py -f stuxnet.vmem moddump -b 0xb21d8000 -D ./dump/
198 | Volatility Foundation Volatility Framework 2.5
199 | Module Base Module Name Result
200 | ----------- -------------------- ------
201 | 0x0b21d8000 mrxnet.sys OK: driver.b21d8000.sys
202 |
203 | $ file dump/*
204 | dump/driver.b21d8000.sys: PE32 executable for MS Windows (native) Intel 80386 32-bit
205 | dump/driver.f895a000.sys: PE32 executable for MS Windows (native) Intel 80386 32-bit
206 | ```
207 |
208 | Online virus scan confirms that the extracted drivers are indeed malicious.
209 |
210 |
211 |
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/win32_api_counting.md:
--------------------------------------------------------------------------------
1 | # Win32 API Counting
2 |
3 |
4 | ## Description
5 |
6 | The challenge consists of an input executable that calls **ReadProcessMemory** Win32 API a certain number of times. The challenge involves simply counting the number of times this API is called.
7 |
8 | ## Solution
9 |
10 | The expected solution involves using *scripted debugging* to count the number of times **ReadProcessMemory** is called. While it might be possible to use a conventional Windows debugger such as *WinDBG* or *OllyDBG* to set a breakpoint and manually count the number of times the breakpoint is hit. However such a solution will be inefficient and may be practically infeasible.
11 |
12 | The following Ruby code utilizing [RbWinDBG](https://github.com/abhisek/RandomCode/tree/master/RbWinDBG) can be used to solve the challenge by automatically counting the number of times a given breakpoint is hit:
13 |
14 | ```ruby
15 |
16 | require 'RbWinDBG'
17 |
18 | if __FILE__ == $0
19 | RbWinDBG.init()
20 |
21 | count = 0
22 | dbg = RbWinDBG.start(ARGV[0])
23 | dbg.on_entrypoint do
24 | dbg.bpx(dbg.resolve_name('kernel32.dll!ReadProcessMemory')) do
25 | count += 1
26 | end
27 | end
28 |
29 | dbg.start()
30 | puts "Count: #{count}"
31 | end
32 |
33 | ```
--------------------------------------------------------------------------------
/gitbook/chapters/solutions/zeus_memory_image.md:
--------------------------------------------------------------------------------
1 | # Zeus Infected Memory Dump Analysis
2 |
3 | ## Description
4 |
5 | A live memory image from a system assumed to be infected with [Zeus](https://en.wikipedia.org/wiki/Zeus_(malware)) malware is provided for inspection and [IOC](https://en.wikipedia.org/wiki/Indicator_of_compromise) identification.
6 |
7 | ## Solution
8 |
9 | We start by identifying a suitable profile for the given image.
10 |
11 | ```bash
12 | $ vol.py -f zeus.vmem imageinfo
13 | Volatility Foundation Volatility Framework 2.5
14 | INFO : volatility.debug : Determining profile based on KDBG search...
15 | Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)
16 | AS Layer1 : IA32PagedMemoryPae (Kernel AS)
17 | AS Layer2 : FileAddressSpace (/Volumes/SSD1/REMA/Memory Images/zeus.vmem)
18 | PAE type : PAE
19 | DTB : 0x319000L
20 | KDBG : 0x80544ce0L
21 | Number of Processors : 1
22 | Image Type (Service Pack) : 2
23 | KPCR for CPU 0 : 0xffdff000L
24 | KUSER_SHARED_DATA : 0xffdf0000L
25 | Image date and time : 2010-08-15 19:17:56 UTC+0000
26 | Image local date and time : 2010-08-15 15:17:56 -0400
27 | ```
28 |
29 | We then look for probably connections to the [Command and Control]() infrastructure being made by the malicious executable:
30 |
31 | ```bash
32 | $ vol.py -f zeus.vmem connscan
33 | Volatility Foundation Volatility Framework 2.5
34 | Offset(P) Local Address Remote Address Pid
35 | ---------- ------------------------- ------------------------- ---
36 | 0x02214988 172.16.176.143:1054 193.104.41.75:80 856
37 | 0x06015ab0 0.0.0.0:1056 193.104.41.75:80 856
38 |
39 | ```
40 |
41 | Here we identify that a process with PID:*856* has made connections to *193.104.41.75*
42 |
43 | We enumerate processes to identify which process has our identified PID:
44 |
45 | ```bash
46 | $ vol.py -f zeus.vmem pslist | grep 856
47 | Volatility Foundation Volatility Framework 2.5
48 | 0x80ff88d8 svchost.exe 856 676 29 336 0 0 2010-08-11 06:06:24 UTC+0000
49 | ```
50 |
51 | While *svchost.exe* is known to be a core Windows service, malware may fake such names for its own executable. To identify if this svchost.exe is indeed the malicious executable, we look for its parent process:
52 |
53 | ```bash
54 | $ vol.py -f zeus.vmem pstree
55 | Volatility Foundation Volatility Framework 2.5
56 | Name Pid PPid Thds Hnds Time
57 | -------------------------------------------------- ------ ------ ------ ------ ----
58 | 0x810b1660:System 4 0 58 379 1970-01-01 00:00:00 UTC+0000
59 | . 0xff2ab020:smss.exe 544 4 3 21 2010-08-11 06:06:21 UTC+0000
60 | .. 0xff1ec978:winlogon.exe 632 544 24 536 2010-08-11 06:06:23 UTC+0000
61 | ... 0xff255020:lsass.exe 688 632 21 405 2010-08-11 06:06:24 UTC+0000
62 | ... 0xff247020:services.exe 676 632 16 288 2010-08-11 06:06:24 UTC+0000
63 | .... 0xff1b8b28:vmtoolsd.exe 1668 676 5 225 2010-08-11 06:06:35 UTC+0000
64 | ..... 0xff224020:cmd.exe 124 1668 0 ------ 2010-08-15 19:17:55 UTC+0000
65 | .... 0x80ff88d8:svchost.exe 856 676 29 336 2010-08-11 06:06:24 UTC+0000
66 | ```
67 |
68 | The *svchost.exe* process with PID *856* appears to be the Windows service as it is started by *services.exe* during boot. This indicates that malicious code may have been injected into *svchost.exe* since we have already found evidence of it connecting to unknown IP address.
69 |
70 | We can identify possibly hooked APIs in *svchost.exe*:
71 |
72 | ```bash
73 | $ vol.py -f zeus.vmem --profile=WinXPSP2x86 -p 856 apihooks
74 | Volatility Foundation Volatility Framework 2.5
75 | ************************************************************************
76 | Hook mode: Usermode
77 | Hook type: Inline/Trampoline
78 | Process: 856 (svchost.exe)
79 | Victim module: ntdll.dll (0x7c900000 - 0x7c9b0000)
80 | Function: ntdll.dll!NtCreateThread at 0x7c90d7d2
81 | Hook address: 0xb73b47
82 | Hooking module:
83 |
84 | Disassembly(0):
85 | 0x7c90d7d2 e970632684 JMP 0xb73b47
86 | 0x7c90d7d7 ba0003fe7f MOV EDX, 0x7ffe0300
87 | 0x7c90d7dc ff12 CALL DWORD [EDX]
88 | 0x7c90d7de c22000 RET 0x20
89 | 0x7c90d7e1 90 NOP
90 | 0x7c90d7e2 90 NOP
91 | 0x7c90d7e3 90 NOP
92 | 0x7c90d7e4 90 NOP
93 | 0x7c90d7e5 90 NOP
94 | 0x7c90d7e6 90 NOP
95 | 0x7c90d7e7 b8 DB 0xb8
96 | 0x7c90d7e8 36 DB 0x36
97 | 0x7c90d7e9 00 DB 0x0
98 | [...]
99 | ```
100 |
101 | We can attempt to dump possibly injected code from *svchost.exe*:
102 |
103 | ```bash
104 | $ vol.py -f zeus.vmem --profile=WinXPSP2x86 -p 856 malfind -D dump/
105 | Volatility Foundation Volatility Framework 2.5
106 | Process: svchost.exe Pid: 856 Address: 0xb70000
107 | Vad Tag: VadS Protection: PAGE_EXECUTE_READWRITE
108 | Flags: CommitCharge: 38, MemCommit: 1, PrivateMemory: 1, Protection: 6
109 |
110 | 0x00b70000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 MZ..............
111 | 0x00b70010 b8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 ........@.......
112 | 0x00b70020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
113 | 0x00b70030 00 00 00 00 00 00 00 00 00 00 00 00 d0 00 00 00 ................
114 |
115 | 0x00b70000 4d DEC EBP
116 | 0x00b70001 5a POP EDX
117 |
118 | [...]
119 | ```
120 |
121 | The *malfind* plugin will dump all possibly injected code in the inspected process. We can manually verify the dumped data for malicious behavior:
122 |
123 | ```bash
124 | $ file dump/*
125 | dump/process.0x80ff88d8.0xb70000.dmp: PE32 executable for MS Windows (GUI) Intel 80386 32-bit
126 | dump/process.0x80ff88d8.0xcb0000.dmp: COM executable for DOS
127 | ```
128 |
129 | We could verify and confirm that one of the dumped file indeed belongs to the malicious executable:
130 |
131 |
132 |
133 | Finally, we enumerate various registry entries through which the malicious executable can run during system startup:
134 |
135 | ```bash
136 | $ vol.py -f zeus.vmem --profile=WinXPSP2x86 printkey -K "Microsoft\\Windows NT\\CurrentVersion\\Winlogon"
137 | Volatility Foundation Volatility Framework 2.5
138 | Legend: (S) = Stable (V) = Volatile
139 |
140 | [...]
141 |
142 | Registry: \Device\HarddiskVolume1\WINDOWS\system32\config\software
143 | Key name: Winlogon (S)
144 | Last updated: 2010-08-15 19:17:23 UTC+0000
145 |
146 | Subkeys:
147 | (S) GPExtensions
148 | (S) Notify
149 | (S) SpecialAccounts
150 | (V) Credentials
151 |
152 | Values:
153 | REG_DWORD AutoRestartShell : (S) 1
154 | REG_SZ DefaultDomainName : (S) BILLY-DB5B96DD3
155 | REG_SZ DefaultUserName : (S) Administrator
156 | REG_SZ LegalNoticeCaption : (S)
157 | REG_SZ LegalNoticeText : (S)
158 | REG_SZ PowerdownAfterShutdown : (S) 0
159 | REG_SZ ReportBootOk : (S) 1
160 | REG_SZ Shell : (S) Explorer.exe
161 | REG_SZ ShutdownWithoutLogon : (S) 0
162 | REG_SZ System : (S)
163 | REG_SZ Userinit : (S) C:\WINDOWS\system32\userinit.exe,C:\WINDOWS\system32\sdra64.exe,
164 | REG_SZ VmApplet : (S) rundll32 shell32,Control_RunDLL "sysdm.cpl"
165 |
166 | ```
167 |
168 | We conclude that the *UserInit* registry entry has been modified with additional path to malicious executable *C:\WINDOWS\system32\sdra64.exe* through which it is executed during system startup.
169 |
170 |
--------------------------------------------------------------------------------
/gitbook/chapters/windows/api_hooking.md:
--------------------------------------------------------------------------------
1 | # API Hooking
2 |
3 | API Hooking is the process of intercepting platform API calls by a process for instrumentation or analysis purpose. API Hooking techniques are usually platform and [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) dependent. In Windows, there are multiple techniques for API Hooking, however [Microsoft Detours](https://www.microsoft.com/en-us/research/project/detours/) library is the officially supported mechanism for intercepting Windows API by Microsoft.
4 |
5 | ## Hooking Mechanism
6 |
7 |
8 |
9 | *Microsoft Detours* implement API Hooking by introducting a trampoline function that is called when the application calls the hooked function. The trampoline function is responsible for called the hook handler function and passing control to original API after the hook handler function has returned.
10 |
11 | ## Using Microsoft Detours for API Hooking
12 |
13 | *Microsoft Detours* library provide C/C++ SDK for developing applications with API Hooking capability. The library can be used to develop *DLL* modules which when injected or loaded into a target process will intercept and trace required API.
14 |
15 | ### Initializing Hooks
16 |
17 | ```c
18 | BOOL ProcessAttach(HMODULE hDll)
19 | {
20 | SyelogOpen("HelloDetour", SYELOG_FACILITY_APPLICATION);
21 |
22 | DetourTransactionBegin();
23 | DetourUpdateThread(GetCurrentThread());
24 |
25 | DetourAttach(&(LPVOID&) Real_CreateFileW, (LPVOID) Detour_CreateFileW);
26 |
27 | Syelog(SYELOG_SEVERITY_NOTICE, "Detour Attached To: %d", GetCurrentProcessId());
28 |
29 | DetourTransactionCommit();
30 | return TRUE;
31 | }
32 | ```
33 |
34 | ### Hook Handler
35 |
36 | ```c
37 | HANDLE WINAPI Detour_CreateFileW(LPCWSTR a0,
38 | DWORD a1,
39 | DWORD a2,
40 | LPSECURITY_ATTRIBUTES a3,
41 | DWORD a4,
42 | DWORD a5,
43 | HANDLE a6)
44 | {
45 | CHAR szPath[MAX_PATH + 1];
46 | DWORD dw;
47 |
48 | wcstombs_s((size_t*) &dw, szPath, MAX_PATH, a0, MAX_PATH);
49 | Syelog(SYELOG_SEVERITY_NOTICE, "CreateFileW: %s", szPath);
50 | return Real_CreateFileW(a0, a1, a2, a3, a4, a5, a6);
51 | }
52 | ```
53 |
54 | ### Tracer Injection
55 |
56 | In order to trace a target application, the hook DLL must be injected or loaded into the target process. This can be achieved by injecting a small *shellcode* in the target process that in turn called [LoadLibrary][1] API to load our tracer DLL in the target process.
57 |
58 |
59 |
60 | ## Reference
61 |
62 | *
63 |
64 | ## Appendix
65 |
66 | ### Sample Application for API Hooking
67 |
68 | ```c
69 | #include
70 | #include
71 | #include
72 |
73 | #include "DetourFunctions.h"
74 |
75 |
76 | HANDLE WINAPI Detour_CreateFileW(LPCWSTR a0,
77 | DWORD a1,
78 | DWORD a2,
79 | LPSECURITY_ATTRIBUTES a3,
80 | DWORD a4,
81 | DWORD a5,
82 | HANDLE a6)
83 | {
84 | CHAR szPath[MAX_PATH + 1];
85 | DWORD dw;
86 |
87 | wcstombs_s((size_t*) &dw, szPath, MAX_PATH, a0, MAX_PATH);
88 | Syelog(SYELOG_SEVERITY_NOTICE, "CreateFileW: %s", szPath);
89 | return Real_CreateFileW(a0, a1, a2, a3, a4, a5, a6);
90 | }
91 |
92 | BOOL ProcessAttach(HMODULE hDll)
93 | {
94 | SyelogOpen("HelloDetour", SYELOG_FACILITY_APPLICATION);
95 |
96 | DetourTransactionBegin();
97 | DetourUpdateThread(GetCurrentThread());
98 |
99 | DetourAttach(&(LPVOID&) Real_CreateFileW, (LPVOID) Detour_CreateFileW);
100 |
101 | Syelog(SYELOG_SEVERITY_NOTICE, "Detour Attached To: %d", GetCurrentProcessId());
102 |
103 | DetourTransactionCommit();
104 | return TRUE;
105 | }
106 |
107 | BOOL ProcessDetach(HMODULE hDll)
108 | {
109 | Syelog(SYELOG_SEVERITY_NOTICE, "Detour closing");
110 | SyelogClose(FALSE);
111 |
112 | return TRUE;
113 | }
114 |
115 | extern "C" {
116 | __declspec(dllexport) VOID __cdecl Init()
117 | {
118 | // Init Tasks
119 | // Called by Loader Shellcode (Injector)
120 | }
121 | }
122 |
123 | BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)
124 | {
125 | switch(dwReason) {
126 |
127 | case DLL_PROCESS_ATTACH:
128 | return ProcessAttach(hModule);
129 |
130 | case DLL_PROCESS_DETACH:
131 | return ProcessDetach(hModule);
132 |
133 | case DLL_THREAD_ATTACH:
134 | break;
135 | case DLL_THREAD_DETACH:
136 | break;
137 |
138 | }
139 |
140 | return TRUE;
141 | }
142 | ```
143 |
144 | ### Injector for API Hooking
145 |
146 | ```ruby
147 | $:.unshift("C:\\Lib\\metasm")
148 |
149 | require 'metasm'
150 | require 'optparse'
151 |
152 | $ASMCODE =
153 | # Win32 PEB based API Resolver
154 | # Metasm seems to fail on jecxz so we compile using nasm and use the binary
155 | "\xe8\x56\x00\x00\x00\x53\x55\x56\x57\x8b\x6c\x24\x18\x8b\x45\x3c" +
156 | "\x8b\x54\x05\x78\x01\xea\x8b\x4a\x18\x8b\x5a\x20\x01\xeb\xe3\x32" +
157 | "\x49\x8b\x34\x8b\x01\xee\x31\xff\xfc\x31\xc0\xac\x38\xe0\x74\x07" +
158 | "\xc1\xcf\x0d\x01\xc7\xeb\xf2\x3b\x7c\x24\x14\x75\xe1\x8b\x5a\x24" +
159 | "\x01\xeb\x66\x8b\x0c\x4b\x8b\x5a\x1c\x01\xeb\x8b\x04\x8b\x01\xe8" +
160 | "\xeb\x02\x31\xc0\x5f\x5e\x5d\x5b\xc2\x08\x00\x31\xc9\x64\x8b\x71" +
161 | "\x30\x8b\x76\x0c\x8b\x76\x1c\x8b\x5e\x08\x8b\x7e\x20\x8b\x36\x66" +
162 | "\x39\x4f\x18\x75\xf2\x5e\x53\x68\x8e\x4e\x0e\xec\xff\xd6\x89\xc7" +
163 | "\x57\x56\x53\x89\xe5" +
164 |
165 | # %define LoadLibraryA [ebp + 8]
166 | # %define LGetProcAddress [ebp + 4]
167 | # %define KERNEL32 BASE [ebp + 0]
168 |
169 | Metasm::Shellcode.assemble(Metasm::Ia32.new, %Q{
170 | jmp _end
171 | _start:
172 |
173 | pop ecx ; DLL Path in ECX
174 |
175 | ; LoadLibraryA(DLL)
176 | push ecx
177 | call [ebp + 8]
178 |
179 | test eax, eax
180 | jz _exit
181 |
182 | ; GetProcessAddress() and find Init()
183 | push eax ; DLL Base
184 | push 0x95481bf4 ; Hash of Init
185 | call [ebp + 4]
186 |
187 | test eax, eax
188 | jz _exit
189 |
190 | call eax ; Init() // FIXME: Crash Here if Init is not exported
191 |
192 | _exit:
193 |
194 | ; Apparently ExitThread is not exported by kernel32 anymore
195 | ; We need to call ntdll!RtlExitUserThread
196 | ; Resolve Exit Thread
197 | ;push [ebp]
198 | ;push 0x60e0ceef ; Hash of Exit Thread
199 | ;call [ebp + 4]
200 |
201 | ; Call ExitThread
202 | ;push 0x00
203 | ;call eax
204 |
205 | call _getNtdll
206 | db 'ntdll.dll', 0x00
207 |
208 | _getNtdll:
209 | call [ebp + 8] ; LoadLibraryA('ntdll.dll')
210 |
211 | push eax
212 | push 0xff7f061a ; RtlExitUserThread
213 | call [ebp + 4]
214 |
215 | xor ebx, ebx
216 | push ebx
217 | call eax ; RtlExitUserThread(0)
218 |
219 | int 3
220 |
221 | _end:
222 | call _start
223 | ; Path (ASCII) for DLL goes here
224 |
225 | }).encode_string()
226 |
227 | def process_inject_dll(process, path)
228 | puts "[+] Attempting to inject \"#{path}\" to pid: #{process.pid}"
229 | Metasm::WinOS.inject_run_shellcode(process, $ASMCODE + path.to_s + "\x00")
230 | end
231 |
232 |
233 | if __FILE__ == $0
234 | options = {}
235 | opts = OptionParser.new do |opts|
236 | opts.banner = "Usage: Injector.rb [options]"
237 |
238 | opts.on("-p", "--pid [PID]", "Inject to process identified by PID") do |pid|
239 | options[:pid] = pid.to_i
240 | end
241 |
242 | opts.on("-n", "--name [NAME]", "Inject to all processes matching name (eg. chrome.exe)") do |name|
243 | options[:name] = name.to_s
244 | end
245 |
246 | opts.on("-D", "--dll-path [PATH]", "Path of DLL to inject") do |dll|
247 | options[:dll] = dll.to_s
248 | end
249 |
250 | opts.on("-l", "--list", "List processes") do |v|
251 | options[:list_processes] = true
252 | end
253 | end
254 |
255 | opts.parse!
256 |
257 | if options[:list_processes]
258 | Metasm::WinOS.list_processes.each do |proc|
259 | puts "%d: %s" % [proc.pid, proc.modules.size > 0 ? proc.modules[0].path : "N/A"]
260 | end
261 |
262 | exit
263 | end
264 |
265 | if (options[:dll].nil?) or (options[:pid].nil? and options[:name].nil?)
266 | puts opts
267 | exit(1)
268 | end
269 |
270 | Metasm::WinOS.list_processes.each do |process|
271 | process_inject_dll(process, options[:dll]) if ((options[:pid]) and (process.pid == options[:pid].to_i)) or
272 | ((options[:name]) and (!process.modules.empty?) and
273 | (File.basename(process.modules[0].path).downcase == options[:name].downcase))
274 | end
275 | end
276 | ```
277 |
278 | [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
--------------------------------------------------------------------------------
/gitbook/chapters/windows/platform_overview.md:
--------------------------------------------------------------------------------
1 | # Windows Platform
2 |
3 | ## Architecture
4 |
5 |
6 |
7 | ## Windows Application Programming Interface (API)
8 |
9 | The Windows API, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. Almost all Windows programs interact with the Windows API. The Windows API abstract OS and system internals from application processes. This allow application developers to focus on their application logic instead of being burdended with system internals.
10 |
11 |
12 |
13 | ### Popular Windows API For Malware Development
14 |
15 | Any malware written for the Windows platform is essentially a Windows application. In order to operate on Windows platform, it must conform to platform requirements and constraints. While there are different APIs or code paths through which various functional or malicious operation can be performed, below are list of common Windows API that are used for specific operations commonly found in malware samples.
16 |
17 | ### Process Manipulation and Injection
18 |
19 | * OpenProcess
20 | * TerminateProcess
21 | * WriteProcessMemory
22 | * CreateRemoteThread
23 | * QueueUserAPC
24 |
25 | ### Keystroke Logging
26 |
27 | * SetWindowsHookEx
28 |
29 | ### File Enumeration
30 |
31 | * FindFirstFile
32 |
33 | ### Screenshot
34 |
35 | * BitBlt
36 |
37 | ### Windows Registry API
38 |
39 | * RegOpenKeyEx
40 | * RegSetValue
41 | * RegCreateKeyEx
42 |
43 | ## References
44 |
45 | * [Windows Internals (Mark E. Russinovich, David A. Solomon, Alex Ionescu)](https://technet.microsoft.com/en-us/sysinternals/bb963901.aspx)
46 | *
47 | *
48 | *
--------------------------------------------------------------------------------
/gitbook/images/api_hooking_detours.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/api_hooking_detours.png
--------------------------------------------------------------------------------
/gitbook/images/api_hooking_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/api_hooking_example.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_dbg1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_dbg1.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_dbg2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_dbg2.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_ida1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_ida1.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_ida2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_ida2.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_ida3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_ida3.png
--------------------------------------------------------------------------------
/gitbook/images/aspack_scylla.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/aspack_scylla.png
--------------------------------------------------------------------------------
/gitbook/images/be2_driver_vt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/be2_driver_vt.png
--------------------------------------------------------------------------------
/gitbook/images/cff1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/cff1.png
--------------------------------------------------------------------------------
/gitbook/images/crashdump_neohex1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/crashdump_neohex1.png
--------------------------------------------------------------------------------
/gitbook/images/fileid_ida1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/fileid_ida1.png
--------------------------------------------------------------------------------
/gitbook/images/fileid_ida2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/fileid_ida2.png
--------------------------------------------------------------------------------
/gitbook/images/ida_main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/ida_main.png
--------------------------------------------------------------------------------
/gitbook/images/pe_headers_basic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pe_headers_basic.png
--------------------------------------------------------------------------------
/gitbook/images/pe_headers_cff.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pe_headers_cff.png
--------------------------------------------------------------------------------
/gitbook/images/peid1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/peid1.png
--------------------------------------------------------------------------------
/gitbook/images/peid2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/peid2.png
--------------------------------------------------------------------------------
/gitbook/images/peid_sample2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/peid_sample2.png
--------------------------------------------------------------------------------
/gitbook/images/pi_dump_file.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pi_dump_file.png
--------------------------------------------------------------------------------
/gitbook/images/pi_hidump.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pi_hidump.png
--------------------------------------------------------------------------------
/gitbook/images/pi_ida_sol.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pi_ida_sol.png
--------------------------------------------------------------------------------
/gitbook/images/pi_memory.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pi_memory.png
--------------------------------------------------------------------------------
/gitbook/images/pi_wpm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/pi_wpm.png
--------------------------------------------------------------------------------
/gitbook/images/rbwindbg_sample.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/rbwindbg_sample.png
--------------------------------------------------------------------------------
/gitbook/images/sandboxie_bsa.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/sandboxie_bsa.png
--------------------------------------------------------------------------------
/gitbook/images/sandboxie_bsa_fakenet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/sandboxie_bsa_fakenet.png
--------------------------------------------------------------------------------
/gitbook/images/smc1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc1.png
--------------------------------------------------------------------------------
/gitbook/images/smc10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc10.png
--------------------------------------------------------------------------------
/gitbook/images/smc11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc11.png
--------------------------------------------------------------------------------
/gitbook/images/smc2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc2.png
--------------------------------------------------------------------------------
/gitbook/images/smc3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc3.png
--------------------------------------------------------------------------------
/gitbook/images/smc4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc4.png
--------------------------------------------------------------------------------
/gitbook/images/smc5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc5.png
--------------------------------------------------------------------------------
/gitbook/images/smc6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc6.png
--------------------------------------------------------------------------------
/gitbook/images/smc7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc7.png
--------------------------------------------------------------------------------
/gitbook/images/smc8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc8.png
--------------------------------------------------------------------------------
/gitbook/images/smc9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/smc9.png
--------------------------------------------------------------------------------
/gitbook/images/stuxnet_Driver.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/stuxnet_Driver.png
--------------------------------------------------------------------------------
/gitbook/images/stuxnet_VT.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/stuxnet_VT.png
--------------------------------------------------------------------------------
/gitbook/images/upx_before_oep.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_before_oep.png
--------------------------------------------------------------------------------
/gitbook/images/upx_disasm1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_disasm1.png
--------------------------------------------------------------------------------
/gitbook/images/upx_disasm2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_disasm2.png
--------------------------------------------------------------------------------
/gitbook/images/upx_ollydump.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_ollydump.png
--------------------------------------------------------------------------------
/gitbook/images/upx_scylla.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_scylla.png
--------------------------------------------------------------------------------
/gitbook/images/upx_unpack1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_unpack1.png
--------------------------------------------------------------------------------
/gitbook/images/upx_unpacked.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/upx_unpacked.png
--------------------------------------------------------------------------------
/gitbook/images/win32_api.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/win32_api.png
--------------------------------------------------------------------------------
/gitbook/images/windows_arch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/windows_arch.png
--------------------------------------------------------------------------------
/gitbook/images/winmd5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/winmd5.png
--------------------------------------------------------------------------------
/gitbook/images/x86_arch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/x86_arch.png
--------------------------------------------------------------------------------
/gitbook/images/x86_cpu_rings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/x86_cpu_rings.png
--------------------------------------------------------------------------------
/gitbook/images/x86_mm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/x86_mm.png
--------------------------------------------------------------------------------
/gitbook/images/zeus_VT.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/gitbook/images/zeus_VT.png
--------------------------------------------------------------------------------
/presentations/pdf/001_Intro_RE.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/001_Intro_RE.pdf
--------------------------------------------------------------------------------
/presentations/pdf/002_A_Intro_Win32_Core_Platform.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/002_A_Intro_Win32_Core_Platform.pdf
--------------------------------------------------------------------------------
/presentations/pdf/003_B_Win32_API_Hooking.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/003_B_Win32_API_Hooking.pdf
--------------------------------------------------------------------------------
/presentations/pdf/004_Intro_PortalExecutable.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/004_Intro_PortalExecutable.pdf
--------------------------------------------------------------------------------
/presentations/pdf/005_A_Intro_X86_ASM.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/005_A_Intro_X86_ASM.pdf
--------------------------------------------------------------------------------
/presentations/pdf/008_B_Malware_Analysis_Memory_Forensics.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/008_B_Malware_Analysis_Memory_Forensics.pdf
--------------------------------------------------------------------------------
/presentations/pdf/009_A_Packers_Crypters.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/009_A_Packers_Crypters.pdf
--------------------------------------------------------------------------------
/presentations/pdf/ASPAck229_Manual_Unpacking.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/ASPAck229_Manual_Unpacking.pdf
--------------------------------------------------------------------------------
/presentations/pdf/HackIM2014_RE_Hard_SMC.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/HackIM2014_RE_Hard_SMC.pdf
--------------------------------------------------------------------------------
/presentations/pdf/Windows_Process_Injection.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/pdf/Windows_Process_Injection.pdf
--------------------------------------------------------------------------------
/presentations/ppt/EMPTY:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abhisek/reverse-engineering-and-malware-analysis/c1f660fa385e44c7b81cf90cc48e9d380db52d35/presentations/ppt/EMPTY
--------------------------------------------------------------------------------