### File *.DMP
- Tệp DMP chủ yếu được liên kết với định dạng tệp MemoryDump hoặc Minidump. Nó được sử dụng trong hệ điều hành Microsoft Windows để lưu trữ dữ liệu đã bị xóa khỏi không gian bộ nhớ của máy tính. Thông thường, các tệp DMP được tạo khi tệp gặp sự cố hoặc xảy ra lỗi. Đôi khi, tệp DMP rất quan trọng đối với các chuyên gia kỹ thuật hoặc người dùng máy tính nâng cao để khắc phục sự cố bạn đang gặp phải và giải quyết bất kỳ loại sự cố ứng dụng nào. Các tệp DMP được lưu trữ dưới dạng định dạng độc quyền trong Microsoft, được hệ điều hành sử dụng để gỡ lỗi bất kỳ ứng dụng nào được cài đặt trên hệ thống.
- 
### Phân tích file DMP với windbg
- Ở đây ta sẽ dump process autorun từ máy để tiến hành phân tích
- Ta bắt đầu với lệnh sau để có cái nhìn tổng quan về process
```
!analyze -v
```
- Kết quả là
```
0:000> !analyze -v
*******************************************************************************
* *
* Exception Analysis *
* *
*******************************************************************************
KEY_VALUES_STRING: 1
Key : Analysis.CPU.mSec
Value: 1921
Key : Analysis.Elapsed.mSec
Value: 52420
Key : Analysis.IO.Other.Mb
Value: 29
Key : Analysis.IO.Read.Mb
Value: 1
Key : Analysis.IO.Write.Mb
Value: 68
Key : Analysis.Init.CPU.mSec
Value: 2968
Key : Analysis.Init.Elapsed.mSec
Value: 996733
Key : Analysis.Memory.CommitPeak.Mb
Value: 101
Key : Analysis.Version.DbgEng
Value: 10.0.27725.1000
Key : Analysis.Version.Description
Value: 10.2408.27.01 amd64fre
Key : Analysis.Version.Ext
Value: 1.2408.27.1
Key : Failure.Bucket
Value: BREAKPOINT_80000003_wow64win.dll!NtUserGetMessage
Key : Failure.Hash
Value: {700e031a-d631-add1-0799-013b383b9d1c}
Key : Timeline.OS.Boot.DeltaSec
Value: 23907
Key : Timeline.Process.Start.DeltaSec
Value: 60
Key : WER.OS.Branch
Value: vb_release
Key : WER.OS.Version
Value: 10.0.19041.1
Key : WER.Process.Version
Value: 14.11.0.0
FILE_IN_CAB: Autoruns.DMP
NTGLOBALFLAG: 0
APPLICATION_VERIFIER_FLAGS: 0
EXCEPTION_RECORD: (.exr -1)
ExceptionAddress: 0000000000000000
ExceptionCode: 80000003 (Break instruction exception)
ExceptionFlags: 00000000
NumberParameters: 0
FAULTING_THREAD: 00002714
PROCESS_NAME: Autoruns.exe
ERROR_CODE: (NTSTATUS) 0x80000003 - {EXCEPTION} Breakpoint A breakpoint has been reached.
EXCEPTION_CODE_STR: 80000003
STACK_TEXT:
00000000`00dfe298 00007ffa`219b399e : 00007ffa`21a05080 00000000`0000000f 00000000`00000000 00000000`00000003 : wow64win!NtUserGetMessage+0x14
00000000`00dfe2a0 00007ffa`218390da : 00000000`00ecd000 00007ffa`219b3820 00000000`00ecf000 00000000`010ff4d0 : wow64win!whNtUserGetMessage+0x2e
00000000`00dfe300 00000000`772617c3 : 00000000`750f136c 00007ffa`21830023 00000000`00ecc000 00000000`010ff4cc : wow64!Wow64SystemServiceEx+0x15a
00000000`00dfebc0 00000000`772611b9 : 00000000`010ff8a4 00007ffa`21833a74 00000000`00dfec90 00007ffa`21833b6f : wow64cpu!ServiceNoTurbo+0xb
00000000`00dfec70 00007ffa`21833989 : 00000000`00ecc000 00000000`00b00118 00000000`00000000 00000000`00dff4d0 : wow64cpu!BTCpuSimulate+0x9
00000000`00dfecb0 00007ffa`2183337d : 00000000`00000000 00000000`011e2638 00000000`00000000 00000000`00000000 : wow64!RunCpuSimulation+0xd
00000000`00dfece0 00007ffa`22223631 : 00007ffa`22275910 00007ffa`22275910 00000000`00000010 00000000`00ecb000 : wow64!Wow64LdrpInitialize+0x12d
00000000`00dfef90 00007ffa`221c5deb : 00000000`00000001 00000000`00000000 00000000`00000000 00000000`00000001 : ntdll!LdrpInitializeProcess+0x18e1
00000000`00dff3b0 00007ffa`221c5c73 : 00000000`00000000 00007ffa`22150000 00000000`00000000 00000000`00ecd000 : ntdll!LdrpInitialize+0x15f
00000000`00dff450 00007ffa`221c5c1e : 00000000`00dff4d0 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!LdrpInitialize+0x3b
00000000`00dff480 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!LdrInitializeThunk+0xe
STACK_COMMAND: ~0s; .ecxr ; kb
SYMBOL_NAME: wow64win!NtUserGetMessage+14
MODULE_NAME: wow64win
IMAGE_NAME: wow64win.dll
FAILURE_BUCKET_ID: BREAKPOINT_80000003_wow64win.dll!NtUserGetMessage
OS_VERSION: 10.0.19041.1
BUILDLAB_STR: vb_release
OSPLATFORM_TYPE: x64
OSNAME: Windows 10
IMAGE_VERSION: 10.0.19041.3996
FAILURE_ID_HASH: {700e031a-d631-add1-0799-013b383b9d1c}
Followup: MachineOwner
---------
```
- Từ đây ta có thể xác định được 1 vài thông tin cơ bản như sau:
**1. Loại lỗi:**
Lỗi là Breakpoint Exception (0x80000003), xảy ra khi chương trình đạt một điểm ngắt (breakpoint). Đây là một lỗi thường do lập trình viên hoặc trình gỡ lỗi (debugger) đặt ra. (`ExceptionCode: 80000003 (Break instruction exception)`)
**2. Nguyên nhân:**
Điểm lỗi nằm trong hàm NtUserGetMessage của module wow64win.dll. Đây là một API Windows liên quan đến giao diện người dùng (UI) trong môi trường 32-bit trên hệ điều hành 64-bit (WOW64). (`FAILURE_BUCKET_ID: BREAKPOINT_80000003_wow64win.dll!NtUserGetMessage`)
**3. Tên ứng dụng:**
Ứng dụng gặp sự cố là Autoruns.exe, một công cụ kiểm tra startup items.
**4. Thông tin stack:**
Stack trace cho thấy luồng thực thi đang trong mô-đun wow64win, wow64, và wow64cpu, liên quan đến việc mô phỏng môi trường 32-bit trên CPU 64-bit.
- Tuỳ theo các trường hợp sử dụng ta chọn các option phù hợp,, sau đây là 1 vài option cơ bản
```
lm : Display all module loaded to process
!analyze: Analyzes the current crash dump and displays information about the faulting code and any relevant call stacks.
!analyze -v: Provides more detailed information than !analyze, including the module and function that caused the crash.
.cls: Clears the WinDbg command window.
.effmach: Sets the effective machine type for the current debug session.
.reload: Reloads symbols from the symbol path.
.detach: Detaches the debugger from the target process.
.restart: Restarts the current debug session.
bp (or .break): Sets a breakpoint at a specific address or function.
dd (or !dword): Displays the contents of a DWORD (4-byte) value at a specific memory address.
dq (or !qword): Displays the contents of a QWORD (8-byte) value at a specific memory address.
dt (or !dml): Displays the type and value of a variable in a formatted manner.
kb (or k): Displays the call stack of the current thread.
lm (or !dlls): Lists all the loaded modules in the target process.
lmf: Lists all the functions exported by a specific module.
lmf: Displays the functions exported by a specific module.
lmv: Lists the versions of all the loaded modules.
ln: Displays the line number and source file information for a specified address.
!process: Displays information about the active processes and threads in the system.
!thread: Displays information about the threads in the current process.
.sympath: Sets the symbol search path for the current debug session.
.load: Loads a specified extension into the current debug session.
.unload: Unloads a specified extension from the current debug session.
~ (or ~n): Switches to a specific thread.
!heap: Displays information about the heap allocations in the current process.
!address: Displays information about the virtual memory addresses used by the current process.
!avrf: Enables or disables Application Verifier for the current process.
!poolused: Displays the memory usage statistics for the kernel memory pools.
!sysinfo: Displays information about the target system, including the operating system version and system memory information.
.effmach: Sets the effective machine type for the current debug session.
.cxr (or .exr): Sets the context record to the specified address, which can be useful when examining a crash dump file.
!uniqstack: Displays the unique call stacks for all the threads in the current process.
!gle (or .exr -1): Displays the last error code value.
!teb: Displays information about the thread environment block (TEB) for the current thread.
!error: Displays information about a specified error code.
.logopen: Starts logging WinDbg commands to a specified file.
.logclose: Stops logging WinDbg commands.
.echo: Displays a message in the WinDbg command window.
.printf: Formats and displays a message in the WinDbg command window.
!peb: Displays information about the process environment block (PEB) for the current process.
!address -summary: Displays a summary of the virtual memory usage for the current process.
!chkimg: Scans the image file headers and sections for integrity violations.
!runaway: Displays information about the threads that have consumed the most CPU time.
!locks: Displays information about the locks held by the threads in the current process.
!handle: Displays information about the handles opened by the current process.
!process 0 0: Displays information about all the processes in the system.
!pe: Displays the PE header information for a specified module.
!analyze -v -hang: Analyzes a dump file for a hang condition.
!heap -s: Displays the summary information for the heap allocations in the current process.
!uniqmodules: Displays the unique call stacks for all the modules in the current process.
!htrace: Traces heap allocations and frees for the current process.
!peb -process: Displays information about the process environment block (PEB) for a specified process.
!handle -f: Displays information about the handles opened by the current process and their object types.
!stacks: Displays the call stacks for all the threads in the current process.
!dml_start: Enables the DML (Debug Markup Language) mode, which allows you to display formatted output in the debugger window.
!dml_end: Disables the DML mode.
!dlls -l: Lists all the loaded modules, including their base addresses, file names, and timestamps.
!dlls -c: Lists all the loaded modules and their dependencies.
!sym noisy: Enables verbose symbol loading output.
!sym quiet: Disables verbose symbol loading output.
!sym fixup: Attempts to fix up the symbol paths for the current debug session.
!sym reload: Reloads the symbols for the current debug session.
!sym path: Displays the current symbol search path.
!sym dump: Dumps the symbols for a specified module to a file.
!token: Displays information about the security token for the current thread.
!token -n: Displays information about the security token for a specified process.
!wow64exts.sw: Switches to the 32-bit debugger extension mode for a 64-bit process.
!analyze -v: Analyzes a dump file and displays a verbose report of the crash or hang.
!objsize: Displays the size of a specified object.
!handle -u: Displays the handles opened by a specified process and their object types.
!locks -v: Displays verbose information about the locks held by the threads in the current process.
!peb -imagebase: Displays the base address of a specified module in the process environment block (PEB).
!thread -field: Displays the value of a specified field in the thread information block (TIB) for the current thread.
!vprot: Displays the virtual memory protection flags for a specified address range.
!vad: Displays the virtual address descriptors (VADs) for the current process.
!pss: Displays the process snapshot information for the current process.
!heap -p -a: Displays the allocation information for a specified address in the heap.
!dt: Displays the data structure layout and contents for a specified type.
!ustr: Displays the contents of a Unicode string.
!vm: Displays information about the virtual memory usage for the current process.
!wmitrace: Traces Windows Management Instrumentation (WMI) events for the current process.
!gflag: Displays or sets the global debugger flags.
!threadpool: Displays information about the thread pool for the current process.
```
- Tìm hiểu thêm các lệnh [tại đây](http://windbg.info/doc/1-common-cmds.html#18_memory)
### DMP file to Exe file
- Đầu tiên ta sử dụng lệnh `lm` trên CLI của windbg để xem các module được load vào
- 
- Đại khái, những module trên cùng sẽ là những module đầu tiên được thực thi và gọi các module khác.
- Để ý thấy module đầu tiên là Autoruns -> đây là file thực thi của chương trình.
- Nhấn vào trong module này, ta có thể xem 1 vài thông tin về offset. (Hoặc dùng lệnh `lmDvm[tên module]`)
- 
- Nhìn vào đây ta thấy file thực thi là Autoruns.exe
- Start - End: Vùng nhớ nơi module được nạp (từ 0x00b00000 đến 0x00cc1000).
- Kích thước module trong bộ nhớ là 0x1C1000 (~1.75 MB)
- Ta sử dụng `.writemem ` để trích xuất dãy byte theo offset đó
- 
- Để sử dụng .writemem ta có 2 cách sử dụng:
<details>
<summary>
1. Dùng offset đầu và offset cuối
</summary>
- 
</details>
<details>
<summary>
2. Dùng offset đầu và size
</summary>
- 
</details>
- Cả 2 đều cho ra 1 kết quả giống nhau
- 
#### Header Raw và Header Virtual
**Header Raw**
- Raw Header là cách dữ liệu của file PE được lưu trên ổ đĩa.
- Đơn vị đo: byte.
- Raw Offset: Chỉ ra vị trí thực tế của dữ liệu trong file.
- Dùng để nạp file từ đĩa vào bộ nhớ hoặc lưu trữ file.
**Header Virtual**
- Virtual Header là cách dữ liệu của file PE được tổ chức khi nạp vào bộ nhớ (RAM).
- Đơn vị đo: virtual address (VA).
- Virtual Address: Là địa chỉ của dữ liệu khi chương trình đang chạy.
- Dữ liệu được sắp xếp theo page alignment (thường là bội số của 4 KB).
- 
#### Vấn đề khi dump file PE
1. Lỗi header khi dump từ bộ nhớ:
- Header bị thiết kế cho không gian virtual, nhưng khi dump ra file thì cần header khớp với không gian raw.
- Kết quả: Các công cụ như IDA Pro hoặc trình gỡ lỗi không đọc được.
2. Sửa header để khớp:
- Cần công cụ như [PE-Dump-Fixer](https://github.com/skadro-official/PE-Dump-Fixer) để sửa raw header sao cho đồng bộ với virtual header.
**Cách hoạt động của [PE-Dump-Fixer](https://github.com/skadro-official/PE-Dump-Fixer)**
- [PE-Dump-Fixer](https://github.com/skadro-official/PE-Dump-Fixer) không sửa section alignment trong header để khớp raw offset, mà nó sửa header raw offset để phù hợp với virtual offset của file trong bộ nhớ. Điều này giúp:
- Offset trong bộ nhớ (virtual) và offset trên file dump khớp nhau.
- Tránh phải tính toán lại các offset trong bộ nhớ khi phân tích.
- 
- Sau khi dump file từ bộ nhớ và sửa header bằng PE Dump Fixer, file dump vẫn có các thông tin không cần thiết liên quan đến việc nạp vào bộ nhớ (virtual memory). Ta cần unmap là để loại bỏ những dữ liệu thừa này và chuyển file về trạng thái gần giống với file gốc trên đĩa.
- Sử dụng công cụ [pe unmap](https://github.com/hasherezade/pe_unmapper) để thực hiện
- 
- 
- Ta đã unmap thành công, load vô ida thử
- 
### Resource
- https://medium.com/@andreabocchetti88/windbg-the-next-dbg-generation-for-windows-b6675bdd42c1
- https://www.patterndiagnostics.com/files/Accelerated-Windows-Memory-Dump-Analysis-Versions-1-2-3-AddOn.pdf
- https://romikoderbynew.com/2011/05/07/memory-dump-analysisw3wp-iis-process/
- http://windbg.info/doc/1-common-cmds.html