desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Finds a pointer to the stack via __environ, which is an exported symbol in libc, which points to the environment block.'
def stack(self):
symbols = ['environ', '_environ', '__environ'] for symbol in symbols: environ = self.lookup(symbol, 'libc') if environ: break else: log.error('Could not find the stack') stack = self.leak.p(environ) self.success(('*environ: %#x' % stack)) return...
'Finds the beginning of the heap via __curbrk, which is an exported symbol in the linker, which points to the current brk.'
def heap(self):
curbrk = self.lookup('__curbrk', 'libc') brk = self.leak.p(curbrk) self.success(('*curbrk: %#x' % brk)) return brk
'Implementation Details: This only works because the class is named ``Thread``. If its name is changed, we have to implement this hook differently.'
def __bootstrap(self):
context.update(**self.old) super(Thread, self).__bootstrap()
'Initialize the ContextType structure. All keyword arguments are passed to :func:`update`.'
def __init__(self, **kwargs):
self._tls = _Tls_DictStack(_defaultdict(ContextType.defaults)) self.update(**kwargs)
'copy() -> dict Returns a copy of the current context as a dictionary. Examples: >>> context.clear() >>> context.os = \'linux\' >>> vars(context) == {\'os\': \'linux\'} True'
def copy(self):
return self._tls.copy()
'Convenience function, which is shorthand for setting multiple variables at once. It is a simple shorthand such that:: context.update(os = \'linux\', arch = \'arm\', ...) is equivalent to:: context.os = \'linux\' context.arch = \'arm\' The following syntax is also valid:: context.update({\'os\': \'linux\', \'arch\': ...
def update(self, *args, **kwargs):
for arg in args: self.update(**arg) for (k, v) in kwargs.items(): setattr(self, k, v)
'local(**kwargs) -> context manager Create a context manager for use with the ``with`` statement. For more information, see the example below or PEP 343. Arguments: kwargs: Variables to be assigned in the new environment. Returns: ContextType manager for managing the old and new environment. Examples: >>> context.clear...
def local(self, function=None, **kwargs):
class LocalContext(object, ): def __enter__(a): self._tls.push() self.update(**{k: v for (k, v) in kwargs.items() if (v is not None)}) return self def __exit__(a, *b, **c): self._tls.pop() def __call__(self, function, *a, **kw): @fu...
'Disable all non-error logging within the enclosed scope.'
@property def silent(self, function=None):
return self.local(function, log_level='error')
'Disables all non-error logging within the enclosed scope, *unless* the debugging level is set to \'debug\' or lower.'
@property def quiet(self, function=None):
level = 'error' if (context.log_level <= logging.DEBUG): level = None return self.local(function, log_level=level)
'Similar to :attr:`quiet`, but wraps a whole function.'
def quietfunc(self, function):
@functools.wraps(function) def wrapper(*a, **kw): level = 'error' if (context.log_level <= logging.DEBUG): level = None with self.local(function, log_level=level): return function(*a, **kw) return wrapper
'Enable all logging within the enclosed scope.'
@property def verbose(self):
return self.local(log_level='debug')
'Clears the contents of the context. All values are set to their defaults. Arguments: a: Arguments passed to ``update`` kw: Arguments passed to ``update`` Examples: >>> # Default value >>> context.clear() >>> context.arch == \'i386\' True >>> context.arch = \'arm\' >>> context.arch == \'i386\' False >>> context.clear()...
def clear(self, *a, **kw):
self._tls._current.clear() if (a or kw): self.update(*a, **kw)
'Target binary architecture. Allowed values are listed in :attr:`pwnlib.context.ContextType.architectures`. Side Effects: If an architecture is specified which also implies additional attributes (e.g. \'amd64\' implies 64-bit words, \'powerpc\' implies big-endian), these attributes will be set on the context if a user ...
@_validator def arch(self, arch):
arch = arch.lower() transform = [('ppc64', 'powerpc64'), ('ppc', 'powerpc'), ('x86_64', 'amd64'), ('x86', 'i386'), ('i686', 'i386'), ('armeabi', 'arm'), ('arm64', 'aarch64')] for (k, v) in transform: if arch.startswith(k): arch = v break try: defaults = ContextTyp...
'ASLR settings for new processes. If :const:`False`, attempt to disable ASLR in all processes which are created via ``personality`` (``setarch -R``) and ``setrlimit`` (``ulimit -s unlimited``). The ``setarch`` changes are lost if a ``setuid`` binary is executed.'
@_validator def aslr(self, aslr):
return bool(aslr)
'Target machine\'s kernel architecture. Usually, this is the same as ``arch``, except when running a 32-bit binary on a 64-bit kernel (e.g. i386-on-amd64). Even then, this doesn\'t matter much -- only when the the segment registers need to be known'
@_validator def kernel(self, arch):
with context.local(arch=arch): return context.arch
'Target machine word size, in bits (i.e. the size of general purpose registers). The default value is ``32``, but changes according to :attr:`arch`. Examples: >>> context.clear() >>> context.bits == 32 True >>> context.bits = 64 >>> context.bits == 64 True >>> context.bits = -1 #doctest: +ELLIPSIS Traceback (most recen...
@_validator def bits(self, bits):
bits = int(bits) if (bits <= 0): raise AttributeError(('bits must be > 0 (%r)' % bits)) return bits
'Infer target architecture, bit-with, and endianness from a binary file. Data type is a :class:`pwnlib.elf.ELF` object. Examples: >>> context.clear() >>> context.arch, context.bits (\'i386\', 32) >>> context.binary = \'/bin/bash\' >>> context.arch, context.bits (\'amd64\', 64) >>> context.binary ELF(\'/bin/bash\')'
@_validator def binary(self, binary):
from pwnlib.elf import ELF if (not isinstance(binary, ELF)): binary = ELF(binary) self.arch = binary.arch self.bits = binary.bits self.endian = binary.endian return binary
'Target machine word size, in bytes (i.e. the size of general purpose registers). This is a convenience wrapper around ``bits / 8``. Examples: >>> context.bytes = 1 >>> context.bits == 8 True >>> context.bytes = 0 #doctest: +ELLIPSIS Traceback (most recent call last): AttributeError: bits must be > 0 (0)'
@property def bytes(self):
return (self.bits / 8)
'Endianness of the target machine. The default value is ``\'little\'``, but changes according to :attr:`arch`. Raises: AttributeError: An invalid endianness was provided Examples: >>> context.clear() >>> context.endian == \'little\' True >>> context.endian = \'big\' >>> context.endian \'big\' >>> context.endian = \'be\...
@_validator def endian(self, endianness):
endian = endianness.lower() if (endian not in ContextType.endiannesses): raise AttributeError(('endian must be one of %r' % sorted(ContextType.endiannesses))) return ContextType.endiannesses[endian]
'Sets the verbosity of ``pwntools`` logging mechanism. More specifically it controls the filtering of messages that happens inside the handler for logging to the screen. So if you want e.g. log all messages to a file, then this attribute makes no difference to you. Valid values are specified by the standard Python ``lo...
@_validator def log_level(self, value):
try: return int(value) except ValueError: pass try: return getattr(logging, value.upper()) except AttributeError: pass level_names = filter((lambda x: isinstance(x, str)), logging._levelNames) permitted = sorted(level_names) raise AttributeError(('log_level ...
'Sets the target file for all logging output. Works in a similar fashion to :attr:`log_level`. Examples: >>> context.log_file = \'foo.txt\' #doctest: +ELLIPSIS >>> log.debug(\'Hello!\') #doctest: +ELLIPSIS >>> with context.local(log_level=\'ERROR\'): #doctest: +ELLIPSIS ... log.info(\'Hello again!\') >>> with conte...
@_validator def log_file(self, value):
if isinstance(value, (str, unicode)): modes = ('w', 'wb', 'a', 'ab') if (',' not in value): value += ',a' (filename, mode) = value.rsplit(',', 1) value = open(filename, mode) elif (not isinstance(value, file)): raise AttributeError('log_file must be a...
'Sets the default logging console target. Examples: >>> context.log_level = \'warn\' >>> log.warn("Hello") [!] Hello >>> context.log_console=open(\'/dev/null\', \'w\') >>> log.warn("Hello") >>> context.clear()'
@_validator def log_console(self, stream):
if isinstance(stream, str): stream = open(stream, 'wt') return stream
'Operating system of the target machine. The default value is ``linux``. Allowed values are listed in :attr:`pwnlib.context.ContextType.oses`. Examples: >>> context.os = \'linux\' >>> context.os = \'foobar\' #doctest: +ELLIPSIS Traceback (most recent call last): AttributeError: os must be one of [\'android\', \'cgc\', ...
@_validator def os(self, os):
os = os.lower() if (os not in ContextType.oses): raise AttributeError(('os must be one of %r' % ContextType.oses)) return os
'Global flag that lots of things should be randomized.'
@_validator def randomize(self, r):
return bool(r)
'Signed-ness for packing operation when it\'s not explicitly set. Can be set to any non-string truthy value, or the specific string values ``\'signed\'`` or ``\'unsigned\'`` which are converted into :const:`True` and :const:`False` correspondingly. Examples: >>> context.signed False >>> context.signed = 1 >>> context.s...
@_validator def signed(self, signed):
try: signed = ContextType.signednesses[signed] except KeyError: pass if isinstance(signed, str): raise AttributeError(('signed must be one of %r or a non-string truthy value' % sorted(ContextType.signednesses))) return bool(signed)
'Default amount of time to wait for a blocking operation before it times out, specified in seconds. The default value is to have an infinite timeout. See :class:`pwnlib.timeout.Timeout` for additional information on valid values.'
@_validator def timeout(self, value=Timeout.default):
return Timeout(value).timeout
'Default terminal used by :meth:`pwnlib.util.misc.run_in_new_terminal`. Can be a string or an iterable of strings. In the latter case the first entry is the terminal and the rest are default arguments.'
@_validator def terminal(self, value):
if isinstance(value, (str, unicode)): return [value] return value
'Default proxy for all socket connections. Accepts either a string (hostname or IP address) for a SOCKS5 proxy on the default port, **or** a ``tuple`` passed to ``socks.set_default_proxy``, e.g. ``(socks.SOCKS4, \'localhost\', 1234)``. >>> context.proxy = \'localhost\' #doctest: +ELLIPSIS >>> r=remote(\'google.com\', 8...
@_validator def proxy(self, proxy):
if (not proxy): socket.socket = _original_socket return None if isinstance(proxy, str): proxy = (socks.SOCKS5, proxy) if (not isinstance(proxy, collections.Iterable)): raise AttributeError('proxy must be a string hostname, or tuple of arguments f...
'Disable all actions which rely on ptrace. This is useful for switching between local exploitation with a debugger, and remote exploitation (without a debugger). This option can be set with the ``NOPTRACE`` command-line argument.'
@_validator def noptrace(self, value):
return bool(value)
'Sets the target host which is used for ADB. This is useful for Android exploitation. The default value is inherited from ANDROID_ADB_SERVER_HOST, or set to the default \'localhost\'.'
@_validator def adb_host(self, value):
return str(value)
'Sets the target port which is used for ADB. This is useful for Android exploitation. The default value is inherited from ANDROID_ADB_SERVER_PORT, or set to the default 5037.'
@_validator def adb_port(self, value):
return int(value)
'Sets the device being operated on.'
@_validator def device(self, device):
if isinstance(device, Device): self.arch = (device.arch or self.arch) self.bits = (device.bits or self.bits) self.endian = (device.endian or self.endian) self.os = (device.os or self.os) elif isinstance(device, str): device = Device(device) elif (device is not None): ...
'Returns an argument array for connecting to adb. Unless ``$ADB_PATH`` is set, uses the default ``adb`` binary in ``$PATH``.'
@property def adb(self):
ADB_PATH = os.environ.get('ADB_PATH', 'adb') command = [ADB_PATH] if (self.adb_host != self.defaults['adb_host']): command += ['-H', self.adb_host] if (self.adb_port != self.defaults['adb_port']): command += ['-P', str(self.adb_port)] if self.device: command += ['-s', str(sel...
'Internal buffer size to use for :class:`pwnlib.tubes.tube.tube` objects. This is not the maximum size of the buffer, but this is the amount of data which is passed to each raw ``read`` syscall (or equivalent).'
@_validator def buffer_size(self, size):
return int(size)
'Directory used for caching data. Note: May be either a path string, or :const:`None`. Example: >>> cache_dir = context.cache_dir >>> cache_dir is not None True >>> os.chmod(cache_dir, 0o000) >>> context.cache_dir is None True >>> os.chmod(cache_dir, 0o755) >>> cache_dir == context.cache_dir True'
@property def cache_dir(self):
home = os.path.expanduser('~') if (not os.access(home, os.W_OK)): return None cache = os.path.join(home, '.pwntools-cache') if (not os.path.exists(cache)): try: os.mkdir(cache) except OSError: return None if (not os.access(cache, os.W_OK)): ret...
'Whether pwntools automatically deletes corefiles after exiting. This only affects corefiles accessed via :attr:`.process.corefile`. Default value is ``False``.'
@_validator def delete_corefiles(self, v):
return bool(v)
'Whether pwntools automatically renames corefiles. This is useful for two things: - Prevent corefiles from being overwritten, if ``kernel.core_pattern`` is something simple like ``"core"``. - Ensure corefiles are generated, if ``kernel.core_pattern`` uses ``apport``, which refuses to overwrite any existing files. This ...
@_validator def rename_corefiles(self, v):
return bool(v)
'Alias for :meth:`pwnlib.context.ContextType.update`'
def __call__(self, **kwargs):
return self.update(**kwargs)
'Deprecated. Use :meth:`clear`.'
def reset_local(self):
self.clear()
'Legacy alias for :attr:`endian`. Examples: >>> context.endian == context.endianness True'
@property def endianness(self):
return self.endian
'Alias for :attr:`signed`'
@property def sign(self):
return self.signed
'Alias for :attr:`signed`'
@property def signedness(self):
return self.signed
'Alias for :attr:`bits`'
@property def word_size(self):
return self.bits
'Instantiates an object which try to automating exploit the vulnerable process Arguments: execute_fmt(function): function to call for communicate with the vulnerable process offset(int): the first formatter\'s offset you control padlen(int): size of the pad you want to add before the payload numbwritten(int): number of...
def __init__(self, execute_fmt, offset=None, padlen=0, numbwritten=0):
self.execute_fmt = execute_fmt self.offset = offset self.padlen = padlen self.numbwritten = numbwritten if (self.offset == None): (self.offset, self.padlen) = self.find_offset() log.info('Found format string offset: %d', self.offset) self.writes = {} self.leaker =...
'execute_writes() -> None Makes payload and send it to the vulnerable process Returns: None'
def execute_writes(self):
fmtstr = randoms(self.padlen) fmtstr += fmtstr_payload(self.offset, self.writes, numbwritten=self.padlen, write_size='byte') self.execute_fmt(fmtstr) self.writes = {}
'write(addr, data) -> None In order to tell : I want to write ``data`` at ``addr``. Arguments: addr(int): the address where you want to write data(int): the data that you want to write ``addr`` Returns: None Examples: >>> def send_fmt_payload(payload): ... print repr(payload) >>> f = FmtStr(send_fmt_payload, offset...
def write(self, addr, data):
self.writes[addr] = data
'Routine executed in the child process before invoking execve(). Handles setting the controlling TTY as well as invoking the user- supplied preexec_fn.'
def __preexec_fn(self):
if (self.pty is not None): self.__pty_make_controlling_tty(self.pty) if (not self.aslr): try: if ((context.os == 'linux') and (self._setuid is not True)): ADDR_NO_RANDOMIZE = 262144 ctypes.CDLL('libc.so.6').personality(ADDR_NO_RANDOMIZE) re...
'We received an \'exec format\' error (ENOEXEC) This implies that the user tried to execute e.g. an ARM binary on a non-ARM system, and does not have binfmt helpers installed for QEMU.'
def __on_enoexec(self, exception):
with context.quiet: from pwnlib.elf import ELF binary = ELF(self.executable) qemu = get_qemu_user(arch=binary.arch) if (not qemu): raise exception qemu = which(qemu) if qemu: self._qemu = qemu args = [qemu] if self.argv: args += ['-0', self...
'Alias for ``executable``, for backward compatibility. Example: >>> p = process(\'true\') >>> p.executable == \'/bin/true\' True >>> p.executable == p.program True'
@property def program(self):
return self.executable
'Directory that the process is working in. Example: >>> p = process(\'sh\') >>> p.sendline(\'cd /tmp; echo AAA\') >>> _ = p.recvuntil(\'AAA\') >>> p.cwd == \'/tmp\' True >>> p.sendline(\'cd /proc; echo BBB;\') >>> _ = p.recvuntil(\'BBB\') >>> p.cwd \'/proc\''
@property def cwd(self):
try: self._cwd = os.readlink(('/proc/%i/cwd' % self.pid)) except Exception: pass return self._cwd
'Perform extended validation on the executable path, argv, and envp. Mostly to make Python happy, but also to prevent common pitfalls.'
def _validate(self, cwd, executable, argv, env):
cwd = (cwd or os.path.curdir) if isinstance(argv, (str, unicode)): argv = [argv] if (not all((isinstance(arg, (str, unicode)) for arg in argv))): self.error(('argv must be strings: %r' % argv)) argv = list((argv or [])) for (i, arg) in enumerate(argv): if ('\x00' ...
'Permit pass-through access to the underlying process object for fields like ``pid`` and ``stdin``.'
def __getattr__(self, attr):
if hasattr(self.proc, attr): return getattr(self.proc, attr) raise AttributeError(("'process' object has no attribute '%s'" % attr))
'kill() Kills the process.'
def kill(self):
self.close()
'poll(block = False) -> int Arguments: block(bool): Wait for the process to exit Poll the exit code of the process. Will return None, if the process has not yet finished and the exit code otherwise.'
def poll(self, block=False):
_ = self.cwd if block: self.wait_for_close() self.proc.poll() returncode = self.proc.returncode if ((returncode != None) and (not self._stop_noticed)): self._stop_noticed = time.time() signame = '' if (returncode < 0): signame = (' (%s)' % signal_names....
'communicate(stdin = None) -> str Calls :meth:`subprocess.Popen.communicate` method on the process.'
def communicate(self, stdin=None):
return self.proc.communicate(stdin)
'This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris.'
def __pty_make_controlling_tty(self, tty_fd):
child_name = os.ttyname(tty_fd) try: fd = os.open('/dev/tty', (os.O_RDWR | os.O_NOCTTY)) if (fd >= 0): os.close(fd) except OSError: pass os.setsid() try: fd = os.open('/dev/tty', (os.O_RDWR | os.O_NOCTTY)) if (fd >= 0): os.close(fd) ...
'libs() -> dict Return a dictionary mapping the path of each shared library loaded by the process to the address it is loaded at in the process\' address space. If ``/proc/$PID/maps`` for the process cannot be accessed, the output of ``ldd`` alone is used. This may give inaccurate results if ASLR is enabled.'
def libs(self):
with context.local(log_level='error'): ldd = process(['ldd', self.executable]).recvall() maps = parse_ldd_output(ldd) try: maps_raw = open(('/proc/%d/maps' % self.pid)).read() except IOError: return maps for line in maps_raw.splitlines(): if ('/' not in line): ...
'libc() -> ELF Returns an ELF for the libc for the current process. If possible, it is adjusted to the correct address automatically.'
@property def libc(self):
from pwnlib.elf import ELF for (lib, address) in self.libs().items(): if ('libc.so' in lib): e = ELF(lib) e.address = address return e
'elf() -> pwnlib.elf.elf.ELF Returns an ELF file for the executable that launched the process.'
@property def elf(self):
import pwnlib.elf.elf return pwnlib.elf.elf.ELF(self.executable)
'corefile() -> pwnlib.elf.elf.Core Returns a corefile for the process. If the process is alive, attempts to create a coredump with GDB. If the process is dead, attempts to locate the coredump created by the kernel.'
@property def corefile(self):
import pwnlib.elf.corefile import pwnlib.gdb if (self.poll() is None): return pwnlib.gdb.corefile(self) finder = pwnlib.elf.corefile.CorefileFinder(self) if (not finder.core_path): self.warn(('Could not find core file for pid %i' % self.pid)) return c...
'Leaks memory within the process at the specified address. Arguments: address(int): Address to leak memory at count(int): Number of bytes to leak at that address. Example: >>> e = ELF(\'/bin/sh\') >>> p = process(e.path) In order to make sure there\'s not a race condition against the process getting set up... >>> p.sen...
def leak(self, address, count=1):
if ('qemu-' in os.path.realpath(('/proc/%i/exe' % self.pid))): self.error('Cannot use leaker on binaries under QEMU.') with open(('/proc/%i/mem' % self.pid), 'rb') as mem: mem.seek(address) return (mem.read(count) or None)
'Helper method to wrap a standard python socket.socket with the tube APIs. Arguments: socket: Instance of socket.socket Returns: Instance of pwnlib.tubes.remote.remote.'
@classmethod def fromsocket(cls, socket):
s = socket (host, port) = s.getpeername() return remote(host, port, fam=s.family, typ=s.type, sock=s)
'recv(numb = 4096, timeout = default) -> str Receives up to `numb` bytes of data from the tube, and returns as soon as any quantity of data is available. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. Raises: exceptions.EOFError: The con...
def recv(self, numb=None, timeout=default):
numb = self.buffer.get_fill_size(numb) return (self._recv(numb, timeout) or '')
'unrecv(data) Puts the specified data back at the beginning of the receive buffer. Examples: >>> t = tube() >>> t.recv_raw = lambda n: \'hello\' >>> t.recv() \'hello\' >>> t.recv() \'hello\' >>> t.unrecv(\'world\') >>> t.recv() \'world\' >>> t.recv() \'hello\''
def unrecv(self, data):
self.buffer.unget(data)
'_fillbuffer(timeout = default) Fills the internal buffer from the pipe, by calling :meth:`recv_raw` exactly once. Returns: The bytes of data received, or ``\'\'`` if no data was received. Examples: >>> t = tube() >>> t.recv_raw = lambda *a: \'abc\' >>> len(t.buffer) 0 >>> t._fillbuffer() \'abc\' >>> len(t.buffer) 3'
def _fillbuffer(self, timeout=default):
data = '' with self.local(timeout): data = self.recv_raw(self.buffer.get_fill_size()) if (data and self.isEnabledFor(logging.DEBUG)): self.debug(('Received %#x bytes:' % len(data))) if ((len(set(data)) == 1) and (len(data) > 1)): self.indented(('%r * %#x' % (d...
'_recv(numb = 4096, timeout = default) -> str Receives one chunk of from the internal buffer or from the OS if the buffer is empty.'
def _recv(self, numb=None, timeout=default):
numb = self.buffer.get_fill_size(numb) data = '' if ((not self.buffer) and (not self._fillbuffer(timeout))): return '' return self.buffer.get(numb)
'recvpred(pred, timeout = default) -> str Receives one byte at a time from the tube, until ``pred(bytes)`` evaluates to True. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. Arguments: pred(callable): Function to call, with the currently-...
def recvpred(self, pred, timeout=default):
data = '' with self.countdown(timeout): while (not pred(data)): try: res = self.recv(1) except Exception: self.unrecv(data) return '' if res: data += res else: self.unrecv(data...
'recvn(numb, timeout = default) -> str Receives exactly `n` bytes. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. Raises: exceptions.EOFError: The connection closed before the request could be satisfied Returns: A string containing bytes...
def recvn(self, numb, timeout=default):
with self.countdown(timeout): while (self.countdown_active() and (len(self.buffer) < numb) and self._fillbuffer(self.timeout)): pass if (len(self.buffer) < numb): return '' return self.buffer.get(numb)
'recvuntil(delims, timeout = default) -> str Receive data until one of `delims` is encountered. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. arguments: delims(str,tuple): String of delimiters characters, or list of delimiter strings. d...
def recvuntil(self, delims, drop=False, timeout=default):
if isinstance(delims, (str, unicode)): delims = (delims,) longest = max(map(len, delims)) data = [] top = '' with self.countdown(timeout): while self.countdown_active(): try: res = self.recv(timeout=self.timeout) except Exception: ...
'recvlines(numlines, keepends = False, timeout = default) -> str list Receive up to ``numlines`` lines. A "line" is any sequence of bytes terminated by the byte sequence set by :attr:`newline`, which defaults to ``\'\n\'``. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an emp...
def recvlines(self, numlines=(2 ** 20), keepends=False, timeout=default):
lines = [] with self.countdown(timeout): for _ in xrange(numlines): try: res = self.recvline(keepends=True, timeout=timeout) except Exception: self.unrecv(''.join(lines)) raise if res: lines.append(res) ...
'recvline(keepends = True) -> str Receive a single line from the tube. A "line" is any sequence of bytes terminated by the byte sequence set in :attr:`newline`, which defaults to ``\'\n\'``. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned....
def recvline(self, keepends=True, timeout=default):
return self.recvuntil(self.newline, drop=(not keepends), timeout=timeout)
'recvline_pred(pred, keepends = False) -> str Receive data until ``pred(line)`` returns a truthy value. Drop all other data. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. Arguments: pred(callable): Function to call. Returns the line fo...
def recvline_pred(self, pred, keepends=False, timeout=default):
tmpbuf = Buffer() line = '' with self.countdown(timeout): while self.countdown_active(): try: line = self.recvline(keepends=True) except Exception: self.buffer.add(tmpbuf) raise if (not line): self.bu...
'Receive lines until one line is found which contains at least one of `items`. Arguments: items(str,tuple): List of strings to search for, or a single string. keepends(bool): Return lines with newlines if :const:`True` timeout(int): Timeout, in seconds Examples: >>> t = tube() >>> t.recv_raw = lambda n: "Hello\nWorld\n...
def recvline_contains(self, items, keepends=False, timeout=default):
if isinstance(items, (str, unicode)): items = (items,) def pred(line): return any(((d in line) for d in items)) return self.recvline_pred(pred, keepends, timeout)
'recvline_startswith(delims, keepends = False, timeout = default) -> str Keep receiving lines until one is found that starts with one of `delims`. Returns the last line received. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. Arguments:...
def recvline_startswith(self, delims, keepends=False, timeout=default):
if isinstance(delims, (str, unicode)): delims = (delims,) return self.recvline_pred((lambda line: any(map(line.startswith, delims))), keepends=keepends, timeout=timeout)
'recvline_endswith(delims, keepends = False, timeout = default) -> str Keep receiving lines until one is found that starts with one of `delims`. Returns the last line received. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``\'\'``) is returned. See :meth:`r...
def recvline_endswith(self, delims, keepends=False, timeout=default):
if isinstance(delims, (str, unicode)): delims = (delims,) delims = tuple(((delim + self.newline) for delim in delims)) return self.recvline_pred((lambda line: any(map(line.endswith, delims))), keepends=keepends, timeout=timeout)
'recvregex(regex, exact = False, timeout = default) -> str Wrapper around :func:`recvpred`, which will return when a regex matches the string in the buffer. By default :func:`re.RegexObject.search` is used, but if `exact` is set to True, then :func:`re.RegexObject.match` will be used instead. If the request is not sati...
def recvregex(self, regex, exact=False, timeout=default):
if isinstance(regex, (str, unicode)): regex = re.compile(regex) if exact: pred = regex.match else: pred = regex.search return self.recvpred(pred, timeout=timeout)
'recvregex(regex, exact = False, keepends = False, timeout = default) -> str Wrapper around :func:`recvline_pred`, which will return when a regex matches a line. By default :func:`re.RegexObject.search` is used, but if `exact` is set to True, then :func:`re.RegexObject.match` will be used instead. If the request is not...
def recvline_regex(self, regex, exact=False, keepends=False, timeout=default):
if isinstance(regex, (str, unicode)): regex = re.compile(regex) if exact: pred = regex.match else: pred = regex.search return self.recvline_pred(pred, keepends=keepends, timeout=timeout)
'recvrepeat(timeout = default) -> str Receives data until a timeout or EOF is reached. Examples: >>> data = [ ... \'d\', ... \'\', # simulate timeout ... \'c\', ... \'b\', ... \'a\', >>> def delayrecv(n, data=data): ... return data.pop() >>> t = tube() >>> t.recv_raw = delayrecv >>> t.recvrepeat(0.2) \'abc\' >>> t....
def recvrepeat(self, timeout=default):
try: while self._fillbuffer(timeout=timeout): pass except EOFError: pass return self.buffer.get()
'recvall() -> str Receives data until EOF is reached.'
def recvall(self, timeout=Timeout.forever):
with self.waitfor('Receiving all data') as h: l = len(self.buffer) with self.local(timeout): try: while True: l = misc.size(len(self.buffer)) h.status(l) if (not self._fillbuffer()): ...
'send(data) Sends data. If log level ``DEBUG`` is enabled, also prints out the data received. If it is not possible to send anymore because of a closed connection, it raises ``exceptions.EOFError`` Examples: >>> def p(x): print repr(x) >>> t = tube() >>> t.send_raw = p >>> t.send(\'hello\') \'hello\''
def send(self, data):
if self.isEnabledFor(logging.DEBUG): self.debug(('Sent %#x bytes:' % len(data))) if (len(set(data)) == 1): self.indented(('%r * %#x' % (data[0], len(data)))) elif all(((c in string.printable) for c in data)): for line in data.splitlines(True): ...
'sendline(data) Shorthand for ``t.send(data + t.newline)``. Examples: >>> def p(x): print repr(x) >>> t = tube() >>> t.send_raw = p >>> t.sendline(\'hello\') \'hello\n\' >>> t.newline = \'\r\n\' >>> t.sendline(\'hello\') \'hello\r\n\''
def sendline(self, line=''):
self.send((line + self.newline))
'sendafter(delim, data, timeout = default) -> str A combination of ``recvuntil(delim, timeout)`` and ``send(data)``.'
def sendafter(self, delim, data, timeout=default):
res = self.recvuntil(delim, timeout) self.send(data) return res
'sendlineafter(delim, data, timeout = default) -> str A combination of ``recvuntil(delim, timeout)`` and ``sendline(data)``.'
def sendlineafter(self, delim, data, timeout=default):
res = self.recvuntil(delim, timeout) self.sendline(data) return res
'sendthen(delim, data, timeout = default) -> str A combination of ``send(data)`` and ``recvuntil(delim, timeout)``.'
def sendthen(self, delim, data, timeout=default):
self.send(data) return self.recvuntil(delim, timeout)
'sendlinethen(delim, data, timeout = default) -> str A combination of ``sendline(data)`` and ``recvuntil(delim, timeout)``.'
def sendlinethen(self, delim, data, timeout=default):
self.send((data + self.newline)) return self.recvuntil(delim, timeout)
'interactive(prompt = pwnlib.term.text.bold_red(\'$\') + \' \') Does simultaneous reading and writing to the tube. In principle this just connects the tube to standard in and standard out, but in practice this is much more usable, since we are using :mod:`pwnlib.term` to print a floating prompt. Thus it only works in w...
def interactive(self, prompt=(term.text.bold_red('$') + ' ')):
self.info('Switching to interactive mode') go = threading.Event() def recv_thread(): while (not go.isSet()): try: cur = self.recv(timeout=0.05) cur = cur.replace('\r\n', '\n') if cur: sys.stdout.write(cur) ...
'stream() Receive data until the tube exits, and print it to stdout. Similar to :func:`interactive`, except that no input is sent. Similar to ``print tube.recvall()`` except that data is printed as it is received, rather than after all data is received. Arguments: line_mode(bool): Whether to receive line-by-line or raw...
def stream(self, line_mode=True):
buf = Buffer() function = (self.recvline if line_mode else self.recv) try: while True: buf.add(function()) sys.stdout.write(buf.data[(-1)]) except KeyboardInterrupt: pass except EOFError: pass return buf.get()
'clean(timeout = 0.05) Removes all the buffered data from a tube by calling :meth:`pwnlib.tubes.tube.tube.recv` with a low timeout until it fails. If ``timeout`` is zero, only cached data will be cleared. Note: If timeout is set to zero, the underlying network is not actually polled; only the internal buffer is cleared...
def clean(self, timeout=0.05):
if (timeout == 0): return self.buffer.get() return self.recvrepeat(timeout)
'clean_and_log(timeout = 0.05) Works exactly as :meth:`pwnlib.tubes.tube.tube.clean`, but logs received data with :meth:`pwnlib.self.info`. Returns: All data received Examples: >>> def recv(n, data=[\'\', \'hooray_data\']): ... while data: return data.pop() >>> t = tube() >>> t.recv_raw = recv >>> t.connected_...
def clean_and_log(self, timeout=0.05):
with context.local(log_level='debug'): return self.clean(timeout)
'connect_input(other) Connects the input of this tube to the output of another tube object. Examples: >>> def p(x): print x >>> def recvone(n, data=[\'data\']): ... while data: return data.pop() ... raise EOFError >>> a = tube() >>> b = tube() >>> a.recv_raw = recvone >>> b.send_raw = p >>> a.connected_raw = la...
def connect_input(self, other):
def pump(): import sys as _sys while self.countdown_active(): if (not (self.connected('send') and other.connected('recv'))): break try: data = other.recv(timeout=0.05) except EOFError: break if (not _sys)...
'connect_output(other) Connects the output of this tube to the input of another tube object. Examples: >>> def p(x): print x >>> def recvone(n, data=[\'data\']): ... while data: return data.pop() ... raise EOFError >>> a = tube() >>> b = tube() >>> a.recv_raw = recvone >>> b.send_raw = p >>> a.connected_raw = l...
def connect_output(self, other):
other.connect_input(self)
'connect_both(other) Connects the both ends of this tube object with another tube object.'
def connect_both(self, other):
self.connect_input(other) self.connect_output(other)
'Spawns a new process having this tube as stdin, stdout and stderr. Takes the same arguments as :class:`subprocess.Popen`.'
def spawn_process(self, *args, **kwargs):
return subprocess.Popen(stdin=self.fileno(), stdout=self.fileno(), stderr=self.fileno(), *args, **kwargs)
'Shorthand for connecting multiple tubes. See :meth:`connect_input` for more information. Examples: The following are equivalent :: tube_a >> tube.b tube_a.connect_input(tube_b) This is useful when chaining multiple tubes :: tube_a >> tube_b >> tube_a tube_a.connect_input(tube_b) tube_b.connect_input(tube_a)'
def __lshift__(self, other):
self.connect_input(other) return other
'Inverse of the ``<<`` operator. See :meth:`__lshift__`. See :meth:`connect_input` for more information.'
def __rshift__(self, other):
self.connect_output(other) return other
'Shorthand for connecting tubes to eachother. The following are equivalent :: a >> b >> a a <> b See :meth:`connect_input` for more information.'
def __ne__(self, other):
((self << other) << self)
'Waits until the tube is closed.'
def wait_for_close(self):
while self.connected(): time.sleep(0.05)
'can_recv(timeout = 0) -> bool Returns True, if there is data available within `timeout` seconds. Examples: >>> import time >>> t = tube() >>> t.can_recv_raw = lambda *a: False >>> t.can_recv() False >>> _=t.unrecv(\'data\') >>> t.can_recv() True >>> _=t.recv() >>> t.can_recv() False'
def can_recv(self, timeout=0):
return bool((self.buffer or self.can_recv_raw(timeout)))
'settimeout(timeout) Set the timeout for receiving operations. If the string "default" is given, then :data:`context.timeout` will be used. If None is given, then there will be no timeout. Examples: >>> t = tube() >>> t.settimeout_raw = lambda t: None >>> t.settimeout(3) >>> t.timeout == 3 True'
def settimeout(self, timeout):
self.timeout = timeout
'shutdown(direction = "send") Closes the tube for futher reading or writing depending on `direction`. Arguments: direction(str): Which direction to close; "in", "read" or "recv" closes the tube in the ingoing direction, "out", "write" or "send" closes it in the outgoing direction. Returns: :const:`None` Examples: >>> d...
def shutdown(self, direction='send'):
try: direction = self.shutdown_directions[direction] except KeyError: raise KeyError(('direction must be in %r' % sorted(self.shutdown_directions))) else: self.shutdown_raw(self.shutdown_directions[direction])