desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Sets a specific ``reg`` to a ``val``'
| def set_regvalue(self, reg, val):
| self[reg] = val
|
'Arguments:
elfs(list): List of :class:`.ELF` objects for mining'
| def __init__(self, elfs, base=None, **kwargs):
| import ropgadget
if isinstance(elfs, ELF):
elfs = [elfs]
elif isinstance(elfs, (str, unicode)):
elfs = [ELF(elfs)]
self.elfs = elfs
self._chain = []
self.base = base
self.migrated = False
self.__load()
|
'Returns an OrderedDict of addresses/values which will set the specified
register context.
Arguments:
registers(dict): Dictionary of ``{register name: value}``
Returns:
An OrderedDict of ``{register: sequence of gadgets, values, etc.}``.'
| def setRegisters(self, registers):
| reg_order = collections.OrderedDict()
for (reg, value) in registers.items():
gadget = self.find_gadget([('pop ' + reg), 'ret'])
if (not gadget):
log.error(("can't set %r" % reg))
reg_order[reg] = [gadget, value]
return reg_order
|
'Resolves a symbol to an address
Arguments:
resolvable(str,int): Thing to convert into an address
Returns:
int containing address of \'resolvable\', or None'
| def resolve(self, resolvable):
| if isinstance(resolvable, str):
for elf in self.elfs:
if (resolvable in elf.symbols):
return elf.symbols[resolvable]
if isinstance(resolvable, (int, long)):
return resolvable
|
'Inverts \'resolve\'. Given an address, it attempts to find a symbol
for it in the loaded ELF files. If none is found, it searches all
known gadgets, and returns the disassembly
Arguments:
value(int): Address to look up
Returns:
String containing the symbol name for the address, disassembly for a gadget
(if there\'s ... | def unresolve(self, value):
| for elf in self.elfs:
for (name, addr) in elf.symbols.items():
if (addr == value):
return name
if (value in self.gadgets):
return '; '.join(self.gadgets[value].insns)
return ''
|
'Generates padding to be inserted into the ROP stack.
>>> rop = ROP([])
>>> val = rop.generatePadding(5,15)
>>> cyclic_find(val[:4])
5
>>> len(val)
15
>>> rop.generatePadding(0,0)'
| def generatePadding(self, offset, count):
| if count:
return cyclic.cyclic((offset + count))[(- count):]
return ''
|
'Return a description for an object in the ROP stack'
| def describe(self, object):
| if isinstance(object, (int, long)):
return self.unresolve(object)
if isinstance(object, str):
return repr(object)
if isinstance(object, Call):
return str(object)
if isinstance(object, Gadget):
return '; '.join(object.insns)
|
'Construct the ROP chain into a list of elements which can be passed
to :func:`.flat`.
Arguments:
base(int):
The base address to build the rop-chain from. Defaults to
:attr:`base`.
description(dict):
Optional output argument, which will gets a mapping of
``address: description`` for each address on the stack,
starting ... | def build(self, base=None, description=None):
| if (base is None):
base = (self.base or 0)
stack = DescriptiveStack(base)
chain = self._chain
iterable = enumerate(chain)
for (idx, slot) in iterable:
remaining = ((len(chain) - 1) - idx)
address = stack.next
if isinstance(slot, (int, long)):
stack.describ... |
'Build the ROP chain
Returns:
str containing raw ROP bytes'
| def chain(self):
| return packing.flat(self.build())
|
'Dump the ROP chain in an easy-to-read manner'
| def dump(self):
| return self.build().dump()
|
'Add a call to the ROP chain
Arguments:
resolvable(str,int): Value which can be looked up via \'resolve\',
or is already an integer.
arguments(list): List of arguments which can be passed to pack().
Alternately, if a base address is set, arbitrarily nested
structures of strings or integers can be provided.'
| def call(self, resolvable, arguments=(), abi=None, **kwargs):
| if self.migrated:
log.error('Cannot append to a migrated chain')
if isinstance(resolvable, str):
addr = self.resolve(resolvable)
elif (hasattr(resolvable, 'name') and hasattr(resolvable, 'address')):
addr = resolvable.address
resolvable = str(resolvable.name)
... |
'Returns a gadget with the exact sequence of instructions specified
in the ``instructions`` argument.'
| def find_gadget(self, instructions):
| n = len(instructions)
for gadget in self.gadgets.values():
if (tuple(gadget.insns)[:n] == tuple(instructions)):
return gadget
|
'Adds a raw integer or string to the ROP chain.
If your architecture requires aligned values, then make
sure that any given string is aligned!
Arguments:
data(int/str): The raw value to put onto the rop chain.
>>> rop = ROP([])
>>> rop.raw(\'AAAAAAAA\')
>>> rop.raw(\'BBBBBBBB\')
>>> rop.raw(\'CCCCCCCC\')
>>> print rop.... | def raw(self, value):
| if self.migrated:
log.error('Cannot append to a migrated chain')
self._chain.append(value)
|
'Explicitly set $sp, by using a ``leave; ret`` gadget'
| def migrate(self, next_base):
| if isinstance(next_base, ROP):
next_base = self.base
pop_sp = (self.rsp or self.esp)
pop_bp = (self.rbp or self.ebp)
leave = self.leave
if (pop_sp and (len(pop_sp.regs) == 1)):
self.raw(pop_sp)
self.raw(next_base)
elif (pop_bp and leave and (len(pop_bp.regs) == 1)):
... |
'Returns: Raw bytes of the ROP chain'
| def __str__(self):
| return self.chain()
|
'Load all ROP gadgets for the selected ELF files'
| def __load(self):
| pop = re.compile('^pop (.{3})')
add = re.compile('^add .sp, (\\S+)$')
ret = re.compile('^ret$')
leave = re.compile('^leave$')
int80 = re.compile('int +0x80')
syscall = re.compile('^syscall$')
sysenter = re.compile('^sysenter$')
valid = (lambda insn: any(map((lambda pattern: p... |
'Iterate through all gadgets which move the stack pointer by
*at least* ``move`` bytes, and which allow you to set all
registers in ``regs``.'
| def search_iter(self, move=None, regs=None):
| move = (move or 0)
regs = set((regs or ()))
for (addr, gadget) in self.gadgets.items():
if (gadget.move < move):
continue
if (not (regs <= set(gadget.regs))):
continue
(yield gadget)
|
'Search for a gadget which matches the specified criteria.
Arguments:
move(int): Minimum number of bytes by which the stack
pointer is adjusted.
regs(list): Minimum list of registers which are popped off the
stack.
order(str): Either the string \'size\' or \'regs\'. Decides how to
order multiple gadgets the fulfill the... | def search(self, move=0, regs=None, order='size'):
| matches = self.search_iter(move, regs)
if (matches is None):
return None
key = {'size': (lambda g: (g.move, len(g.regs), g.address)), 'regs': (lambda g: (len(g.regs), g.move, g.address))}[order]
try:
result = min(matches, key=key)
except ValueError:
return None
if (move a... |
'Helper to make finding ROP gadets easier.
Also provides a shorthand for ``.call()``:
``rop.function(args)`` is equivalent to ``rop.call(function, args)``
>>> elf=ELF(which(\'bash\'))
>>> rop=ROP([elf])
>>> rop.rdi == rop.search(regs=[\'rdi\'], order = \'regs\')
True
>>> rop.r13_r14_r15_rbp == rop.search(regs=[\'r1... | def __getattr__(self, attr):
| gadget = collections.namedtuple('gadget', ['address', 'details'])
bad_attrs = ['trait_names', 'download', 'upload']
if ((attr in self.__dict__) or (attr in bad_attrs) or attr.startswith('_')):
raise AttributeError(('ROP instance has no attribute %r' % attr))
if attr.startswith('re... |
'Return a flat list of ``int`` or ``str`` objects which can be
passed to :func:`.flat`.
Arguments:
addr(int): Address at which the data starts in memory.
If :const:`None`, ``self.addr`` is used.'
| def resolve(self, addr=None):
| if (addr is None):
addr = self.address
with self.local(addr):
self.address = addr
rv = ([None] * len(self.values))
for (i, value) in enumerate(self.values):
if isinstance(value, int):
rv[i] = value
if isinstance(value, str):
... |
'eval(string) -> value
Evaluates a string in the context of values of this module.
Example:
>>> with context.local(arch = \'i386\', os = \'linux\'):
... print 13 == constants.eval(\'SYS_execve + PROT_WRITE\')
True
>>> with context.local(arch = \'amd64\', os = \'linux\'):
... print 61 == constants.eval(\'SYS_execv... | def eval(self, string):
| if (not isinstance(string, str)):
return string
simple = getattr(self, string, None)
if (simple is not None):
return simple
key = (context.os, context.arch)
if (key not in self._env_store):
self._env_store[key] = {key: getattr(self, key) for key in dir(self) if (not key.endsw... |
'Shellcode encoder class
Implements an architecture-specific shellcode encoder'
| def __init__(self):
| Encoder._encoders[self.arch].append(self)
|
'avoid(raw_bytes, avoid)
Arguments:
raw_bytes(str):
String of bytes to encode
avoid(set):
Set of bytes to avoid
pcreg(str):
Register which contains the address of the shellcode.
May be necessary for some shellcode.'
| def __call__(self, raw_bytes, avoid, pcreg):
| raise NotImplementedError()
|
'Returns the degree of the polynomial.
Examples:
>>> BitPolynom(0).degree()
0
>>> BitPolynom(1).degree()
0
>>> BitPolynom(2).degree()
1
>>> BitPolynom(7).degree()
2
>>> BitPolynom((1 << 10) - 1).degree()
9
>>> BitPolynom(1 << 10).degree()
10'
| def degree(self):
| return max(0, (int(self).bit_length() - 1))
|
'A generic CRC-sum function.
This is suitable to use with:
http://reveng.sourceforge.net/crc-catalogue/all.htm
The "check" value in the document is the CRC-sum of the string "123456789".
Arguments:
data(str): The data to calculate the CRC-sum of. This should either be a string or a list of bits.
polynom(int): The po... | @staticmethod
def generic_crc(data, polynom, width, init, refin, refout, xorout):
| polynom = (BitPolynom(int(polynom)) | (1 << width))
if (polynom.degree() != width):
raise ValueError('Polynomial is too large for that width')
init &= ((1 << width) - 1)
xorout &= ((1 << width) - 1)
if isinstance(data, list):
inlen = len(data)
p = BitPolynom... |
'cksum(data) -> int
Calculates the same checksum as returned by the UNIX-tool ``cksum``.
Arguments:
data(str): The data to checksum.
Example:
>>> print cksum(\'123456789\')
930766865'
| @staticmethod
def cksum(data):
| l = len(data)
data += packing.pack(l, 'all', endian='little', sign=False)
return crc.crc_32_posix(data)
|
'Finds all known CRC functions that hashes a piece of data into a specific
checksum. It does this by trying all known CRC functions one after the other.
Arguments:
data(str): Data for which the checksum is known.
Example:
>>> find_crc_function(\'test\', 46197)
[<function crc_crc_16_dnp at ...>]'
| @staticmethod
def find_crc_function(data, checksum):
| candidates = []
for v in known.all_crcs.keys():
func = getattr(crc, v)
if (func(data) == checksum):
candidates.append(func)
return candidates
|
'__call__(config) -> str
Check whether the configuration point is set correctly.
Arguments:
config(dict): Dictionary of all configuration points
Returns:
A tuple (result, message) where result is whether the
option is correctly configured, and message is an optional
message describing the error.'
| def __call__(self, config):
| if (not self.relevant(config)):
return (True, '')
return self.check(config.get(self.name, None))
|
':class:`str`: Alias for :attr:`.Mapping.name`'
| @property
def path(self):
| return self.name
|
':class:`int`: Alias for :data:`Mapping.start`.'
| @property
def address(self):
| return self.start
|
':class:`str`: Human-readable memory permission string, e.g. ``r-xp``.'
| @property
def permstr(self):
| flags = self.flags
return ''.join([('r' if (flags & 4) else '-'), ('w' if (flags & 2) else '-'), ('x' if (flags & 1) else '-'), 'p'])
|
':class:`str`: Memory of the mapping.'
| @property
def data(self):
| return self._core.read(self.start, self.size)
|
'Similar to str.find() but works on our address space'
| def find(self, sub, start=None, end=None):
| if (start is None):
start = self.start
if (end is None):
end = self.stop
result = self.data.find(sub, (start - self.address), (end - self.address))
if (result == (-1)):
return result
return (result + self.address)
|
'Similar to str.rfind() but works on our address space'
| def rfind(self, sub, start=None, end=None):
| if (start is None):
start = self.start
if (end is None):
end = self.stop
result = self.data.rfind(sub, (start - self.address), (end - self.address))
if (result == (-1)):
return result
return (result + self.address)
|
':class:`Mapping`: Mapping for the vvar section'
| @property
def vvar(self):
| for m in self.mappings:
if (m.name == '[vvar]'):
return m
|
':class:`Mapping`: Mapping for the vdso section'
| @property
def vdso(self):
| for m in self.mappings:
if (m.name == '[vdso]'):
return m
|
':class:`Mapping`: Mapping for the vsyscall section'
| @property
def vsyscall(self):
| for m in self.mappings:
if (m.name == '[vsyscall]'):
return m
|
':class:`Mapping`: First mapping for ``libc.so``'
| @property
def libc(self):
| expr = 'libc\\b.*so$'
for m in self.mappings:
if (not m.name):
continue
basename = os.path.basename(m.name)
if re.match(expr, basename):
return m
|
':class:`Mapping`: First mapping for the executable file.'
| @property
def exe(self):
| for m in self.mappings:
if (self.at_entry and (m.start <= self.at_entry <= m.stop)):
if ((not m.name) and self.at_execfn):
m.name = self.string(self.at_execfn)
return m
|
':class:`int`: PID of the process which created the core dump.'
| @property
def pid(self):
| if self.prstatus:
return int(self.prstatus.pr_pid)
|
':class:`int`: Parent PID of the process which created the core dump.'
| @property
def ppid(self):
| if self.prstatus:
return int(self.prstatus.pr_ppid)
|
':class:`int`: Signal which caused the core to be dumped.'
| @property
def signal(self):
| if self.siginfo:
return int(self.siginfo.si_signo)
if self.prstatus:
return int(self.prstatus.pr_cursig)
|
':class:`int`: Address which generated the fault, for the signals
SIGILL, SIGFPE, SIGSEGV, SIGBUS. This is only available in native
core dumps created by the kernel. If the information is unavailable,
this returns the address of the instruction pointer.'
| @property
def fault_addr(self):
| if self.siginfo:
return int(self.siginfo.sigfault_addr)
return getattr(self, 'pc', 0)
|
':class:`int`: The program counter for the Corefile
This is a cross-platform way to get e.g. ``core.eip``, ``core.rip``, etc.'
| @property
def pc(self):
| return self.registers.get(self._pc_register, None)
|
':class:`int`: The program counter for the Corefile
This is a cross-platform way to get e.g. ``core.esp``, ``core.rsp``, etc.'
| @property
def sp(self):
| return self.registers.get(self._sp_register, None)
|
':class:`str`: A printable string which is similar to /proc/xx/maps.
>>> print Corefile(\'./core\').maps
8048000-8049000 r-xp 1000 /home/user/pwntools/crash
8049000-804a000 r--p 1000 /home/user/pwntools/crash
804a000-804b000 rw-p 1000 /home/user/pwntools/crash
f7528000-f7529000 rw-p 1000 None
f7529000-f76d1000 r-xp 1a8... | @property
def maps(self):
| return '\n'.join(map(str, self.mappings))
|
'getenv(name) -> int
Read an environment variable off the stack, and return its contents.
Arguments:
name(str): Name of the environment variable to read.
Returns:
:class:`str`: The contents of the environment variable.'
| def getenv(self, name):
| if (name not in self.env):
log.error(('Environment variable %r not set' % name))
return self.string(self.env[name]).split('=', 1)[(-1)]
|
':class:`dict`: All available registers in the coredump.'
| @property
def registers(self):
| if (not self.prstatus):
return {}
rv = {}
for k in dir(self.prstatus.pr_reg):
if k.startswith('_'):
continue
try:
rv[k] = int(getattr(self.prstatus.pr_reg, k))
except Exception:
pass
return rv
|
'Open the corefile under a debugger.'
| def debug(self, *a, **kw):
| if (a or kw):
log.error(('Arguments are not supported for %s.debug()' % self.__class__.__name__))
import pwnlib.gdb
pwnlib.gdb.attach(self, exe=self.exe.path)
|
'Test whether a Corefile matches our process
Speculatively load a Corefile without informing the user, so that we
can check if it matches the process we\'re looking for.
Arguments:
path(str): Path to the corefile on disk
Returns:
`bool`: ``True`` if the Corefile matches, ``False`` otherwise.'
| def load_core_check_pid(self):
| try:
with context.quiet:
with tempfile.NamedTemporaryFile() as tmp:
tmp.write(self.read(self.core_path))
tmp.flush()
return Corefile(tmp.name).pid
except Exception:
pass
return (-1)
|
'Find the apport crash for the process, and extract the core file.
Arguments:
process(process): Process object we\'re looking for.
Returns:
`str`: Raw core file contents'
| def apport_corefile(self):
| crash_data = self.apport_read_crash_data()
log.debug(('Apport Crash Data:\n%s' % crash_data))
if crash_data:
return self.apport_crash_extract_corefile(crash_data)
|
'Extract a corefile from an apport crash file contents.
Arguments:
crashfile_data(str): Crash file contents
Returns:
`str`: Raw binary data for the core file, or ``None``.'
| def apport_crash_extract_corefile(self, crashfile_data):
| file = StringIO.StringIO(crashfile_data)
for line in file:
if line.startswith(' Pid:'):
pid = int(line.split()[(-1)])
if (pid == self.pid):
break
else:
return
for line in file:
if line.startswith('CoreDump: base64'):
break... |
'Find the apport crash for the process
Returns:
`str`: Raw contents of the crash file or ``None``.'
| def apport_read_crash_data(self):
| uid = self.uid
crash_name = self.exe.replace('/', '_')
crash_path = ('/var/crash/%s.%i.crash' % (crash_name, uid))
try:
log.debug(('Looking for Apport crash at %r' % crash_path))
data = self.read(crash_path)
except Exception:
return None
try:
self.u... |
'Find the corefile for a native crash.
Arguments:
process(process): Process whose crash we should find.'
| def native_corefile(self):
| if self.kernel_core_pattern.startswith('|'):
log.debug('Checking for corefile (piped)')
return self.native_corefile_pipe()
log.debug('Checking for corefile (pattern)')
return self.native_corefile_pattern()
|
'native_corefile_pipe(self) -> str'
| def native_corefile_pipe(self):
| if ('/apport' not in self.kernel_core_pattern):
log.warn_once(('Unsupported core_pattern: %r' % self.kernel_core_pattern))
return None
apport_core = self.apport_corefile()
if apport_core:
filename = ('core.%s.%i.apport' % (self.basename, self.pid))
with open(filename, '... |
'%% a single % character
%c core file size soft resource limit of crashing process (since Linux 2.6.24)
%d dump modeâsame as value returned by prctl(2) PR_GET_DUMPABLE (since Linux 3.7)
%e executable filename (without path prefix)
%E pathname of executable, with slashes (\'/\') replaced by exclamation marks (\'!... | def native_corefile_pattern(self):
| replace = {'%%': '%', '%e': self.basename, '%E': self.exe.replace('/', '!'), '%g': str(self.gid), '%h': socket.gethostname(), '%i': str(self.pid), '%I': str(self.pid), '%p': str(self.pid), '%P': str(self.pid), '%s': str((- self.process.poll())), '%u': str(self.uid)}
replace = dict(((re.escape(k), v) for (k, v) ... |
'qemu_corefile() -> str
Retrieves the path to a QEMU core dump.'
| def qemu_corefile(self):
| corefile_name = 'qemu_{basename}_*_{pid}.core'
corefile_name = corefile_name.format(basename=self.basename, pid=self.pid)
corefile_path = os.path.join(self.cwd, corefile_name)
log.debug(('Trying corefile_path: %r' % corefile_path))
for corefile in sorted(glob.glob(corefile_path), reverse=True)... |
'Parses /proc/sys/fs/binfmt_misc to find the interpreter for a file'
| def binfmt_lookup(self):
| binfmt_misc = '/proc/sys/fs/binfmt_misc'
if (not isinstance(self.process, process)):
log.debug('Not a process')
return ''
if self.process._qemu:
return self.process._qemu
if (not os.path.isdir(binfmt_misc)):
log.debug('No binfmt_misc dir')
return ''
... |
'from_assembly(assembly) -> ELF
Given an assembly listing, return a fully loaded ELF object
which contains that assembly at its entry point.
Arguments:
assembly(str): Assembly language listing
vma(int): Address of the entry point and the module\'s base address.
Example:
>>> e = ELF.from_assembly(\'nop; foo: int 0x80\',... | @staticmethod
@LocalContext
def from_assembly(assembly, *a, **kw):
| return ELF(make_elf_from_assembly(assembly, *a, **kw))
|
'from_bytes(bytes) -> ELF
Given a sequence of bytes, return a fully loaded ELF object
which contains those bytes at its entry point.
Arguments:
bytes(str): Shellcode byte string
vma(int): Desired base address for the ELF.
Example:
>>> e = ELF.from_bytes(\'\x90\xcd\x80\', vma=0xc000)
>>> print(e.disasm(e.entry, 3))
c000... | @staticmethod
@LocalContext
def from_bytes(bytes, *a, **kw):
| return ELF(make_elf(bytes, extract=False, *a, **kw))
|
'process(argv=[], *a, **kw) -> process
Execute the binary with :class:`.process`. Note that ``argv``
is a list of arguments, and should not include ``argv[0]``.
Arguments:
argv(list): List of arguments to the binary
*args: Extra arguments to :class:`.process`
**kwargs: Extra arguments to :class:`.process`
Returns:
:cl... | def process(self, argv=[], *a, **kw):
| p = process
if (context.os == 'android'):
p = adb.process
return p(([self.path] + argv), *a, **kw)
|
'debug(argv=[], *a, **kw) -> tube
Debug the ELF with :func:`.gdb.debug`.
Arguments:
argv(list): List of arguments to the binary
*args: Extra arguments to :func:`.gdb.debug`
**kwargs: Extra arguments to :func:`.gdb.debug`
Returns:
:class:`.tube`: See :func:`.gdb.debug`'
| def debug(self, argv=[], *a, **kw):
| import pwnlib.gdb
return pwnlib.gdb.debug(([self.path] + argv), *a, **kw)
|
':class:`int`: Address of the entry point for the ELF'
| @property
def entry(self):
| return (self.address + (self.header.e_entry - self.load_addr))
|
':class:`str`: ELF type (``EXEC``, ``DYN``, etc)'
| @property
def elftype(self):
| return describe_e_type(self.header.e_type).split()[0]
|
':class:`list`: A list of :class:`elftools.elf.segments.Segment` objects
for the segments in the ELF.'
| @property
def segments(self):
| return list(self.iter_segments())
|
'Yields:
Segments matching the specified type.'
| def iter_segments_by_type(self, t):
| for seg in self.iter_segments():
if ((t == seg.header.p_type) or (t in str(seg.header.p_type))):
(yield seg)
|
':class:`list`: A list of :class:`elftools.elf.sections.Section` objects
for the segments in the ELF.'
| @property
def sections(self):
| return list(self.iter_sections())
|
'DWARF info for the elf'
| @property
def dwarf(self):
| return self.get_dwarf_info()
|
':class:`dotdict`: Alias for :attr:`.ELF.symbols`'
| @property
def sym(self):
| return self.symbols
|
':class:`int`: Address of the lowest segment loaded in the ELF.
When updated, the addresses of the following fields are also updated:
- :attr:`~.ELF.symbols`
- :attr:`~.ELF.got`
- :attr:`~.ELF.plt`
- :attr:`~.ELF.functions`
However, the following fields are **NOT** updated:
- :attr:`~.ELF.segments`
- :attr:`~.ELF.secti... | @property
def address(self):
| return self._address
|
'section(name) -> bytes
Gets data for the named section
Arguments:
name(str): Name of the section
Returns:
:class:`str`: String containing the bytes for that section'
| def section(self, name):
| return self.get_section_by_name(name).data()
|
':class:`list`: List of all segments which are writeable and executable.
See:
:attr:`.ELF.segments`'
| @property
def rwx_segments(self):
| if (not self.nx):
return self.writable_segments
wx = (P_FLAGS.PF_X | P_FLAGS.PF_W)
return [s for s in self.segments if ((s.header.p_flags & wx) == wx)]
|
':class:`list`: List of all segments which are executable.
See:
:attr:`.ELF.segments`'
| @property
def executable_segments(self):
| if (not self.nx):
return list(self.segments)
return [s for s in self.segments if (s.header.p_flags & P_FLAGS.PF_X)]
|
':class:`list`: List of all segments which are writeable.
See:
:attr:`.ELF.segments`'
| @property
def writable_segments(self):
| return [s for s in self.segments if (s.header.p_flags & P_FLAGS.PF_W)]
|
':class:`list`: List of all segments which are NOT writeable.
See:
:attr:`.ELF.segments`'
| @property
def non_writable_segments(self):
| return [s for s in self.segments if (not (s.header.p_flags & P_FLAGS.PF_W))]
|
':class:`.ELF`: If this :class:`.ELF` imports any libraries which contain ``\'libc[.-]``,
and we can determine the appropriate path to it on the local
system, returns a new :class:`.ELF` object pertaining to that library.
If not found, the value will be :const:`None`.'
| @property
def libc(self):
| for lib in self.libs:
if (('/libc.' in lib) or ('/libc-' in lib)):
return ELF(lib)
|
'>>> from os.path import exists
>>> bash = ELF(which(\'bash\'))
>>> all(map(exists, bash.libs.keys()))
True
>>> any(map(lambda x: \'libc\' in x, bash.libs.keys()))
True'
| def _populate_libraries(self):
| if (not self.get_section_by_name('.dynamic')):
self.libs = {}
return
try:
cmd = ('ulimit -s unlimited; LD_TRACE_LOADED_OBJECTS=1 LD_WARN=1 LD_BIND_NOW=1 %s 2>/dev/null' % sh_string(self.path))
data = subprocess.check_output(cmd, shell=True, stderr=subprocess.... |
'Builds a dict of \'functions\' (i.e. symbols of type \'STT_FUNC\')
by function name that map to a tuple consisting of the func address and size
in bytes.'
| def _populate_functions(self):
| for sec in self.sections:
if (not isinstance(sec, SymbolTableSection)):
continue
for sym in sec.iter_symbols():
if self.functions.has_key(sym.name):
continue
if ((sym.entry.st_info['type'] == 'STT_FUNC') and (sym.entry.st_size != 0)):
... |
'>>> bash = ELF(which(\'bash\'))
>>> bash.symbols[\'_start\'] == bash.entry
True'
| def _populate_symbols(self):
| for section in self.sections:
if (not isinstance(section, SymbolTableSection)):
continue
for symbol in section.iter_symbols():
value = symbol.entry.st_value
if (not value):
continue
self.symbols[symbol.name] = value
|
'Adds symbols from the GOT and PLT to the symbols dictionary.
Does not overwrite any existing symbols, and prefers PLT symbols.
Synthetic plt.xxx and got.xxx symbols are added for each PLT and
GOT entry, respectively.
Example:bash.
>>> bash = ELF(which(\'bash\'))
>>> bash.symbols.wcscmp == bash.plt.wcscmp
True
>>> bash... | def _populate_synthetic_symbols(self):
| for (symbol, address) in self.plt.items():
self.symbols.setdefault(symbol, address)
self.symbols[('plt.' + symbol)] = address
for (symbol, address) in self.got.items():
self.symbols.setdefault(symbol, address)
self.symbols[('got.' + symbol)] = address
|
'Loads the symbols for all relocations'
| def _populate_got(self):
| if self.statically_linked:
return
for section in self.iter_sections():
if (not isinstance(section, RelocationSection)):
continue
if (section.header.sh_link == SHN_INDICES.SHN_UNDEF):
continue
symbols = self.get_section(section.header.sh_link)
for r... |
'Loads the PLT symbols
>>> path = pwnlib.data.elf.path
>>> for test in glob(os.path.join(path, \'test-*\')):
... test = ELF(test)
... assert \'__stack_chk_fail\' in test.got, test
... if test.arch != \'ppc\':
... assert \'__stack_chk_fail\' in test.plt, test'
| def _populate_plt(self):
| if self.statically_linked:
log.debug(('%r is statically linked, skipping GOT/PLT symbols' % self.path))
return
if (not self.got):
log.debug(("%r doesn't have any GOT symbols, skipping PLT" % self.path))
return
dt_pltgot = (self.dynamic_v... |
'search(needle, writable = False) -> generator
Search the ELF\'s virtual address space for the specified string.
Notes:
Does not search empty space between segments, or uninitialized
data. This will only return data that actually exists in the
ELF file. Searching for a long string of NULL bytes probably
won\'t work.
... | def search(self, needle, writable=False):
| load_address_fixup = (self.address - self.load_addr)
if writable:
segments = self.writable_segments
else:
segments = self.segments
for seg in segments:
addr = seg.header.p_vaddr
memsz = seg.header.p_memsz
zeroed = (memsz - seg.header.p_filesz)
offset = seg... |
'offset_to_vaddr(offset) -> int
Translates the specified offset to a virtual address.
Arguments:
offset(int): Offset to translate
Returns:
`int`: Virtual address which corresponds to the file offset, or
:const:`None`.
Examples:
This example shows that regardless of changes to the virtual
address layout by modifying :at... | def offset_to_vaddr(self, offset):
| load_address_fixup = (self.address - self.load_addr)
for segment in self.segments:
begin = segment.header.p_offset
size = segment.header.p_filesz
end = (begin + size)
if ((begin <= offset) and (offset <= end)):
delta = (offset - begin)
return ((segment.hea... |
'vaddr_to_offset(address) -> int
Translates the specified virtual address to a file offset
Arguments:
address(int): Virtual address to translate
Returns:
int: Offset within the ELF file which corresponds to the address,
or :const:`None`.
Examples:
>>> bash = ELF(which(\'bash\'))
>>> bash.vaddr_to_offset(bash.address)
0... | def vaddr_to_offset(self, address):
| for interval in self.memory[address]:
segment = interval.data
address = ((address - self.address) + self.load_addr)
offset = (address - segment.header.p_vaddr)
return (segment.header.p_offset + offset)
|
'read(address, count) -> bytes
Read data from the specified virtual address
Arguments:
address(int): Virtual address to read
count(int): Number of bytes to read
Returns:
A :class:`str` object, or :const:`None`.
Examples:
The simplest example is just to read the ELF header.
>>> bash = ELF(which(\'bash\'))
>>> bash.read(... | def read(self, address, count):
| retval = []
if (count == 0):
return ''
start = address
stop = (address + count)
overlap = self.memory.search(start, stop)
memory = intervaltree.IntervalTree(overlap)
memory.chop(None, start)
memory.chop(stop, None)
if (memory.begin() != start):
log.error(('Address ... |
'Writes data to the specified virtual address
Arguments:
address(int): Virtual address to write
data(str): Bytes to write
Note:
This routine does not check the bounds on the write to ensure
that it stays in the same segment.
Examples:
>>> bash = ELF(which(\'bash\'))
>>> bash.read(bash.address+1, 3)
\'ELF\'
>>> bash.wri... | def write(self, address, data):
| offset = self.vaddr_to_offset(address)
if (offset is not None):
length = len(data)
self.mmap[offset:(offset + length)] = data
return None
|
'Save the ELF to a file
>>> bash = ELF(which(\'bash\'))
>>> bash.save(\'/tmp/bash_copy\')
>>> copy = file(\'/tmp/bash_copy\')
>>> bash = file(which(\'bash\'))
>>> bash.read() == copy.read()
True'
| def save(self, path=None):
| if (path is None):
path = self.path
misc.write(path, self.data)
|
'get_data() -> bytes
Retrieve the raw data from the ELF file.
>>> bash = ELF(which(\'bash\'))
>>> fd = open(which(\'bash\'))
>>> bash.get_data() == fd.read()
True'
| def get_data(self):
| return self.mmap[:]
|
':class:`str`: Raw data of the ELF file.
See:
:meth:`get_data`'
| @property
def data(self):
| return self.mmap[:]
|
'disasm(address, n_bytes) -> str
Returns a string of disassembled instructions at
the specified virtual memory address'
| def disasm(self, address, n_bytes):
| arch = self.arch
if ((self.arch == 'arm') and (address & 1)):
arch = 'thumb'
address -= 1
return disasm(self.read(address, n_bytes), vma=address, arch=arch, endian=self.endian)
|
'asm(address, assembly)
Assembles the specified instructions and inserts them
into the ELF at the specified address.
This modifies the ELF in-pace.
The resulting binary can be saved with :meth:`.ELF.save`'
| def asm(self, address, assembly):
| binary = asm(assembly, vma=address)
self.write(address, binary)
|
'bss(offset=0) -> int
Returns:
Address of the ``.bss`` section, plus the specified offset.'
| def bss(self, offset=0):
| orig_bss = self.get_section_by_name('.bss').header.sh_addr
curr_bss = ((orig_bss - self.load_addr) + self.address)
return (curr_bss + offset)
|
'dynamic_by_tag(tag) -> tag
Arguments:
tag(str): Named ``DT_XXX`` tag (e.g. ``\'DT_STRTAB\'``).
Returns:
:class:`elftools.elf.dynamic.DynamicTag`'
| def dynamic_by_tag(self, tag):
| dt = None
dynamic = self.get_section_by_name('.dynamic')
if (not dynamic):
return None
try:
dt = next((t for t in dynamic.iter_tags() if (tag == t.entry.d_tag)))
except StopIteration:
pass
return dt
|
'dynamic_value_by_tag(tag) -> int
Retrieve the value from a dynamic tag a la ``DT_XXX``.
If the tag is missing, returns ``None``.'
| def dynamic_value_by_tag(self, tag):
| tag = self.dynamic_by_tag(tag)
if tag:
return tag.entry.d_val
|
'dynamic_string(offset) -> bytes
Fetches an enumerated string from the ``DT_STRTAB`` table.
Arguments:
offset(int): String index
Returns:
:class:`str`: String from the table as raw bytes.'
| def dynamic_string(self, offset):
| dt_strtab = self.dynamic_by_tag('DT_STRTAB')
if (not dt_strtab):
return None
address = (dt_strtab.entry.d_ptr + offset)
string = ''
while ('\x00' not in string):
string += self.read(address, 1)
address += 1
return string.rstrip('\x00')
|
':class:`bool`: Whether the current binary uses RELRO protections.
This requires both presence of the dynamic tag ``DT_BIND_NOW``, and
a ``GNU_RELRO`` program header.
The `ELF Specification`_ describes how the linker should resolve
symbols immediately, as soon as a binary is loaded. This can be
emulated with the ``LD_... | @property
def relro(self):
| if (not any((('GNU_RELRO' in str(s.header.p_type)) for s in self.segments))):
return None
if self.dynamic_by_tag('DT_BIND_NOW'):
return 'Full'
flags = self.dynamic_value_by_tag('DT_FLAGS')
if (flags and (flags & constants.DF_BIND_NOW)):
return 'Full'
flags_1 = self.dynamic_va... |
':class:`bool`: Whether the current binary uses NX protections.
Specifically, we are checking for ``READ_IMPLIES_EXEC`` being set
by the kernel, as a result of honoring ``PT_GNU_STACK`` in the kernel.
The **Linux kernel** directly honors ``PT_GNU_STACK`` to `mark the
stack as executable.`__
.. __: https://github.com/to... | @property
def nx(self):
| if (not self.executable):
return True
for seg in self.iter_segments_by_type('GNU_STACK'):
return (not bool((seg.header.p_flags & P_FLAGS.PF_X)))
return False
|
':class:`bool`: Whether the current binary uses an executable stack.
This is based on the presence of a program header PT_GNU_STACK_
being present, and its setting.
``PT_GNU_STACK``
The p_flags member specifies the permissions on the segment
containing the stack and is used to indicate wether the stack
should be execut... | @property
def execstack(self):
| if (not self.executable):
return False
if (not self.nx):
return True
for _ in self.iter_segments_by_type('GNU_STACK'):
break
else:
return (self.arch != 'aarch64')
return False
|
':class:`bool`: Whether the current binary uses stack canaries.'
| @property
def canary(self):
| return ('__stack_chk_fail' in (set(self.symbols) | set(self.got)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.