SlideShare a Scribd company logo
1 of 66
Shellcode Mastering
by Anton Dorfman
About me
• Fan of & Fun with Assembly language
• Reverser
• Teach Reverse Engineering since 2001
• Candidate of technical science
Hands-on Lab structure
• Basics of shellcode
• Basic shellcode techniques
• Shellcode optimization techniques
• Optimization example analysis
• Practice
Required tools
• Windows XP virtual machine
• Windows 7 virtual machine
• Olly Debugger
• Masm32 by hutch v11
• RadASM
• Hview
• Total Commander
Basics of shellcode
Shellcode features
• Base independent
• Small size of code
• Written in Assembly Language
• Used as payload in the exploitation of
vulnerabilities
Types of shellcode
• Local
• Remote
• Download and execute
• Staged
• Null-free shelcode
Shellcode development tasks
• Find yourself in memory (delta offset, value of
the EIP register – program counter)
• Addressing shellcode variables
• Work with strings
Windows specific shellcode tasks
• Find kernel32.dll base address
• Find entry points of needed Win32 API
Basic shellcode techniques
Usual program
Call and Ret algorithms
Delta offset
• call next (or call $+5)
• next:
• pop ebp
• sub ebp,offset next
• Open Delta.asm
• Compile and debug it
• Add bytes before start and check
Zero-null delta offset variant
• call $+4
• ret
• pop ebp
• Open DeltaNoNull.asm
• Compile and debug it
• Check instruction overlap
Addressing shellcode variables
• First – find delta offset of our code
• Commonly used [reg+offset of instruction]
• We can use any registers
• Create VarUsing.asm
• Write in it base-independent (shellcode-like)
variant of “Usual program” example
• Compile and debug it
Addressing shellcode variables
through code blocks structure
• call next
• Var dd 12345678h
• next:
• pop esi – now points to Var
• Create VarUsingBlocks.asm
• Modify VarUsing.asm to use this tecnique
• Compile and debug it
Types of strings in shellcodes
• Come parameters
• Names of dll libraries
• Names of Win32 API
Using strings in stack
• push ‘yt’
• push ‘rewq’
• mov esi,esp - esi now points to string ‘qwerty’
• Create StringUsingStack.asm with using this
technique and string you prefer
• Create StringUsingBlock.asm with the using code
blocks structure technique
• Compile and debug it
Hashes are less then strings
• One hash – 4 bytes
• Hash procedure – x bytes
• Total size of Win32 API names- y bytes
• If (x+4) less then we must use hashes
Restricted but weak hashes
• We can check API namespace of the dll
libraries used in our shellcode for 2-byte or
even 1 byte hashes
Few symbols less then hash
• We can check API namespace of the dll
libraries used in our shellcode for unique
symbols in different positions of the API name
• If we find such “unique positions” we can use
them for checking needed APIs
Find entry points of needed Win32 API
• Using hardcoded addresses of API
• Scan for GetProcAddress
• Find API from Export
Using hardcoded addresses of API
• Find addresses of needed API in OS similar to
target
• Harcode them into shellcode
• For example:
• call 7c801d7bh – kernel32.LoadLibraryA
Ways to find kernel32.dll Base Address
• Hardcoded address
• PEB based (Process Environment Block)
• SEH based (Structured Exception Handler)
• From TOP of the STACK
Kernel32.dll Base from PEB
Kernel32.dll Base from PEB
Kernel32.dll Base from SEH
Kernel32.dll Base from TOP STACK
Scan for GetProcAddress
Find API from Export
Shellcode optimization
techniques
Shellcode optimization techniques
• Structural optimization
• Less action – value reusing optimization
• Local optimization
Instruction format
Types of Opcode byte
ModR/M
SIB
Opcode map - 00h-77h
Opcode map - 08h-7Fh
Opcode map - 80h-F7h
Opcode map - 88h-FFh
Opcode in ModR/M
Common optimization rules
• Relative addresses, offsets and immediate
values are less in instruction if they between -
128: +127 (00h-0FFh)
• Some instructions with eax/ax/al are less for 1
byte
• 1 byte instructions: push reg, pop reg, inc reg,
dec reg, xchg eax,reg
• Chained instructions are best
Zeroing register
• mov eax,00000000h – 5 bytes
• xor eax,eax – 2 bytes
• sub eax,eax – 2 bytes
Assign “-1” to register
• mov eax,0FFFFFFFFh (-1)
• xor eax,eax (sub eax,eax) – 2 bytes
• dec eax – 1 byte
• or eax,-1 – 3 bytes
Check register for zero
• cmp eax,00000000h – 5 bytes
• jz eax_is_zero – 2 bytes
• test eax,eax (or eax,eax) – 2 bytes
• jz eax_is_zero – 2 bytes
• xchg eax,ecx – 1 byte
• jecxz eax_is_zero – 2 bytes
Check register for “-1”
• cmp eax,0FFFFFFFFh – 5 bytes
• jz eax_is_minus_1 – 2 bytes
• inc eax – 1 byte
• jz eax_is_minus_1 – 2 bytes
• dec eax – 1 byte
Assign 8bit value to register
• mov eax,000000FFh – 5 bytes
• xor eax,eax – 2 bytes
• mov al,0FFh – 2 bytes
• push 0FFh – 2 bytes
• pop eax – 1 byte
Отказ от стека
Optimization example analysis
Prehistory
• In 3-th January 2009 guy with nickname “sl0n”
made a proposal for “New Year competition of
smallest download and execute shellcode”
• Link:
http://wasm.ru/forum/viewtopic.php?pid=28
8731
• Participants: sl0n, takerZ cencored, freeman,
researcher (me)
Branches of code optimization
• Sl0n_185 - censored_170 - freeman_163
• researcher_160 - researcher_149 NULL-FREE
branch
• takerZ_160 - takerZ_160_148 -
researcher_153 - takerZ_150 - researcher_141
- takerZ_138 - researcher_137 -
researcher_134
Sl0n_185
• Check the file 1_sl0n_185.asm
• Analyze it structure and actions
censored_170
• Check the file 3_censored_170.asm
• Analyze it structure and actions
freeman_163
• Check the file 4_freeman_163.asm
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
takerZ_160
• Check the file 2_takerZ_160.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
takerZ_160_148
• Check the file 21_takerZ_160_148.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
researcher_160
• Check the file 5_researcher_160.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous - 2_takerZ_160.asm
• Extract optimization changes
• Notify the Null-Free feature
researcher_153
• Check the file 6_researcher_153.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous - 2_takerZ_160.asm
• Extract optimization changes
takerZ_150
• Check the file 7_takerZ_150.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
researcher_149
• Check the file 81_researcher_149.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
• Notify the Null-Free feature
researcher_141
• Check the file 8_researcher_141.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
takerZ_138
• Check the file 9_takerZ_138.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
researcher_137
• Check the file A_researcher_137.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
researcher_134
• Check the file B_researcher_134.asm
• Compile and debug
• Analyze it structure and actions
• Compare with previous
• Extract optimization changes
Task for Practice – VolgaCTF 2013
Quals – PPC 400
• You have some information about a remote vulnerability in a
service of our enemies. This service is based on sockets. You have
already developed an exploit and the second stage shellcode.
• You should write x86 first stage shellcode. Its size should be no
more than XXX bytes. Null bytes are allowed.
• Hardcoded entrypoint addresses of API and image base addresses
of dlls are not allowed. Possible OS platform - Windows, except for
Windows 7.
• Shellcode must do reverse connect to address 127.0.0.1, port 20480
(5000h), receive exactly 512 bytes (our second stage) to buffer and
jump to it (first byte).
• The guy who will check your shellcode is a lazy bastard, so you need
to wait some time before he will answer.
Questions ?

More Related Content

What's hot

Performance Analysis Tools for Linux Kernel
Performance Analysis Tools for Linux KernelPerformance Analysis Tools for Linux Kernel
Performance Analysis Tools for Linux Kernellcplcp1
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0Tim Bunce
 
Return oriented programming
Return oriented programmingReturn oriented programming
Return oriented programminghybr1s
 
Course lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingCourse lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingJonathan Salwan
 
Triton and symbolic execution on gdb
Triton and symbolic execution on gdbTriton and symbolic execution on gdb
Triton and symbolic execution on gdbWei-Bo Chen
 
What you need to remember when you upload to CPAN
What you need to remember when you upload to CPANWhat you need to remember when you upload to CPAN
What you need to remember when you upload to CPANcharsbar
 
Return-Oriented Programming: Exploits Without Code Injection
Return-Oriented Programming: Exploits Without Code InjectionReturn-Oriented Programming: Exploits Without Code Injection
Return-Oriented Programming: Exploits Without Code Injectionguest9f4856
 
One Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationOne Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationQuinn Wilton
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Valeriy Kravchuk
 
[COSCUP 2021] A trip about how I contribute to LLVM
[COSCUP 2021] A trip about how I contribute to LLVM[COSCUP 2021] A trip about how I contribute to LLVM
[COSCUP 2021] A trip about how I contribute to LLVMDouglas Chen
 
typemap in Perl/XS
typemap in Perl/XS  typemap in Perl/XS
typemap in Perl/XS charsbar
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)yang firo
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLitecharsbar
 
An introduction to ROP
An introduction to ROPAn introduction to ROP
An introduction to ROPSaumil Shah
 

What's hot (20)

Performance Analysis Tools for Linux Kernel
Performance Analysis Tools for Linux KernelPerformance Analysis Tools for Linux Kernel
Performance Analysis Tools for Linux Kernel
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
 
Return oriented programming
Return oriented programmingReturn oriented programming
Return oriented programming
 
x86
x86x86
x86
 
Course lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingCourse lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented Programming
 
Return oriented programming (ROP)
Return oriented programming (ROP)Return oriented programming (ROP)
Return oriented programming (ROP)
 
Triton and symbolic execution on gdb
Triton and symbolic execution on gdbTriton and symbolic execution on gdb
Triton and symbolic execution on gdb
 
Advance ROP Attacks
Advance ROP AttacksAdvance ROP Attacks
Advance ROP Attacks
 
What you need to remember when you upload to CPAN
What you need to remember when you upload to CPANWhat you need to remember when you upload to CPAN
What you need to remember when you upload to CPAN
 
Return Oriented Programming (ROP) Based Exploits - Part I
Return Oriented Programming  (ROP) Based Exploits  - Part IReturn Oriented Programming  (ROP) Based Exploits  - Part I
Return Oriented Programming (ROP) Based Exploits - Part I
 
Return-Oriented Programming: Exploits Without Code Injection
Return-Oriented Programming: Exploits Without Code InjectionReturn-Oriented Programming: Exploits Without Code Injection
Return-Oriented Programming: Exploits Without Code Injection
 
One Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationOne Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform Exploitation
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
 
[COSCUP 2021] A trip about how I contribute to LLVM
[COSCUP 2021] A trip about how I contribute to LLVM[COSCUP 2021] A trip about how I contribute to LLVM
[COSCUP 2021] A trip about how I contribute to LLVM
 
Network programming
Network programmingNetwork programming
Network programming
 
typemap in Perl/XS
typemap in Perl/XS  typemap in Perl/XS
typemap in Perl/XS
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
 
An introduction to ROP
An introduction to ROPAn introduction to ROP
An introduction to ROP
 

Viewers also liked

Reverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniquesReverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniquesEran Goldstein
 
The Dark Arts of Hacking.
The Dark Arts of Hacking.The Dark Arts of Hacking.
The Dark Arts of Hacking.Sumutiu Marius
 
Creacion de shellcodes para Exploits en Linux/x86
Creacion de shellcodes para Exploits en Linux/x86 Creacion de shellcodes para Exploits en Linux/x86
Creacion de shellcodes para Exploits en Linux/x86 Internet Security Auditors
 
Design and Implementation of Shellcodes.
Design and Implementation of Shellcodes.Design and Implementation of Shellcodes.
Design and Implementation of Shellcodes.Sumutiu Marius
 
Cisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneCisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneDefconRussia
 
Netcat 101 by-mahesh-beema
Netcat 101 by-mahesh-beemaNetcat 101 by-mahesh-beema
Netcat 101 by-mahesh-beemaRaghunath G
 
Finalppt metasploit
Finalppt metasploitFinalppt metasploit
Finalppt metasploitdevilback
 
Offensive Security with Metasploit
Offensive Security with MetasploitOffensive Security with Metasploit
Offensive Security with Metasploitegypt
 
Manual de integración de Latch en Mosquito MQTT Broker
Manual de integración de Latch en Mosquito MQTT BrokerManual de integración de Latch en Mosquito MQTT Broker
Manual de integración de Latch en Mosquito MQTT BrokerTelefónica
 
Metasploit for Penetration Testing: Beginner Class
Metasploit for Penetration Testing: Beginner ClassMetasploit for Penetration Testing: Beginner Class
Metasploit for Penetration Testing: Beginner ClassGeorgia Weidman
 

Viewers also liked (13)

Reverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniquesReverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniques
 
Exploitation
ExploitationExploitation
Exploitation
 
DLL Injection
DLL InjectionDLL Injection
DLL Injection
 
The Dark Arts of Hacking.
The Dark Arts of Hacking.The Dark Arts of Hacking.
The Dark Arts of Hacking.
 
Creacion de shellcodes para Exploits en Linux/x86
Creacion de shellcodes para Exploits en Linux/x86 Creacion de shellcodes para Exploits en Linux/x86
Creacion de shellcodes para Exploits en Linux/x86
 
Design and Implementation of Shellcodes.
Design and Implementation of Shellcodes.Design and Implementation of Shellcodes.
Design and Implementation of Shellcodes.
 
Ethical Hacking
Ethical HackingEthical Hacking
Ethical Hacking
 
Cisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneCisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-one
 
Netcat 101 by-mahesh-beema
Netcat 101 by-mahesh-beemaNetcat 101 by-mahesh-beema
Netcat 101 by-mahesh-beema
 
Finalppt metasploit
Finalppt metasploitFinalppt metasploit
Finalppt metasploit
 
Offensive Security with Metasploit
Offensive Security with MetasploitOffensive Security with Metasploit
Offensive Security with Metasploit
 
Manual de integración de Latch en Mosquito MQTT Broker
Manual de integración de Latch en Mosquito MQTT BrokerManual de integración de Latch en Mosquito MQTT Broker
Manual de integración de Latch en Mosquito MQTT Broker
 
Metasploit for Penetration Testing: Beginner Class
Metasploit for Penetration Testing: Beginner ClassMetasploit for Penetration Testing: Beginner Class
Metasploit for Penetration Testing: Beginner Class
 

Similar to Shellcode mastering

Ch 18: Source Code Auditing
Ch 18: Source Code AuditingCh 18: Source Code Auditing
Ch 18: Source Code AuditingSam Bowne
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler ConstructionAhmed Raza
 
Игорь Фесенко "Direction of C# as a High-Performance Language"
Игорь Фесенко "Direction of C# as a High-Performance Language"Игорь Фесенко "Direction of C# as a High-Performance Language"
Игорь Фесенко "Direction of C# as a High-Performance Language"Fwdays
 
CNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code AuditingCNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code AuditingSam Bowne
 
Triton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaTriton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaWei-Bo Chen
 
¡El mejor lenguaje para automatizar pruebas!
¡El mejor lenguaje para automatizar pruebas!¡El mejor lenguaje para automatizar pruebas!
¡El mejor lenguaje para automatizar pruebas!Antonio Robres Turon
 
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON
 
Week1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC BeginWeek1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC Begin敬倫 林
 
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...DefconRussia
 
Automatic tool for static analysis
Automatic tool for static analysisAutomatic tool for static analysis
Automatic tool for static analysisChong-Kuan Chen
 
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)Sam Bowne
 
ログ収集プラットフォーム開発におけるElasticsearchの運用
ログ収集プラットフォーム開発におけるElasticsearchの運用ログ収集プラットフォーム開発におけるElasticsearchの運用
ログ収集プラットフォーム開発におけるElasticsearchの運用LINE Corporation
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceESUG
 
Erlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent WorldErlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent WorldZvi Avraham
 
ARM AAE - Developing Code for ARM
ARM AAE - Developing Code for ARMARM AAE - Developing Code for ARM
ARM AAE - Developing Code for ARMAnh Dung NGUYEN
 
CNIT 126 13: Data Encoding
CNIT 126 13: Data EncodingCNIT 126 13: Data Encoding
CNIT 126 13: Data EncodingSam Bowne
 
Scaling ingest pipelines with high performance computing principles - Rajiv K...
Scaling ingest pipelines with high performance computing principles - Rajiv K...Scaling ingest pipelines with high performance computing principles - Rajiv K...
Scaling ingest pipelines with high performance computing principles - Rajiv K...SignalFx
 
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017Dynamic Instrumentation- OpenEBS Golang Meetup July 2017
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017OpenEBS
 

Similar to Shellcode mastering (20)

Ch 18: Source Code Auditing
Ch 18: Source Code AuditingCh 18: Source Code Auditing
Ch 18: Source Code Auditing
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Игорь Фесенко "Direction of C# as a High-Performance Language"
Игорь Фесенко "Direction of C# as a High-Performance Language"Игорь Фесенко "Direction of C# as a High-Performance Language"
Игорь Фесенко "Direction of C# as a High-Performance Language"
 
CNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code AuditingCNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code Auditing
 
Triton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaTriton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON China
 
¡El mejor lenguaje para automatizar pruebas!
¡El mejor lenguaje para automatizar pruebas!¡El mejor lenguaje para automatizar pruebas!
¡El mejor lenguaje para automatizar pruebas!
 
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
 
Avro intro
Avro introAvro intro
Avro intro
 
Week1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC BeginWeek1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC Begin
 
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
 
Automatic tool for static analysis
Automatic tool for static analysisAutomatic tool for static analysis
Automatic tool for static analysis
 
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
 
ログ収集プラットフォーム開発におけるElasticsearchの運用
ログ収集プラットフォーム開発におけるElasticsearchの運用ログ収集プラットフォーム開発におけるElasticsearchの運用
ログ収集プラットフォーム開発におけるElasticsearchの運用
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
Erlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent WorldErlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent World
 
ARM AAE - Developing Code for ARM
ARM AAE - Developing Code for ARMARM AAE - Developing Code for ARM
ARM AAE - Developing Code for ARM
 
CNIT 126 13: Data Encoding
CNIT 126 13: Data EncodingCNIT 126 13: Data Encoding
CNIT 126 13: Data Encoding
 
Scaling ingest pipelines with high performance computing principles - Rajiv K...
Scaling ingest pipelines with high performance computing principles - Rajiv K...Scaling ingest pipelines with high performance computing principles - Rajiv K...
Scaling ingest pipelines with high performance computing principles - Rajiv K...
 
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017Dynamic Instrumentation- OpenEBS Golang Meetup July 2017
Dynamic Instrumentation- OpenEBS Golang Meetup July 2017
 

More from Positive Hack Days

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesPositive Hack Days
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerPositive Hack Days
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesPositive Hack Days
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikPositive Hack Days
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQubePositive Hack Days
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityPositive Hack Days
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Positive Hack Days
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для ApproofPositive Hack Days
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Positive Hack Days
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложенийPositive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложенийPositive Hack Days
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application SecurityPositive Hack Days
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летPositive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиPositive Hack Days
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОPositive Hack Days
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке СиPositive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CorePositive Hack Days
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опытPositive Hack Days
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterPositive Hack Days
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиPositive Hack Days
 

More from Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Recently uploaded

ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 

Recently uploaded (20)

ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 

Shellcode mastering

  • 2. About me • Fan of & Fun with Assembly language • Reverser • Teach Reverse Engineering since 2001 • Candidate of technical science
  • 3. Hands-on Lab structure • Basics of shellcode • Basic shellcode techniques • Shellcode optimization techniques • Optimization example analysis • Practice
  • 4. Required tools • Windows XP virtual machine • Windows 7 virtual machine • Olly Debugger • Masm32 by hutch v11 • RadASM • Hview • Total Commander
  • 6. Shellcode features • Base independent • Small size of code • Written in Assembly Language • Used as payload in the exploitation of vulnerabilities
  • 7. Types of shellcode • Local • Remote • Download and execute • Staged • Null-free shelcode
  • 8. Shellcode development tasks • Find yourself in memory (delta offset, value of the EIP register – program counter) • Addressing shellcode variables • Work with strings
  • 9. Windows specific shellcode tasks • Find kernel32.dll base address • Find entry points of needed Win32 API
  • 12. Call and Ret algorithms
  • 13. Delta offset • call next (or call $+5) • next: • pop ebp • sub ebp,offset next • Open Delta.asm • Compile and debug it • Add bytes before start and check
  • 14. Zero-null delta offset variant • call $+4 • ret • pop ebp • Open DeltaNoNull.asm • Compile and debug it • Check instruction overlap
  • 15. Addressing shellcode variables • First – find delta offset of our code • Commonly used [reg+offset of instruction] • We can use any registers • Create VarUsing.asm • Write in it base-independent (shellcode-like) variant of “Usual program” example • Compile and debug it
  • 16. Addressing shellcode variables through code blocks structure • call next • Var dd 12345678h • next: • pop esi – now points to Var • Create VarUsingBlocks.asm • Modify VarUsing.asm to use this tecnique • Compile and debug it
  • 17. Types of strings in shellcodes • Come parameters • Names of dll libraries • Names of Win32 API
  • 18. Using strings in stack • push ‘yt’ • push ‘rewq’ • mov esi,esp - esi now points to string ‘qwerty’ • Create StringUsingStack.asm with using this technique and string you prefer • Create StringUsingBlock.asm with the using code blocks structure technique • Compile and debug it
  • 19. Hashes are less then strings • One hash – 4 bytes • Hash procedure – x bytes • Total size of Win32 API names- y bytes • If (x+4) less then we must use hashes
  • 20. Restricted but weak hashes • We can check API namespace of the dll libraries used in our shellcode for 2-byte or even 1 byte hashes
  • 21. Few symbols less then hash • We can check API namespace of the dll libraries used in our shellcode for unique symbols in different positions of the API name • If we find such “unique positions” we can use them for checking needed APIs
  • 22. Find entry points of needed Win32 API • Using hardcoded addresses of API • Scan for GetProcAddress • Find API from Export
  • 23. Using hardcoded addresses of API • Find addresses of needed API in OS similar to target • Harcode them into shellcode • For example: • call 7c801d7bh – kernel32.LoadLibraryA
  • 24. Ways to find kernel32.dll Base Address • Hardcoded address • PEB based (Process Environment Block) • SEH based (Structured Exception Handler) • From TOP of the STACK
  • 30. Find API from Export
  • 32. Shellcode optimization techniques • Structural optimization • Less action – value reusing optimization • Local optimization
  • 36. SIB
  • 37. Opcode map - 00h-77h
  • 38. Opcode map - 08h-7Fh
  • 39. Opcode map - 80h-F7h
  • 40. Opcode map - 88h-FFh
  • 42. Common optimization rules • Relative addresses, offsets and immediate values are less in instruction if they between - 128: +127 (00h-0FFh) • Some instructions with eax/ax/al are less for 1 byte • 1 byte instructions: push reg, pop reg, inc reg, dec reg, xchg eax,reg • Chained instructions are best
  • 43. Zeroing register • mov eax,00000000h – 5 bytes • xor eax,eax – 2 bytes • sub eax,eax – 2 bytes
  • 44. Assign “-1” to register • mov eax,0FFFFFFFFh (-1) • xor eax,eax (sub eax,eax) – 2 bytes • dec eax – 1 byte • or eax,-1 – 3 bytes
  • 45. Check register for zero • cmp eax,00000000h – 5 bytes • jz eax_is_zero – 2 bytes • test eax,eax (or eax,eax) – 2 bytes • jz eax_is_zero – 2 bytes • xchg eax,ecx – 1 byte • jecxz eax_is_zero – 2 bytes
  • 46. Check register for “-1” • cmp eax,0FFFFFFFFh – 5 bytes • jz eax_is_minus_1 – 2 bytes • inc eax – 1 byte • jz eax_is_minus_1 – 2 bytes • dec eax – 1 byte
  • 47. Assign 8bit value to register • mov eax,000000FFh – 5 bytes • xor eax,eax – 2 bytes • mov al,0FFh – 2 bytes • push 0FFh – 2 bytes • pop eax – 1 byte
  • 50. Prehistory • In 3-th January 2009 guy with nickname “sl0n” made a proposal for “New Year competition of smallest download and execute shellcode” • Link: http://wasm.ru/forum/viewtopic.php?pid=28 8731 • Participants: sl0n, takerZ cencored, freeman, researcher (me)
  • 51. Branches of code optimization • Sl0n_185 - censored_170 - freeman_163 • researcher_160 - researcher_149 NULL-FREE branch • takerZ_160 - takerZ_160_148 - researcher_153 - takerZ_150 - researcher_141 - takerZ_138 - researcher_137 - researcher_134
  • 52. Sl0n_185 • Check the file 1_sl0n_185.asm • Analyze it structure and actions
  • 53. censored_170 • Check the file 3_censored_170.asm • Analyze it structure and actions
  • 54. freeman_163 • Check the file 4_freeman_163.asm • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 55. takerZ_160 • Check the file 2_takerZ_160.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 56. takerZ_160_148 • Check the file 21_takerZ_160_148.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 57. researcher_160 • Check the file 5_researcher_160.asm • Compile and debug • Analyze it structure and actions • Compare with previous - 2_takerZ_160.asm • Extract optimization changes • Notify the Null-Free feature
  • 58. researcher_153 • Check the file 6_researcher_153.asm • Compile and debug • Analyze it structure and actions • Compare with previous - 2_takerZ_160.asm • Extract optimization changes
  • 59. takerZ_150 • Check the file 7_takerZ_150.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 60. researcher_149 • Check the file 81_researcher_149.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes • Notify the Null-Free feature
  • 61. researcher_141 • Check the file 8_researcher_141.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 62. takerZ_138 • Check the file 9_takerZ_138.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 63. researcher_137 • Check the file A_researcher_137.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 64. researcher_134 • Check the file B_researcher_134.asm • Compile and debug • Analyze it structure and actions • Compare with previous • Extract optimization changes
  • 65. Task for Practice – VolgaCTF 2013 Quals – PPC 400 • You have some information about a remote vulnerability in a service of our enemies. This service is based on sockets. You have already developed an exploit and the second stage shellcode. • You should write x86 first stage shellcode. Its size should be no more than XXX bytes. Null bytes are allowed. • Hardcoded entrypoint addresses of API and image base addresses of dlls are not allowed. Possible OS platform - Windows, except for Windows 7. • Shellcode must do reverse connect to address 127.0.0.1, port 20480 (5000h), receive exactly 512 bytes (our second stage) to buffer and jump to it (first byte). • The guy who will check your shellcode is a lazy bastard, so you need to wait some time before he will answer.