Skip to content

Instantly share code, notes, and snippets.

@nnnewb
Last active October 12, 2021 08:03
Show Gist options
  • Save nnnewb/8ce17449d7bde9f6560258f816d7e509 to your computer and use it in GitHub Desktop.
Save nnnewb/8ce17449d7bde9f6560258f816d7e509 to your computer and use it in GitHub Desktop.
PE from scratch with nasm
; author: weak_ptr <weak_ptr@outlook.com>
; date: 2021-10-11 17:01
; description: PE from scratch with nasm assembler
;
; reference: http://www.phreedom.org/research/tinype/
;
; compile command: nasm -f bin tinype.asm -o tinype.exe
;
BITS 32
$FILEALIGN equ 400h
$SECTALIGN equ 1000h
$IMAGEBASE equ 0x4000000
%define ROUND(n, r) (((n+(r-1))/r)*r)
dos_header:
.magic dw "MZ"
.cblp dw 90h
.cp dw 3
.crlc dw 0
.cparhdr dw 4
.minalloc dw 0
.maxalloc dw -1
.ss dw 0
.sp dw 0B8h
.csum dw 0
.ip dw 0
.cs dw 0
.lfarlc dw 40h
.ovno dw 0
.res times 4 dw 0
.oemid dw 0
.oeminfo dw 0
.res2 times 10 dw 0
.lfanew dd .next
.next:
nt_header:
pe_signature:
.sig dd "PE"
file_header:
.machine dw 0x014c
.numberofsections dw 0x02
.timedatestamp dd 0
.pointertosymboltable dd 0
.numberofsymbols dd 0
.optheadersize dw $OPT_HEADER_SIZE
.characteristics dw 0x102
optional_header:
.magic dw 0x10b
.linker_version db 8,0
.sizeof_code dd 1000h
.sizeof_initialized_data dd 0
.sizeof_uninitialized_data dd 0
.addressof_entrypoint dd 1000h
.baseof_code dd 1000h
.baseof_data dd 2000h
.image_base dd $IMAGEBASE
.section_alignment dd $SECTALIGN
.file_alignment dd $FILEALIGN
.os_version dw 4,0
.img_version dw 0,0
.subsystem_version dw 5,0
.win32_ver_value dd 0
.sizeof_img dd 3000h
.sizeof_headers dd ROUND($HEADER_SIZE, $FILEALIGN)
.checksum dd 0
.subsystem dw 2
.dll_characteristics dw 0x400
.sizeof_stack_reserved dd 0x100000
.sizeof_stack_commit dd 0x1000
.sizeof_heap_reserved dd 0x100000
.sizeof_heap_commit dd 0x1000
.loeader_flags dd 0
.numberof_rva_and_sizes dd 10h
data_directories:
times 10h dd 0, 0
$OPT_HEADER_SIZE equ $ - optional_header
section_table:
.text:
db ".text", 0, 0, 0 ; section name
dd 1000h ; virtual size
dd 1000h ; virtual address
dd ROUND($CODESIZE, $FILEALIGN) ; sizeof raw data
dd code ; pointer to raw data
dd 0 ; pointer to relocations
dd 0 ; pointer to linenum
dw 0 ; number of relocations
dw 0 ; number of linenum
dd 0x60000020 ; characteristics
.alloc:
db ".alloc", 0, 0 ; section name
dd 1000h ; virtual size
dd 2000h ; virtual address
dd ROUND($DATASIZE, $FILEALIGN) ; sizeof raw data
dd data ; pointer to raw data
dd 0 ; pointer to relocations
dd 0 ; pointer to linenum
dw 0 ; number of relocations
dw 0 ; number of linenum
dd 0x40000000 ; characteristics
align $FILEALIGN, db 0
$HEADER_SIZE equ $ - $$
code:
.start:
push byte 42
pop eax
ret
align $FILEALIGN, db 0
$CODESIZE equ $ - code
data:
times 10h db 0
align $FILEALIGN, db 0
$DATASIZE equ $ - data
$FILESIZE equ $ - $$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment