### Install pwntools with apt-get and pip Source: https://github.com/gallopsled/pwntools/blob/dev/README.md Installs necessary system dependencies and then upgrades pip and installs pwntools using pip. This is the recommended installation method for Ubuntu. ```shell sudo apt-get update sudo apt-get install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential python3 -m pip install --upgrade pip python3 -m pip install --upgrade pwntools ``` -------------------------------- ### Default Configuration Example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/config.md This snippet shows an example of the default configuration file format, including sections for logging, context, and updates. ```ini [log] success.symbol=😎 error.symbol=☠ info.color=blue [context] adb_port=4141 randomize=1 timeout=60 terminal=['x-terminal-emulator', '-e'] [update] interval=7 ``` -------------------------------- ### pwnlib.testexample.add function examples Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/testexample.md Examples of using the 'add' function from the pwnlib.testexample module with different integer inputs. ```pycon >>> add(1,2) 3 ``` ```pycon >>> add(-1, 33) 32 ``` -------------------------------- ### Install Binutils on Ubuntu Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install/binutils.md Installs necessary software properties and adds the pwntools PPA for binutils on Ubuntu. ```bash sudo apt-get install software-properties-common sudo apt-add-repository ppa:pwntools/binutils sudo apt-get update ``` -------------------------------- ### Install and Run Pwntools Test Suite Source: https://github.com/gallopsled/pwntools/blob/dev/TESTING.md Commands to set up the environment and execute the full test suite for pwntools. This includes installing dependencies and running doctests. ```bash bash travis/install.sh bash travis/ssh_setup.sh pip install --upgrade --editable . pip install --upgrade -r docs/requirements.txt PWNLIB_NOTERM=1 make -C docs doctest ``` -------------------------------- ### Install QEMU User Mode Emulator Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/qemu.md Installs the QEMU user-mode emulator package. This is sufficient if your binary is statically linked. ```bash sudo apt-get install qemu-user ``` -------------------------------- ### Install Cross-Architecture C Library Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/qemu.md Installs the C library for a specific cross-architecture, necessary for dynamically linked binaries. Example for ARM64. ```bash sudo apt-get install libc6-arm64-cross ``` -------------------------------- ### Build Binutils from Source Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install/binutils.md Builds and installs binutils from source for a specified version and architecture. This script handles downloading, verifying, configuring, and installing binutils. ```bash #!/usr/bin/env bash V=2.38 # Binutils Version ARCH=arm # Target architecture cd ${TMPDIR:-/tmp} wget -nc https://ftp.gnu.org/gnu/binutils/binutils-$V.tar.gz wget -nc https://ftp.gnu.org/gnu/binutils/binutils-$V.tar.gz.sig gpg --keyserver keys.gnupg.net --recv-keys 4AE55E93 gpg --verify binutils-$V.tar.gz.sig tar xf binutils-$V.tar.gz mkdir binutils-build cd binutils-build export AR=ar export AS=as ../binutils-$V/configure \ --prefix=${PREFIX:-/usr/local} \ --target=$ARCH-unknown-linux-gnu \ --disable-static \ --disable-multilib \ --disable-werror \ --disable-nls MAKE=gmake hash gmake || MAKE=make $MAKE -j clean all sudo $MAKE install ``` -------------------------------- ### i386 push instruction examples Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/i386.md Illustrates how to push values onto the stack using shellcraft for i386. Examples include pushing immediate integers, constants evaluated from strings (like system call numbers), and handling OS-specific values. ```python print(pwnlib.shellcraft.i386.push(0).rstrip()) ``` ```python print(pwnlib.shellcraft.i386.push(1).rstrip()) ``` ```python print(pwnlib.shellcraft.i386.push(256).rstrip()) ``` ```python print(pwnlib.shellcraft.i386.push('SYS_execve').rstrip()) ``` ```python print(pwnlib.shellcraft.i386.push('SYS_sendfile').rstrip()) ``` ```python with context.local(os = 'freebsd'): print(pwnlib.shellcraft.i386.push('SYS_execve').rstrip()) ``` -------------------------------- ### SSH Connection with Pwntools Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md Example showing how to establish an SSH connection using the `ssh` class provided by pwntools. ```python from pwn import * # Example of using the ssh class # try: # p = ssh('user@example.com', password='password') # print(p.upload('/path/to/local/file', '/path/to/remote/file')) # print(p.download('/path/to/remote/file', '/path/to/local/file')) # p.close() # except Exception as e: # print(f'SSH connection failed: {e}') ``` -------------------------------- ### Cache directory example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/context.md Demonstrates checking, resetting, and verifying the cache directory behavior. ```python >>> cache_dir = context.cache_dir >>> cache_dir is not None True >>> os.chmod(cache_dir, 0o000) >>> context.cache_dir = True >>> context.cache_dir is None True >>> os.chmod(cache_dir, 0o755) >>> cache_dir == context.cache_dir True >>> context.cache_dir = None >>> context.cache_dir is None True >>> context.cache_dir = True >>> context.cache_dir is not None True ``` -------------------------------- ### ARM Linux Syscall Examples Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/arm.md Demonstrates how to generate ARM shellcode for Linux system calls using shellcraft. Includes examples for general syscalls and specific ones like exit. ```python print(shellcraft.arm.linux.syscall(11, 1, 'sp', 2, 0).rstrip()) ``` ```python print(shellcraft.arm.linux.syscall('SYS_exit', 0).rstrip()) ``` -------------------------------- ### ARM SROP Example: Write Message Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/rop/srop.md Shows how to implement SROP on ARM architecture for a write syscall. Includes assembly setup and SigreturnFrame construction for ARM registers. ```python >>> context.clear() >>> context.arch = "arm" >>> assembly = 'setup: sub sp, sp, 1024\n' >>> assembly += 'read:' + shellcraft.read(constants.STDIN_FILENO, 'sp', 1024) >>> assembly += 'sigreturn:' + shellcraft.sigreturn() >>> assembly += 'int3:' + shellcraft.trap() >>> assembly += 'syscall: ' + shellcraft.syscall() >>> assembly += 'exit: ' + 'eor r0, r0; mov r7, 0x1; swi #0;' >>> assembly += 'message: ' + ('.asciz "%s"' % message) >>> binary = ELF.from_assembly(assembly) ``` ```python >>> frame = SigreturnFrame() >>> frame.r7 = constants.SYS_write >>> frame.r0 = constants.STDOUT_FILENO >>> frame.r1 = binary.symbols['message'] >>> frame.r2 = len(message) >>> frame.sp = 0xdead0000 >>> frame.pc = binary.symbols['syscall'] ``` ```python >>> p = process(binary.path) >>> p.send(bytes(frame)) >>> p.recvline() b'Hello, World\n' >>> p.wait_for_close() >>> p.poll(block=True) 0 ``` -------------------------------- ### Interact with a spawned Python process Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/processes.md This example demonstrates spawning a Python interpreter, sending commands, and receiving output. It shows how to use `sendline`, `recv`, `recvline`, `recvuntil`, and `recvregex` for interactive communication. The example also illustrates checking for closed connections and handling `EOFError`. ```python >>> p = process('python') >>> p.sendline(b"print('Hello world')") >>> p.sendline(b"print('Wow, such data')") >>> b'' == p.recv(timeout=0.01) True >>> p.shutdown('send') >>> p.proc.stdin.closed True >>> p.connected('send') False >>> p.recvline(drop=True) b'Hello world' >>> p.recvuntil(b',') b'Wow,' >>> p.recvregex(b'.*data') b' such data' >>> p.recv()[-1:] == b'\n' True >>> p.recv() Traceback (most recent call last): ... (omitted for brevity) EOFError ``` -------------------------------- ### Configure Options with Pwntools UI Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md Example showing the usage of `pwnlib.ui.options()` for configuring program options. ```python from pwn import * # Example of using options # options = { # '--verbose': False, # '--output': None # } # args = options.parse_args(options) ``` -------------------------------- ### i386 mov instruction examples Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/i386.md Demonstrates various ways to generate the 'mov' instruction for i386 architecture using shellcraft. Covers direct register moves, immediate values, and conversions between register sizes. Some examples show alternative methods for pushing values onto the stack when direct moves are not suitable or when avoiding null bytes. ```python print(shellcraft.i386.mov('eax','ebx').rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 0).rstrip()) ``` ```python print(shellcraft.i386.mov('ax', 0).rstrip()) ``` ```python print(shellcraft.i386.mov('ax', 17).rstrip()) ``` ```python print(shellcraft.i386.mov('edi', ord('\n')).rstrip()) ``` ```python print(shellcraft.i386.mov('al', 'ax').rstrip()) ``` ```python print(shellcraft.i386.mov('esp', 'esp').rstrip()) ``` ```python print(shellcraft.i386.mov('ax', 'bl').rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 1).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 1, stack_allowed=False).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 0xdead00ff).rstrip()) ``` ```python print(shellcraft.i386.mov('edi', 0xc0).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 0xc000).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 0xffc000).rstrip()) ``` ```python print(shellcraft.i386.mov('edi', 0xc000).rstrip()) ``` ```python print(shellcraft.i386.mov('edi', 0xf500).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 0xc0c0).rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 'SYS_execve').rstrip()) ``` ```python with context.local(os='freebsd'): print(shellcraft.i386.mov('eax', 'SYS_execve').rstrip()) ``` ```python print(shellcraft.i386.mov('eax', 'PROT_READ | PROT_WRITE | PROT_EXEC').rstrip()) ``` -------------------------------- ### Install Binutils for Specific Architecture on Ubuntu Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install/binutils.md Installs the binutils package for a specified target architecture on Ubuntu. ```bash sudo apt-get install binutils-$ARCH-linux-gnu ``` -------------------------------- ### Assemble and Use Shellcode with Pwntools Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md Example showing the interface to `pwnlib.asm.asm` and `pwnlib.shellcraft` for assembling and generating shellcode. ```python from pwn import * context.clear() context.arch = 'amd64' context.os = 'linux' # Example of shellcode generation # print(asm(shellcraft.sh())) # Example of assembly # print(asm('mov rax, 0x3b; mov rdi, 0x602030; mov rsi, 0x0; xor rdx, rdx; syscall')) ``` -------------------------------- ### Install Pwntools with Python 3 Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install.md Installs necessary system libraries and then installs the latest version of pwntools using pip for Python 3. Ensure you have Python 3.10 or later. ```bash $ sudo apt-get update $ sudo apt-get install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential $ python3 -m pip install --upgrade pip $ python3 -m pip install --upgrade pwntools ``` -------------------------------- ### adb.install() Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/adb.md Installs an APK onto the Android device. ```APIDOC ## install(apk, *arguments) ### Description Installs an Android application package (APK) onto the connected device. This function is a wrapper around the `pm install` command. ### Method N/A (Function call) ### Parameters - **apk** (str) - Path to the APK file to install (e.g., `'app.apk'`). - **arguments** - Supplementary arguments to pass to `pm install`, such as `'-l'` or `'-g'`. ### Response None ``` -------------------------------- ### Display Spinners with Pwntools Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md This example simply displays a variety of spinners provided by pwntools. ```python from pwn import * # Example of displaying spinners # for _ in range(10): # spinner.status('Loading...') # time.sleep(0.1) # spinner.success('Done!') ``` -------------------------------- ### Configure QEMU Library Path Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/qemu.md Creates a symlink to tell QEMU where to find libraries for a specific architecture. This example is for 'aarch64'. ```bash sudo mkdir /etc/qemu-binfmt sudo ln -s /usr/aarch64-linux-gnu /etc/qemu-binfmt/aarch64 ``` -------------------------------- ### pwnlib.util.proc.starttime Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/util/proc.md Retrieves the time (in seconds) the process started after system boot. ```APIDOC ## pwnlib.util.proc.starttime(pid) ### Description Retrieves the time (in seconds) the process started after system boot. ### Parameters #### Path Parameters - **pid** (int) - Required - PID of the process. ### Returns The time (in seconds) the process started after system boot. ``` -------------------------------- ### Compare start times of parent and child processes Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/util/proc.md Compares the start times of the current process and its parent process. Useful for verifying process startup order. ```python >>> starttime(os.getppid()) <= starttime(os.getpid()) True ``` -------------------------------- ### pwnlib.adb.adb.packages Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/adb.md Returns a list of packages installed on the system. ```APIDOC ## pwnlib.adb.adb.packages ### Description Returns a list of packages installed on the system. ``` -------------------------------- ### Create and use a TCP server with next_connection() Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/sockets.md This example demonstrates how to create a TCP server, establish a connection from a client, send data, and receive it. It uses the `next_connection()` method to retrieve the client connection. ```python s = server(8888) client_conn = remote('localhost', s.lport) server_conn = s.next_connection() client_conn.sendline(b'Hello') server_conn.recvline() client_conn.close() s.close() ``` -------------------------------- ### Mipsel SROP Example: Write Message Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/rop/srop.md An example of SROP on Mipsel (little-endian) for a write syscall. Shows assembly setup and SigreturnFrame configuration for Mipsel registers. ```python >>> context.clear() >>> context.arch = "mips" >>> context.endian = "little" >>> assembly = 'setup: sub $sp, $sp, 1024\n' >>> assembly += 'read:' + shellcraft.read(constants.STDIN_FILENO, '$sp', 1024) >>> assembly += 'sigreturn:' + shellcraft.sigreturn() >>> assembly += 'syscall: ' + shellcraft.syscall() >>> assembly += 'exit: ' + shellcraft.exit(0) >>> assembly += 'message: ' + ('.asciz "%s"' % message) >>> binary = ELF.from_assembly(assembly) ``` -------------------------------- ### MIPS SROP Example: Write Message Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/rop/srop.md Provides an example of SROP on MIPS (big-endian) for a write syscall. Demonstrates assembly setup and SigreturnFrame configuration for MIPS registers. ```python >>> context.clear() >>> context.arch = "mips" >>> context.endian = "big" >>> assembly = 'setup: sub $sp, $sp, 1024\n' >>> assembly += 'read:' + shellcraft.read(constants.STDIN_FILENO, '$sp', 1024) >>> assembly += 'sigreturn:' + shellcraft.sigreturn() >>> assembly += 'syscall: ' + shellcraft.syscall() >>> assembly += 'exit: ' + shellcraft.exit(0) >>> assembly += 'message: ' + ('.asciz "%s"' % message) >>> binary = ELF.from_assembly(assembly) ``` ```python >>> frame = SigreturnFrame() >>> frame.v0 = constants.SYS_write >>> frame.a0 = constants.STDOUT_FILENO >>> frame.a1 = binary.symbols['message'] >>> frame.a2 = len(message) >>> frame.sp = 0xdead0000 >>> frame.pc = binary.symbols['syscall'] ``` ```python >>> p = process(binary.path) >>> p.send(bytes(frame)) >>> p.recvline() b'Hello, World\n' >>> p.poll(block=True) 0 ``` -------------------------------- ### Use Remote Tube with Pwntools Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md Example demonstrating how to use the `remote` class for network communication. ```python from pwn import * # Example of using the remote class # p = remote('example.com', 1337) # p.sendline(b'hello') # print(p.recvline()) # p.close() ``` -------------------------------- ### Thread Context Inheritance Example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/context.md Demonstrates how pwnlib.context.Thread inherits the context, while a standard threading.Thread starts with a default context. Shows context isolation between threads. ```python >>> context.clear() >>> context.update(arch='arm') >>> def p(): ... print(context.arch) ... context.arch = 'mips' ... print(context.arch) >>> # Note that a normal Thread starts with a clean context >>> # (i386 is the default architecture) >>> t = threading.Thread(target=p) >>> _=(t.start(), t.join()) i386 mips >>> # Note that the main Thread's context is unchanged >>> print(context.arch) arm >>> # Note that a context-aware Thread receives a copy of the context >>> t = pwnlib.context.Thread(target=p) >>> _=(t.start(), t.join()) arm mips >>> # Again, the main thread is unchanged >>> print(context.arch) arm ``` -------------------------------- ### Evaluate Input with pwnlib.term.readline.eval_input Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/term/readline.md Demonstrates how to use eval_input to get a dictionary-like input and access its elements. This example simulates input redirection and restores original stdin and term_mode afterwards. ```python >>> try: ... saved = sys.stdin, pwnlib.term.term_mode ... pwnlib.term.term_mode = False ... sys.stdin = io.TextIOWrapper(io.BytesIO(b"{'a': 20}")) ... eval_input("Favorite object? ")['a'] ... finally: ... sys.stdin, pwnlib.term.term_mode = saved Favorite object? 20 ``` -------------------------------- ### Create and use a TCP server with a callback Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/sockets.md This example shows how to set up a TCP server that uses a callback function to handle incoming connections. The callback receives a tube, processes client input (reversing it), and sends it back. The server is configured to not block the accepter thread while the callback is running. ```python def cb(r): client_input = r.readline() r.send(client_input[::-1]) t = server(8888, callback=cb) client_conn = remote('localhost', t.lport) client_conn.sendline(b'callback') client_conn.recv() client_conn.close() t.close() ``` -------------------------------- ### Install APK on Android Device Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/adb.md Installs an APK file onto the Android device, with support for additional arguments for the 'pm install' command. ```python adb.install(apk, *arguments) ``` -------------------------------- ### Linux open file example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/amd64.md Demonstrates opening a file in Linux using the 'open' syscall. The file path is pushed onto the stack and then used as an argument. ```python print(pwnlib.shellcraft.amd64.linux.open('/home/pwn/flag').rstrip()) ``` -------------------------------- ### Install Pwntools with Python 2 (Deprecated) Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install.md Installs necessary system libraries and then installs pwntools v4.15.0 using pip for Python 2. This version is deprecated and requires a specific pip version. ```bash $ sudo apt-get update $ sudo apt-get install python python-pip python-dev git libssl-dev libffi-dev build-essential $ python2 -m pip install --upgrade pip==20.3.4 $ python2 -m pip install --upgrade pwntools ``` -------------------------------- ### Linux Syscall Example (Thumb) Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/thumb.md Demonstrates how to generate Thumb assembly for a Linux syscall using shellcraft. The syscall number and arguments are provided directly. ```python print(shellcraft.thumb.linux.syscall(11, 1, 'sp', 2, 0).rstrip()) ``` -------------------------------- ### Download and Install Binutils Recipe on Mac OS X Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install/binutils.md Downloads a binutils Homebrew recipe and installs it on Mac OS X. ```bash wget https://raw.githubusercontent.com/Gallopsled/pwntools-binutils/master/macos/binutils-$ARCH.rb brew install ./binutils-$ARCH.rb ``` -------------------------------- ### Start ADB proxy for debugging Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/protocols.md The `proxy` function starts an ADB proxy on a specified port, which is useful for debugging ADB interactions. ```python >>> pwnlib.protocols.adb.proxy(port=9999) ``` -------------------------------- ### Set up a Listener and Connect Remotely Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/intro.md Starts a listener on a random port and establishes a remote connection to it, allowing for inter-process communication testing. ```pycon >>> l = listen() >>> r = remote('localhost', l.lport) >>> c = l.wait_for_connection() >>> r.send(b'hello') >>> c.recv() b'hello' ``` -------------------------------- ### Get Length of FileStructure Object Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/filepointer.md Demonstrates how to get the byte length of a FileStructure object. This is useful for understanding the memory footprint of the structure. ```python >>> len(fileStr) 224 ``` -------------------------------- ### Check for RPyC installation in GDB Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Ensure the `rpyc` package is installed in GDB's Python environment if Pwntools uses a different interpreter. ```bash $ gdb -batch -ex "python import rpyc" ``` -------------------------------- ### Present user with options Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/ui.md Use `options` to present a prompt with a list of choices to the user. It returns the user's selected option as an integer. The default option can be specified. ```python >>> options("Select a color", ("red", "green", "blue"), "green") Traceback (most recent call last): ... ValueError: options(): default must be a number or None ``` ```python >>> p = testpwnproc("print(options('select a color', ('red', 'green', 'blue')))") >>> p.sendline(b"\33[C\33[A\33[A\33[B\33[1;5A\33[1;5B 0310") >>> _ = p.recvall() >>> saved_stdin = sys.stdin >>> try: ... sys.stdin = io.TextIOWrapper(io.BytesIO(b"\n4\n\n3\n")) ... with context.local(log_level="INFO"): ... options("select a color A", ("red", "green", "blue"), 0) ... options("select a color B", ("red", "green", "blue")) ... finally: ... sys.stdin = saved_stdin [?] select a color A 1) red 2) green 3) blue Choice [1] 0 [?] select a color B 1) red 2) green 3) blue Choice [?] select a color B 1) red 2) green 3) blue Choice [?] select a color B 1) red 2) green 3) blue Choice 2 ``` -------------------------------- ### Development Installation of Pwntools Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install.md Clones the pwntools repository and installs it in editable mode for local development. This allows for direct modifications to the library code. ```bash $ git clone https://github.com/Gallopsled/pwntools $ pip install --upgrade --editable ./pwntools ``` -------------------------------- ### Create a temporary directory and file on remote SSH Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/filesystem.md Demonstrates creating an SSH connection, setting a working directory, creating a file using touch(), checking its existence, resolving its absolute path, writing text content, and reading it back as bytes. ```python >>> ssh_conn = ssh('travis', 'example.pwnme') >>> _ = ssh_conn.set_working_directory() >>> f = SSHPath('filename', ssh=ssh_conn) >>> f.touch() >>> f.exists() True >>> f.resolve().path # doctests: +ELLIPSIS '/tmp/.../filename' >>> f.write_text('asdf ❤️') >>> f.read_bytes() b'asdf \xe2\x9d\xa4\xef\xb8\x8f' ``` -------------------------------- ### Install Python Development Headers on Ubuntu Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/install/headers.md Use this command to install the Python development headers package on Ubuntu systems. This is required for building native extensions. ```bash $ sudo apt-get install python-dev ``` -------------------------------- ### ROP object initialization and basic usage Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/rop/rop.md Demonstrates initializing a ROP object with an ELF file and using its methods to add gadgets and chain calls. This provides a foundational example for using the ROP class. ```python elf = ELF('ropasaurusrex') rop = ROP(elf) rop.read(0, elf.bss(0x80)) rop.dump() # ['0x0000: 0x80482fc (read)', # '0x0004: 0xdeadbeef', # '0x0008: 0x0', # '0x000c: 0x80496a8'] bytes(rop) ``` -------------------------------- ### SSH Remote Listen Example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Shows how to listen remotely through an SSH connection, equivalent to using `ssh -R`. It sets up a listener and then establishes a connection back to the remote listener. ```python >>> from pwn import * >>> s = ssh(host='example.pwnme') >>> l = s.listen_remote() >>> a = remote(s.host, l.port) >>> a=a; b = l.wait_for_connection() # a=a; prevents hangs >>> a.sendline(b'Hello') >>> print(repr(b.recvline())) b'Hello\n' ``` -------------------------------- ### Debug a new process from the start Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Use `debug()` to start a new process under GDB, stopped at the first instruction or `main`. The return value is a tube object. ```python p = gdb.debug("./binary") ``` -------------------------------- ### Set Multiple Registers with Dependencies Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/arm.md Demonstrates setting multiple registers, handling dependencies between them. Shows examples for simple assignments and register swaps. ```python >>> print(shellcraft.setregs({'r0':1, 'r2':'r3'}).rstrip()) mov r0, #1 mov r2, r3 ``` ```python >>> print(shellcraft.setregs({'r0':'r1', 'r1':'r0', 'r2':'r3'}).rstrip()) mov r2, r3 eor r0, r0, r1 /* xchg r0, r1 */ eor r1, r0, r1 eor r0, r0, r1 ``` -------------------------------- ### RISCV64: Push empty string and get hex representation Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/riscv64.md Shows how to push an empty string and get its assembled hex representation. Useful for stack manipulation with no data. ```python print(enhex(asm(shellcraft.riscv64.pushstr("")))) 232c01fe130181ff ``` -------------------------------- ### Interconnect Sockets with Pwntools Uroboros Example Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md An example script demonstrating the interconnection of sockets. This script waits for three connections on port 1337 and then connects them in a three-way Uroboros fashion. ```python from pwn import * # Example of setting up interconnected sockets # server = listen(1337) # clients = [] # for _ in range(3): # clients.append(server.wait_for_connection()) # connect_both(clients[0], clients[1]) # connect_both(clients[1], clients[2]) # connect_both(clients[2], clients[0]) # pause() ``` -------------------------------- ### Set Working Directory with Symlink and Check for File Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Demonstrates setting the working directory using a symlink and checking for file presence, ensuring the directory differs from the home directory. ```python >>> _=s.set_working_directory(symlink=True) >>> assert b'foo' in s.ls().split(), s.ls().split() >>> assert homedir != s.pwd() ``` -------------------------------- ### Get remaining sequence from cyclic_gen Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/util/cyclic.md Demonstrates using `get()` without arguments to retrieve the rest of the sequence from a `cyclic_gen` instance. It also shows the `StopIteration` exception when the generator is exhausted. ```python >>> g = cyclic_gen() >>> g.get(4) # Get a chunk of length 4 b'aaaa' >>> g.get(4) # Get a chunk of length 4 b'baaa' >>> g.get(8) # Get a chunk of length 8 b'caaadaaa' >>> g.get(4) # Get a chunk of length 4 b'eaaa' >>> g.get() # Get the rest of the sequence b'faaagaaahaaaiaaajaaa...yyxzyzxzzyxzzzyyyyzyyzzyzyzzzz' >>> g.get(12) # Generator is exhausted Traceback (most recent call last): ... StopIteration ``` -------------------------------- ### FreeBSD i386 syscall execve example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/i386.md Generates shellcode for the execve syscall on FreeBSD. The first example calls execve with specific arguments, while the second demonstrates a different set of arguments. ```python print(pwnlib.shellcraft.i386.freebsd.syscall('SYS_execve', 1, 'esp', 2, 0).rstrip()) ``` ```python print(pwnlib.shellcraft.i386.freebsd.syscall('SYS_execve', 2, 1, 0, 20).rstrip()) ``` -------------------------------- ### Basic SSH Process Execution Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Demonstrates basic command execution, including sending commands, receiving output, and handling different argument types. Shows how to execute commands with specific environments and working directories. ```python >>> s = ssh(host='example.pwnme') >>> sh = s.process('/bin/sh', env={'PS1':''}) >>> sh.sendline(b'echo Hello; exit') >>> sh.recvall() b'Hello\n' >>> s.process(['/bin/echo', b'\xff']).recvall() b'\xff\n' >>> s.process(['readlink', '/proc/self/exe']).recvall() b'.../bin/readlink\n' >>> s.process(['LOLOLOL', '/proc/self/exe'], executable='readlink').recvall() b'.../bin/readlink\n' >>> s.process(['LOLOLOL\x00', '/proc/self/cmdline'], executable='cat').recvall() b'LOLOLOL\x00/proc/self/cmdline\x00' >>> sh = s.process(executable='/bin/sh') >>> str(sh.pid).encode() in s.pidof('sh') True >>> io = s.process(['pwd'], cwd='/tmp') >>> io.recvall() b'/tmp\n' >>> io.cwd '/tmp' >>> p = s.process(['python','-c','import os; os.write(1, os.read(2, 1024))'], stderr=0) >>> p.send(b'hello') >>> p.recv() b'hello' >>> s.process(['/bin/echo', 'hello']).recvall() b'hello\n' >>> s.process(['/bin/echo', 'hello'], stdout='/dev/null').recvall() b'' >>> s.process(['/usr/bin/env'], env={}).recvall() b'' >>> s.process('/usr/bin/env', env={'A':'B'}).recvall() b'A=B\n' ``` -------------------------------- ### Connect to a Remote Host and Write Data Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/i386.md This example establishes a network connection to a specified host and port, then writes data to the connected socket. The connected socket is left in the EDX register. It demonstrates both IPv4 and IPv6 connections. ```python >>> l = listen(timeout=5) >>> assembly = shellcraft.i386.linux.connect('localhost', l.lport) >>> assembly += shellcraft.i386.pushstr('Hello') >>> assembly += shellcraft.i386.linux.write('edx', 'esp', 5) >>> p = run_assembly(assembly) >>> l.wait_for_connection().recv() b'Hello' ``` ```python >>> l = listen(fam='ipv6', timeout=5) >>> assembly = shellcraft.i386.linux.connect('::1', l.lport, 'ipv6') >>> p = run_assembly(assembly) >>> assert l.wait_for_connection() ``` -------------------------------- ### Linux i386 syscall execve example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/i386.md Generates shellcode for the execve syscall on Linux. The first example calls execve with specific arguments, while the second demonstrates a different set of arguments. ```python print(pwnlib.shellcraft.i386.linux.syscall('SYS_execve', 1, 'esp', 2, 0).rstrip()) ``` ```python print(pwnlib.shellcraft.i386.linux.syscall('SYS_execve', 2, 1, 0, 20).rstrip()) ``` -------------------------------- ### Buffer Initialization and Data Handling Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/buffer.md Demonstrates adding data to a Buffer and retrieving it. Shows how the buffer manages data chunks and returns empty bytes when exhausted. ```python >>> b = Buffer() >>> b.add(b"A" * 10) >>> b.add(b"B" * 10) >>> len(b) 20 >>> b.get(1) b'A' >>> len(b) 19 >>> b.get(9999) b'AAAAAAAAABBBBBBBBBB' >>> len(b) 0 >>> b.get(1) b'' ``` -------------------------------- ### Get absolute path of a remote file Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/filesystem.md Illustrates how to get the absolute path of a file on a remote system using the absolute() method of SSHPath, which respects the SSH connection's current working directory. ```python >>> f = SSHPath('absA/../absB/file', ssh=ssh_conn) >>> f.absolute().path '/.../absB/file' ``` -------------------------------- ### MIPS Linux Syscall Example 1 Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/mips.md Demonstrates calling the `execve` syscall with specific arguments. The arguments are prepared and then the syscall is invoked. ```python print(pwnlib.shellcraft.mips.linux.syscall('SYS_execve', 1, '$sp', 2, 0).rstrip()) ``` -------------------------------- ### RISCV64: Push null byte without terminator and get hex representation Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/riscv64.md Demonstrates pushing a single null byte without appending an additional terminator, and getting its hex representation. Useful for specific byte handling. ```python print(enhex(asm(shellcraft.riscv64.pushstr("\x00", append_null = False)))) 232c01fe130181ff ``` -------------------------------- ### Pwntools Readline Completers Example Source: https://github.com/gallopsled/pwntools/blob/dev/examples/README.md Demonstrates pwntools' readline implementation and various completers. This part of the library may undergo significant changes. ```python from pwn import * # Example of readline completers # def completer(text, state): # options = ['apple', 'banana', 'cherry'] # return options[state] # readline.set_completer(completer) # readline.parse_and_bind("tab: complete") # input('Enter fruit: ') ``` -------------------------------- ### SSH Download File Example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Illustrates downloading a file from a remote server via SSH and saving it locally. It also shows how to set the working directory on the remote host. ```python >>> with open('/tmp/foobar','w+') as f: ... _ = f.write('Hello, world') >>> s = ssh(host='example.pwnme', ... cache=False) >>> _ = s.set_working_directory(wd='/tmp') >>> _ = s.download_file('foobar', 'barfoo') >>> with open('barfoo','r') as f: ... print(f.read()) Hello, world ``` -------------------------------- ### Run pwntools Docker tests Source: https://github.com/gallopsled/pwntools/blob/dev/travis/docker/README.md Execute the make command to build the Docker image and run the doctest suite. Specify ANDROID=yes or ANDROID=no to control Android tests, and optionally set TARGET to a specific rst file. ```shell $ make -C travis/docker ANDROID=yes $ make -C travis/docker ANDROID=no TARGET=ssh.rst ``` -------------------------------- ### Demonstrate LD_PRELOAD Respect Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Copies libc, then debugs a process to verify that a specific version of libc (local-libc.so) is loaded via LD_PRELOAD. ```python io = process(["grep", "libc.so.6", "/proc/self/maps"]) real_libc_path = io.recvline().split()[-1] io.close() import shutil local_path = shutil.copy(real_libc_path, "./local-libc.so") # make a copy of libc to demonstrate that it is loaded io = gdb.debug(["grep", "local-libc.so", "/proc/self/maps"], gdbscript="continue", env={"LD_PRELOAD": "./local-libc.so"}) io.recvline().split()[-1] b'.../local-libc.so' io.close() os.remove("./local-libc.so") # cleanup ``` -------------------------------- ### arch Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Gets the CPU architecture of the remote machine. ```APIDOC ## arch ### Description Gets the CPU architecture of the remote machine. ### Property `arch` ### Type `str` ``` -------------------------------- ### pwn libcdb file usage Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/commandline.md Illustrates the command-line syntax for 'pwn libcdb file', which dumps information about a specified libc binary. ```console usage: pwn libcdb file [-h] [-s [symbols ...]] [-o offset] [--unstrip] files [files ...] ``` -------------------------------- ### _leak Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/memleak.md Leak `n` consecutive bytes starting at `addr`. ```APIDOC ## pwnlib.memleak.MemLeak._leak(addr, n, recurse=True) ### Description Leak `n` consecutive bytes starting at `addr`. ### Returns A string of length `n`, or `None`. ``` -------------------------------- ### Verify Entry Point Symbol Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/elf/elf.md Confirms that the '_start' symbol in an ELF binary corresponds to its entry point address. ```python >>> bash = ELF(which('bash')) >>> bash.symbols['_start'] == bash.entry True ``` -------------------------------- ### bits Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Gets the pointer size (in bits) of the remote machine. ```APIDOC ## bits ### Description Gets the pointer size (in bits) of the remote machine. ### Property `bits` ### Type `str` ``` -------------------------------- ### Create a listening socket and interact Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/sockets.md Sets up a listening socket on a specified port and allows interaction with a connecting client. Use for creating servers or services. ```python >>> l = listen(1234) >>> r = remote('localhost', l.lport) >>> _ = l.wait_for_connection() >>> l.sendline(b'Hello') >>> r.recvline() b'Hello\n' >>> l.close() >>> r.close() ``` -------------------------------- ### cwd Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/processes.md Gets or sets the current working directory of the process. ```APIDOC ## cwd ### Description Directory that the process is working in. ``` -------------------------------- ### pwnlib.gdb._gdbserver_args Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Sets up arguments for a listening `gdbserver`, either to connect to a specified PID or launch a specified binary. This function helps in configuring `gdbserver` for attaching to existing processes or starting new ones for debugging. ```APIDOC ## pwnlib.gdb._gdbserver_args(pid=None, path=None, args=None, which=None, env=None) -> list Sets up a listening gdbserver, to either connect to the specified PID, or launch the specified binary by its full path. * **Parameters:** * **pid** (*int*) – Process ID to attach to * **path** (*str*) – Process to launch * **port** (*int*) – Port to use for gdbserver, default: random * **gdbserver_args** (*list*) – List of additional arguments to pass to gdbserver * **args** (*list*) – List of arguments to provide on the debugger command line * **which** (*callable*) – Function to find the path of a binary. * **env** (*dict*) – Environment variables to pass to the program * **python_wrapper_script** (*str*) – Path to a python script to use with `--wrapper` * **Returns:** A list of arguments to invoke gdbserver. ``` -------------------------------- ### SSH Download Data Example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Demonstrates downloading data from a remote file using SSH. It shows how to handle cases where SFTP might be unavailable or has been reset. ```python >>> with open('/tmp/bar','w+') as f: ... _ = f.write('Hello, world') >>> s = ssh(host='example.pwnme', ... cache=False) >>> s.download_data('/tmp/bar') b'Hello, world' >>> s._sftp = None >>> s._tried_sftp = True >>> s.download_data('/tmp/bar') b'Hello, world' ``` -------------------------------- ### pwnlib.protocols.adb.proxy Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/protocols.md Starts an ADB proxy on the specified port for debugging purposes. ```APIDOC ## pwnlib.protocols.adb.proxy ### Description Starts an ADB proxy on the specified port for debugging purposes. ### Method POST (implied) ### Parameters #### Query Parameters - **port** (int) - Optional - The port to start the proxy on. Defaults to 9999. ``` -------------------------------- ### Set architecture to PowerPC (aliased) Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/context.md Demonstrates setting the architecture to 'ppc' and verifying it is aliased to 'powerpc'. ```python >>> context.arch = 'ppc' >>> context.arch == 'powerpc' # Aliased architecture True ``` -------------------------------- ### ARM Shellcraft: Execute a shell Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/arm.md Spawns a new shell process. This example demonstrates executing a shell and sending a command to it, then receiving the output. ```python >>> p = run_assembly(shellcraft.arm.linux.sh()) >>> p.sendline(b'echo Hello') >>> p.recv() b'Hello\n' ``` -------------------------------- ### distro Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/tubes/ssh.md Gets the Linux distribution name and release of the remote machine. ```APIDOC ## distro ### Description Gets the Linux distribution name and release of the remote machine. ### Property `distro` ### Type `tuple` ``` -------------------------------- ### Pwntools Version Display Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/commandline.md Displays the currently installed version of the pwntools library. ```console usage: pwn version [-h] ``` -------------------------------- ### Linux write example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/amd64.md Demonstrates writing data to a file descriptor in Linux using the 'write' syscall. The data and count are specified as arguments. ```python print(shellcraft.amd64.write(0, '*/', 2).rstrip()) ``` -------------------------------- ### Create shared library from assembly Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/asm.md Builds a shared library from assembly code. This example demonstrates creating a library that prints 'Hello' and then allows 'World' to be printed via LD_PRELOAD. ```pycon >>> context.clear() >>> context.arch = 'amd64' >>> sc = 'push rbp; mov rbp, rsp;' >>> sc += shellcraft.echo('Hello\n') >>> sc += 'mov rsp, rbp; pop rbp; ret' >>> solib = make_elf_from_assembly(sc, shared=1) >>> subprocess.check_output(['echo', 'World'], env={'LD_PRELOAD': solib}, universal_newlines = True) 'Hello\nWorld\n' ``` -------------------------------- ### Module-level doctest example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/testexample.md A basic module-level doctest demonstrating the 'add' function. ```pycon >>> add(3, add(2, add(1, 0))) 6 ``` -------------------------------- ### pwnlib.gdb.version Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Gets the current GDB version, requiring a specific format for compatibility. ```APIDOC ## pwnlib.gdb.version ### Description Gets the current GDB version. ### NOTE Requires that GDB version meets the following format: `GNU gdb (GDB) 7.12` ### Returns *tuple* – A tuple containing the version numbers ### Example ```pycon >>> (7,0) <= gdb.version() <= (19,0) True ``` ``` -------------------------------- ### AdbClient.list Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/protocols.md Executes the LIST command of the SYNC API to get a directory listing. ```APIDOC ## AdbClient.list ### Description Executes the LIST command of the SYNC API to get a directory listing. ### Method GET (implied) ### Parameters #### Query Parameters - **path** (str) - Required - Path of the directory to list. ### Response #### Success Response (200) - **directory_listing** (dict) - A dictionary where keys are filenames and values are file stat information. ``` -------------------------------- ### Handle missing binutils Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/asm.md Demonstrates the exception raised when the 'as' binutils utility is not found for a specific architecture context. It suggests installing binutils via apt-get. ```python >>> context.clear(arch = 'amd64') >>> pwnlib.asm.print_binutils_instructions('as', context) Traceback (most recent call last): ...PwnlibException: Could not find 'as' installed for ContextType(arch = 'amd64', bits = 64, endian = 'little') Try installing binutils for this architecture: $ sudo apt-get install binutils ``` -------------------------------- ### Get Android Build ID Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/adb.md Retrieves the Build ID of the Android device. ```python adb.build() ``` -------------------------------- ### Linux syscall example Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/shellcraft/amd64.md Demonstrates calling Linux syscalls with various arguments, including system call numbers, registers, and immediate values. Used for low-level system interactions. ```python print(pwnlib.shellcraft.amd64.linux.syscall('SYS_execve', 1, 'rsp', 2, 0).rstrip()) ``` ```python print(pwnlib.shellcraft.amd64.linux.syscall('SYS_execve', 2, 1, 0, -1).rstrip()) ``` ```python print(pwnlib.shellcraft.amd64.linux.syscall().rstrip()) ``` ```python print(pwnlib.shellcraft.amd64.linux.syscall('rax', 'rdi', 'rsi').rstrip()) ``` ```python print(pwnlib.shellcraft.amd64.linux.syscall('rbp', None, None, 1).rstrip()) ``` ```python print(pwnlib.shellcraft.amd64.linux.syscall( 'SYS_mmap', 0, 0x1000, 'PROT_READ | PROT_WRITE | PROT_EXEC', 'MAP_PRIVATE | MAP_ANONYMOUS', -1, 0).rstrip()) ``` -------------------------------- ### Check GDB Python version Source: https://github.com/gallopsled/pwntools/blob/dev/docs/source/gdb.md Verify the Python version used by your GDB installation. ```bash $ gdb -batch -ex "python import sys; print(sys.version)" ```