desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'connected(direction = \'any\') -> bool Returns True if the tube is connected in the specified direction. Arguments: direction(str): Can be the string \'any\', \'in\', \'read\', \'recv\', \'out\', \'write\', \'send\'. Doctest: >>> def p(x): print x >>> t = tube() >>> t.connected_raw = p >>> _=map(t.connected, (\'any\',...
def connected(self, direction='any'):
try: direction = self.connected_directions[direction] except KeyError: raise KeyError(('direction must be in %r' % sorted(self.connected_directions))) else: return self.connected_raw(direction)
'Permit use of \'with\' to control scoping and closing sessions. Examples: >>> t = tube() >>> def p(x): print x >>> t.close = lambda: p("Closed!") >>> with t: pass Closed!'
def __enter__(self):
return self
'Handles closing for \'with\' statement See :meth:`__enter__`'
def __exit__(self, type, value, traceback):
self.close()
'recv_raw(numb) -> str Should not be called directly. Receives data without using the buffer on the object. Unless there is a timeout or closed connection, this should always return data. In case of a timeout, it should return None, in case of a closed connection it should raise an ``exceptions.EOFError``.'
def recv_raw(self, numb):
raise EOFError('Not implemented')
'send_raw(data) Should not be called directly. Sends data to the tube. Should return ``exceptions.EOFError``, if it is unable to send any more, because of a close tube.'
def send_raw(self, data):
raise EOFError('Not implemented')
'settimeout_raw(timeout) Should not be called directly. Sets the timeout for the tube.'
def settimeout_raw(self, timeout):
raise NotImplementedError()
'Informs the raw layer of the tube that the timeout has changed. Should not be called directly. Inherited from :class:`Timeout`.'
def timeout_change(self):
try: self.settimeout_raw(self.timeout) except NotImplementedError: pass
'can_recv_raw(timeout) -> bool Should not be called directly. Returns True, if there is data available within the timeout, but ignores the buffer on the object.'
def can_recv_raw(self, timeout):
raise NotImplementedError()
'connected(direction = \'any\') -> bool Should not be called directly. Returns True iff the tube is connected in the given direction.'
def connected_raw(self, direction):
raise NotImplementedError()
'close() Closes the tube.'
def close(self):
pass
'fileno() -> int Returns the file number used for reading.'
def fileno(self):
raise NotImplementedError()
'shutdown_raw(direction) Should not be called directly. Closes the tube for further reading or writing.'
def shutdown_raw(self, direction):
raise NotImplementedError()
'recvall() -> str Receives data until the socket is closed.'
def recvall(self, timeout=tube.forever):
if (getattr(self, 'type', None) == socket.SOCK_DGRAM): self.error('UDP sockets does not supports recvall') else: return super(sock, self).recvall(timeout)
'Tests: >>> l = listen() >>> r = remote(\'localhost\', l.lport) >>> r.can_recv_raw(timeout=0) False >>> l.send(\'a\') >>> r.can_recv_raw(timeout=1) True >>> r.recv() \'a\' >>> r.can_recv_raw(timeout=0) False >>> l.close() >>> r.can_recv_raw(timeout=1) False >>> r.closed[\'recv\'] True'
def can_recv_raw(self, timeout):
if ((not self.sock) or self.closed['recv']): return False can_recv = (select.select([self.sock], [], [], timeout) == ([self.sock], [], [])) if (not can_recv): return False try: self.recv_raw(1, socket.MSG_PEEK) except EOFError: return False return True
'Tests: >>> l = listen() >>> r = remote(\'localhost\', l.lport) >>> r.connected() True >>> l.close() >>> time.sleep(1) # Avoid race condition >>> r.connected() False'
def connected_raw(self, direction):
if (not self.sock): return False if self.closed.get(direction, False): return False if all(self.closed.values()): return False want = {'recv': select.POLLIN, 'send': select.POLLOUT, 'any': (select.POLLIN | select.POLLOUT)}[direction] poll = select.poll() poll.register(sel...
'Blocks until a connection has been established.'
def wait_for_connection(self):
self.sock return self
'>>> b = Buffer() >>> b.add(\'lol\') >>> len(b) == 3 True >>> b.add(\'foobar\') >>> len(b) == 9 True'
def __len__(self):
return self.size
'>>> b = Buffer() >>> b.add(\'asdf\') >>> \'x\' in b False >>> b.add(\'x\') >>> \'x\' in b True'
def __contains__(self, x):
for b in self.data: if (x in b): return True return False
'>>> b = Buffer() >>> b.add(\'asdf\') >>> b.add(\'qwert\') >>> b.index(\'t\') == len(b) - 1 True'
def index(self, x):
sofar = 0 for b in self.data: if (x in b): return (sofar + b.index(x)) sofar += len(b) raise IndexError()
'Adds data to the buffer. Arguments: data(str,Buffer): Data to add'
def add(self, data):
if (not data): return if isinstance(data, Buffer): self.size += data.size self.data += data.data else: self.size += len(data) self.data.append(data)
'Places data at the front of the buffer. Arguments: data(str,Buffer): Data to place at the beginning of the buffer. Example: >>> b = Buffer() >>> b.add("hello") >>> b.add("world") >>> b.get(5) \'hello\' >>> b.unget("goodbye") >>> b.get() \'goodbyeworld\''
def unget(self, data):
if isinstance(data, Buffer): self.data = (data.data + self.data) self.size += data.size else: self.data.insert(0, data) self.size += len(data)
'Retrieves bytes from the buffer. Arguments: want(int): Maximum number of bytes to fetch Returns: Data as string Example: >>> b = Buffer() >>> b.add(\'hello\') >>> b.add(\'world\') >>> b.get(1) \'h\' >>> b.get() \'elloworld\''
def get(self, want=float('inf')):
if (want >= self.size): data = ''.join(self.data) self.size = 0 self.data = [] return data have = 0 i = 0 while (want >= have): have += len(self.data[i]) i += 1 data = ''.join(self.data[:i]) self.data = self.data[i:] if (have > want): e...
'Retrieves the default fill size for this buffer class. Arguments: size (int): (Optional) If set and not None, returns the size variable back. Returns: Fill size as integer if size == None, else size.'
def get_fill_size(self, size=None):
if (size is None): size = self.buffer_fill_size with context.local(buffer_size=size): return context.buffer_size
'kill() Kills the process.'
def kill(self):
self.close()
'poll() -> int 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):
if ((self.returncode == None) and self.sock and (block or self.sock.exit_status_ready())): while (not self.sock.status_event.is_set()): self.sock.status_event.wait(0.05) self.returncode = self.sock.recv_exit_status() return self.returncode
'interactive(prompt = pwnlib.term.text.bold_red(\'$\') + \' \') If not in TTY-mode, this does exactly the same as meth:`pwnlib.tubes.tube.tube.interactive`, otherwise it does mostly the same. An SSH connection in TTY-mode will typically supply its own prompt, thus the prompt argument is ignored in this case. We also ha...
def interactive(self, prompt=(term.text.bold_red('$') + ' ')):
if (self.process is not None): return super(ssh_channel, self).interactive(prompt) self.info('Switching to interactive mode') term.term.show_cursor() event = threading.Event() def recv_thread(event): while (not event.is_set()): try: cur = self.rec...
'libs() -> dict Returns a dictionary mapping the address of each loaded library in the process\'s address space. If ``/proc/$PID/maps`` cannot be opened, the output of ldd is used verbatim, which may be different than the actual addresses if ASLR is enabled.'
def libs(self):
maps = self.parent.libs(self.executable) maps_raw = self.parent.cat(('/proc/%d/maps' % self.pid)) for lib in maps: remote_path = lib.split(self.parent.host)[(-1)] for line in maps_raw.splitlines(): if line.endswith(remote_path): address = line.split('-')[0] ...
'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 libs = self.parent.libs(self.executable) for lib in libs: if (self.executable in lib): return pwnlib.elf.elf.ELF(lib)
'Retrieve the address of an environment variable in the remote process.'
def getenv(self, variable, **kwargs):
argv0 = self.argv[0] script = ';'.join(('from ctypes import *', 'import os', 'libc = CDLL("libc.so.6")', ('print os.path.realpath(%r)' % self.executable), ('print(libc.getenv(%r))' % variable))) try: with context.local(log_level='error'): python = self.parent.which('...
'Blocks until a connection has been established.'
def wait_for_connection(self):
_ = self.sock return self
'Creates a new ssh connection. Arguments: user(str): The username to log in with host(str): The hostname to connect to port(int): The port to connect to password(str): Try to authenticate using this password key(str): Try to authenticate using this private key. The string should be the actual private key. keyfile(str):...
def __init__(self, user, host, port=22, password=None, key=None, keyfile=None, proxy_command=None, proxy_sock=None, level=None, cache=True, ssh_agent=False, *a, **kw):
super(ssh, self).__init__(*a, **kw) Logger.__init__(self) if (level is not None): self.setLevel(level) self.host = host self.port = port self.user = user self.password = password self.key = key self.keyfile = keyfile self._cachedir = os.path.join(tempfile.gettempdir(), 'p...
'shell(shell = None, tty = True, timeout = Timeout.default) -> ssh_channel Open a new channel with a shell inside. Arguments: shell(str): Path to the shell program to run. If :const:`None`, uses the default shell for the logged in user. tty(bool): If :const:`True`, then a TTY is requested on the remote server. Returns:...
def shell(self, shell=None, tty=True, timeout=Timeout.default):
return self.run(shell, tty, timeout=timeout)
'Executes a process on the remote server, in the same fashion as pwnlib.tubes.process.process. To achieve this, a Python script is created to call ``os.execve`` with the appropriate arguments. As an added bonus, the ``ssh_channel`` object returned has a ``pid`` property for the process pid. Arguments: argv(list): List ...
def process(self, argv=None, executable=None, tty=True, cwd=None, env=None, timeout=Timeout.default, run=True, stdin=0, stdout=1, stderr=2, preexec_fn=None, preexec_args=[], raw=True, aslr=None, setuid=None, shell=False):
if ((not argv) and (not executable)): self.error('Must specify argv or executable') argv = (argv or []) aslr = (aslr if (aslr is not None) else context.aslr) if isinstance(argv, (str, unicode)): argv = [argv] if (not isinstance(argv, (list, tuple))): self.error('a...
'which(program) -> str Minor modification to just directly invoking ``which`` on the remote system which adds the current working directory to the end of ``$PATH``.'
def which(self, program):
if (os.path.sep in program): return program result = self.run(('export PATH=$PATH:$PWD; which %s' % program)).recvall().strip() if (('/%s' % program) not in result): return None return result
'system(process, tty = True, wd = None, env = None, timeout = Timeout.default, raw = True) -> ssh_channel Open a new channel with a specific process inside. If `tty` is True, then a TTY is requested on the remote server. If `raw` is True, terminal control codes are ignored and input is not echoed back. Return a :class:...
def system(self, process, tty=True, wd=None, env=None, timeout=None, raw=True):
if (wd is None): wd = self.cwd if (timeout is None): timeout = self.timeout return ssh_channel(self, process, tty, wd, env, timeout=timeout, level=self.level, raw=raw)
'Retrieve the address of an environment variable on the remote system. Note: The exact address will differ based on what other environment variables are set, as well as argv[0]. In order to ensure that the path is *exactly* the same, it is recommended to invoke the process with ``argv=[]``.'
def getenv(self, variable, **kwargs):
script = ("\nfrom ctypes import *; libc = CDLL('libc.so.6'); print(libc.getenv(%r))\n" % variable) with context.local(log_level='error'): python = self.which('python') if (not python): self.error('Python is not installed on the remote system....
'run_to_end(process, tty = False, timeout = Timeout.default, env = None) -> str Run a command on the remote server and return a tuple with (data, exit_status). If `tty` is True, then the command is run inside a TTY on the remote server. Examples: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... ...
def run_to_end(self, process, tty=False, wd=None, env=None):
with context.local(log_level='ERROR'): c = self.run(process, tty, wd=wd, timeout=Timeout.default) data = c.recvall() retcode = c.wait() c.close() return (data, retcode)
'connect_remote(host, port, timeout = Timeout.default) -> ssh_connecter Connects to a host through an SSH connection. This is equivalent to using the ``-L`` flag on ``ssh``. Returns a :class:`pwnlib.tubes.ssh.ssh_connecter` object. Examples: >>> from pwn import * >>> l = listen() >>> s = ssh(host=\'example.pwnme\', .....
def connect_remote(self, host, port, timeout=Timeout.default):
return ssh_connecter(self, host, port, timeout, level=self.level)
'listen_remote(port = 0, bind_address = \'\', timeout = Timeout.default) -> ssh_connecter Listens remotely through an SSH connection. This is equivalent to using the ``-R`` flag on ``ssh``. Returns a :class:`pwnlib.tubes.ssh.ssh_listener` object. Examples: >>> from pwn import * >>> s = ssh(host=\'example.pwnme\', ... ...
def listen_remote(self, port=0, bind_address='', timeout=Timeout.default):
return ssh_listener(self, bind_address, port, timeout, level=self.level)
'Permits indexed access to run commands over SSH Examples: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\') >>> print s[\'echo hello\'] hello'
def __getitem__(self, attr):
return self.__getattr__(attr)()
'Permits function-style access to run commands over SSH Examples: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\') >>> print repr(s(\'echo hello\')) \'hello\''
def __call__(self, attr):
return self.__getattr__(attr)()
'Permits member access to run commands over SSH Examples: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\') >>> s.echo(\'hello\') \'hello\' >>> s.whoami() \'travis\' >>> s.echo([\'huh\',\'yay\',\'args\']) \'huh yay args\''
def __getattr__(self, attr):
bad_attrs = ['trait_names'] if ((attr in self.__dict__) or (attr in bad_attrs) or attr.startswith('_')): raise AttributeError def runner(*args): if ((len(args) == 1) and isinstance(args[0], (list, tuple))): command = ([attr] + args[0]) else: command = ' '.j...
'Returns True if we are connected. Example: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\') >>> s.connected() True >>> s.close() >>> s.connected() False'
def connected(self):
return bool((self.client and self.client.get_transport().is_active()))
'Close the connection.'
def close(self):
if self.client: self.client.close() self.client = None self.info(('Closed connection to %r' % self.host))
'Return a dictionary of the libraries used by a remote file.'
def _libs_remote(self, remote):
escaped_remote = sh_string(remote) cmd = ''.join(['(', 'ulimit -s unlimited;', ('ldd %s > /dev/null &&' % escaped_remote), '(', ('LD_TRACE_LOADED_OBJECTS=1 %s||' % escaped_remote), ('ldd %s' % escaped_remote), '))', ' 2>/dev/null']) (data, status) = self.run_to_end(cmd) if (st...
'Downloads a file from the remote server and returns it as a string. Arguments: remote(str): The remote filename to download. Examples: >>> with file(\'/tmp/bar\',\'w+\') as f: ... f.write(\'Hello, world\') >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\', ... ...
def download_data(self, remote):
with self.progress(('Downloading %r' % remote)) as p: with open(self._download_to_cache(remote, p)) as fd: return fd.read()
'Downloads a file from the remote server. The file is cached in /tmp/pwntools-ssh-cache using a hash of the file, so calling the function twice has little overhead. Arguments: remote(str): The remote filename to download local(str): The local filename to save it to. Default is to infer it from the remote filename.'
def download_file(self, remote, local=None):
if (not local): local = os.path.basename(os.path.normpath(remote)) if (os.path.basename(remote) == remote): remote = os.path.join(self.cwd, remote) with self.progress(('Downloading %r to %r' % (remote, local))) as p: local_tmp = self._download_to_cache(remote, p) if ((no...
'Recursively downloads a directory from the remote server Arguments: local: Local directory remote: Remote directory'
def download_dir(self, remote=None, local=None):
remote = (remote or self.cwd) if self.sftp: remote = str(self.sftp.normalize(remote)) else: with context.local(log_level='error'): remote = self.system(('readlink -f ' + sh_string(remote))) dirname = os.path.dirname(remote) basename = os.path.basename(remote) lo...
'Uploads some data into a file on the remote server. Arguments: data(str): The data to upload. remote(str): The filename to upload it to. Example: >>> s = ssh(host=\'example.pwnme\', ... user=\'travis\', ... password=\'demopass\') >>> s.upload_data(\'Hello, world\', \'/tmp/upload_foo\') >>> print file(...
def upload_data(self, data, remote):
if (os.path.normpath(remote) == os.path.basename(remote)): remote = os.path.join(self.cwd, remote) if self.sftp: with tempfile.NamedTemporaryFile() as f: f.write(data) f.flush() self.sftp.put(f.name, remote) return with context.local(log_level=...
'Uploads a file to the remote server. Returns the remote filename. Arguments: filename(str): The local filename to download remote(str): The remote filename to save it to. Default is to infer it from the local filename.'
def upload_file(self, filename, remote=None):
if (remote == None): remote = os.path.normpath(filename) remote = os.path.basename(remote) remote = os.path.join(self.cwd, remote) with open(filename) as fd: data = fd.read() self.info(('Uploading %r to %r' % (filename, remote))) self.upload_data(data, remote) ...
'Recursively uploads a directory onto the remote server Arguments: local: Local directory remote: Remote directory'
def upload_dir(self, local, remote=None):
remote = (remote or self.cwd) local = os.path.expanduser(local) dirname = os.path.dirname(local) basename = os.path.basename(local) if (not os.path.isdir(local)): self.error(('%r is not a directory' % local)) msg = ('Uploading %r to %r' % (basename, remote)) with...
'upload(file_or_directory, remote=None) Upload a file or directory to the remote host. Arguments: file_or_directory(str): Path to the file or directory to download. remote(str): Local path to store the data. By default, uses the working directory.'
def upload(self, file_or_directory, remote=None):
if isinstance(file_or_directory, str): file_or_directory = os.path.expanduser(file_or_directory) file_or_directory = os.path.expandvars(file_or_directory) if os.path.isfile(file_or_directory): return self.upload_file(file_or_directory, remote) if os.path.isdir(file_or_directory): ...
'download(file_or_directory, local=None) Download a file or directory from the remote host. Arguments: file_or_directory(str): Path to the file or directory to download. local(str): Local path to store the data. By default, uses the current directory.'
def download(self, file_or_directory, local=None):
if (not self.sftp): self.error('Cannot determine remote file type without SFTP') if (0 == self.system(('test -d ' + sh_string(file_or_directory))).wait()): self.download_dir(file_or_directory, local) else: self.download_file(file_or_directory, local)
'unlink(file) Delete the file on the remote host Arguments: file(str): Path to the file'
def unlink(self, file):
if (not self.sftp): self.error('unlink() is only supported if SFTP is supported') return self.sftp.unlink(file)
'Downloads the libraries referred to by a file. This is done by running ldd on the remote server, parsing the output and downloading the relevant files. The directory argument specified where to download the files. This defaults to \'./$HOSTNAME\' where $HOSTNAME is the hostname of the remote server.'
def libs(self, remote, directory=None):
libs = self._libs_remote(remote) remote = self.readlink('-f', remote).strip() libs[remote] = 0 if (directory == None): directory = self.host directory = os.path.realpath(directory) res = {} seen = set() for (lib, addr) in libs.items(): local = os.path.realpath(os.path.joi...
'Create an interactive session. This is a simple wrapper for creating a new :class:`pwnlib.tubes.ssh.ssh_channel` object and calling :meth:`pwnlib.tubes.ssh.ssh_channel.interactive` on it.'
def interactive(self, shell=None):
s = self.shell(shell) if (self.cwd != '.'): cmd = ('cd ' + sh_string(self.cwd)) s.sendline(cmd) s.interactive() s.close()
'Sets the working directory in which future commands will be run (via ssh.run) and to which files will be uploaded/downloaded from if no path is provided Note: This uses ``mktemp -d`` under the covers, sets permissions on the directory to ``0700``. This means that setuid binaries will **not** be able to access files c...
def set_working_directory(self, wd=None, symlink=False):
status = 0 if (symlink and (not isinstance(symlink, str))): symlink = os.path.join(self.pwd(), '*') if (not wd): (wd, status) = self.run_to_end('x=$(mktemp -d) && cd $x && chmod +x . && echo $PWD', wd='.') wd = wd.strip() if status: ...
'Wrapper around upload_data to match :func:`pwnlib.util.misc.write`'
def write(self, path, data):
return self.upload_data(data, path)
'Wrapper around download_data to match :func:`pwnlib.util.misc.read`'
def read(self, path):
return self.download_data(path)
'Fills _platform_info, e.g.: {\'distro\': \'Ubuntu \'distro_ver\': \'14.04 \'machine\': \'x86_64\', \'node\': \'pwnable.kr\', \'processor\': \'x86_64\', \'release\': \'3.11.0-12-generic\', \'system\': \'linux\', \'version\': \'#19-ubuntu smp wed oct 9 16:20:46 utc 2013\'}'
def _init_remote_platform_info(self):
if self._platform_info: return def preexec(): import platform print '\n'.join(platform.uname()) with context.quiet: with self.process('true', preexec_fn=preexec) as io: self._platform_info = {'system': io.recvline().lower().strip(), 'node': io.recvline().lower().s...
':class:`str`: Operating System of the remote machine.'
@property def os(self):
try: self._init_remote_platform_info() with context.local(os=self._platform_info['system']): return context.os except Exception: return 'Unknown'
':class:`str`: CPU Architecture of the remote machine.'
@property def arch(self):
try: self._init_remote_platform_info() with context.local(arch=self._platform_info['machine']): return context.arch except Exception: return 'Unknown'
':class:`str`: Pointer size of the remote machine.'
@property def bits(self):
try: with context.local(): context.clear() context.arch = self.arch return context.bits except Exception: return context.bits
':class:`tuple`: Kernel version of the remote machine.'
@property def version(self):
try: self._init_remote_platform_info() vers = self._platform_info['release'] expr = '([0-9]+\\.?)+' vers = re.search(expr, vers).group() return tuple(map(int, vers.split('.'))) except Exception: return (0, 0, 0)
':class:`tuple`: Linux distribution name and release.'
@property def distro(self):
try: self._init_remote_platform_info() return (self._platform_info['distro'], self._platform_info['distro_ver']) except Exception: return ('Unknown', 'Unknown')
':class:`bool`: Whether ASLR is enabled on the system. Example: >>> s = ssh("travis", "example.pwnme") >>> s.aslr True'
@property def aslr(self):
if (self._aslr is None): if (self.os != 'linux'): self.warn_once('Only Linux is supported for ASLR checks.') self._aslr = False else: with context.quiet: rvs = self.read('/proc/sys/kernel/randomize_va_space') self._asl...
':class:`bool`: Whether the entropy of 32-bit processes can be reduced with ulimit.'
@property def aslr_ulimit(self):
import pwnlib.elf.elf import pwnlib.shellcraft if (self._aslr_ulimit is not None): return self._aslr_ulimit arch = {'amd64': 'i386', 'aarch64': 'arm'}.get(self.arch, self.arch) with context.local(arch=arch, bits=32, os=self.os, aslr=True): with context.quiet: try: ...
'checksec() Prints a helpful message about the remote system. Arguments: banner(bool): Whether to print the path to the ELF binary.'
def checksec(self, banner=True):
cached = self._checksec_cache() if cached: return cached red = text.red green = text.green yellow = text.yellow res = [('%s@%s:' % (self.user, self.host)), ('Distro'.ljust(10) + ' '.join(self.distro)), ('OS:'.ljust(10) + self.os), ('Arch:'.ljust(10) + self.arch), ('Version:'.ljust(10)...
'struct(address, struct) => structure object Leak an entire structure. Arguments: address(int): Addess of structure in memory struct(class): A ctypes structure to be instantiated with leaked data Return Value: An instance of the provided struct class, with the leaked data decoded Examples: >>> @pwnlib.memleak.MemLeak ...
def struct(self, address, struct):
size = ctypes.sizeof(struct) data = self.n(address, size) obj = struct.from_buffer_copy(data) return obj
'field(address, field) => a structure field. Leak a field from a structure. Arguments: address(int): Base address to calculate offsets from field(obj): Instance of a ctypes field Return Value: The type of the return value will be dictated by the type of ``field``.'
def field(self, address, obj):
size = obj.size offset = obj.offset data = self.n((address + offset), size) if (not data): return None return unpack(data, (size * 8))
'field_compare(address, field, expected) ==> bool Leak a field from a structure, with an expected value. As soon as any mismatch is found, stop leaking the structure. Arguments: address(int): Base address to calculate offsets from field(obj): Instance of a ctypes field expected(int,str): Expected value Return Value: ...
def field_compare(self, address, obj, expected):
if (not isinstance(expected, (int, str))): raise TypeError('Expected value must be an int or str') if isinstance(expected, int): expected = pack(expected, bytes=obj.size) assert (obj.size == len(expected)) return self.compare((address + obj.offset), expected)
'_leak(addr, n) => str Leak ``n`` consecutive bytes starting at ``addr``. Returns: A string of length ``n``, or :const:`None`.'
def _leak(self, addr, n, recurse=True):
if ((not self.relative) and (addr < 0)): return None addresses = [(addr + i) for i in xrange(n)] for address in addresses: if (address in self.cache): continue data = None try: data = self.leak(address) except Exception as e: if sel...
'raw(addr, numb) -> list Leak `numb` bytes at `addr`'
def raw(self, addr, numb):
return map((lambda a: self._leak(a, 1)), range(addr, (addr + numb)))
'b(addr, ndx = 0) -> int Leak byte at ``((uint8_t*) addr)[ndx]`` Examples: >>> import string >>> data = string.ascii_lowercase >>> l = MemLeak(lambda a: data[a:a+2], reraise=False) >>> l.b(0) == ord(\'a\') True >>> l.b(25) == ord(\'z\') True >>> l.b(26) is None True'
def b(self, addr, ndx=0):
return self._b(addr, ndx, 1)
'w(addr, ndx = 0) -> int Leak word at ``((uint16_t*) addr)[ndx]`` Examples: >>> import string >>> data = string.ascii_lowercase >>> l = MemLeak(lambda a: data[a:a+4], reraise=False) >>> l.w(0) == unpack(\'ab\', 16) True >>> l.w(24) == unpack(\'yz\', 16) True >>> l.w(25) is None True'
def w(self, addr, ndx=0):
return self._b(addr, ndx, 2)
'd(addr, ndx = 0) -> int Leak dword at ``((uint32_t*) addr)[ndx]`` Examples: >>> import string >>> data = string.ascii_lowercase >>> l = MemLeak(lambda a: data[a:a+8], reraise=False) >>> l.d(0) == unpack(\'abcd\', 32) True >>> l.d(22) == unpack(\'wxyz\', 32) True >>> l.d(23) is None True'
def d(self, addr, ndx=0):
return self._b(addr, ndx, 4)
'q(addr, ndx = 0) -> int Leak qword at ``((uint64_t*) addr)[ndx]`` Examples: >>> import string >>> data = string.ascii_lowercase >>> l = MemLeak(lambda a: data[a:a+16], reraise=False) >>> l.q(0) == unpack(\'abcdefgh\', 64) True >>> l.q(18) == unpack(\'stuvwxyz\', 64) True >>> l.q(19) is None True'
def q(self, addr, ndx=0):
return self._b(addr, ndx, 8)
'p(addr, ndx = 0) -> int Leak a pointer-width value at ``((void**) addr)[ndx]``'
def p(self, addr, ndx=0):
return self._b(addr, ndx, context.bytes)
's(addr) -> str Leak bytes at `addr` until failure or a nullbyte is found Return: A string, without a NULL terminator. The returned string will be empty if the first byte is a NULL terminator, or if the first byte could not be retrieved. Examples: >>> data = "Hello\x00World" >>> l = MemLeak(lambda a: data[a:a+4], rerai...
def s(self, addr):
orig = addr while self.b(addr): addr += 1 return self._leak(orig, (addr - orig))
'n(addr, ndx = 0) -> str Leak `numb` bytes at `addr`. Returns: A string with the leaked bytes, will return `None` if any are missing Examples: >>> import string >>> data = string.ascii_lowercase >>> l = MemLeak(lambda a: data[a:a+4], reraise=False) >>> l.n(0,1) == \'a\' True >>> l.n(0,26) == data True >>> len(l.n(0,26)...
def n(self, addr, numb):
return (self._leak(addr, numb) or None)
'clearb(addr, ndx = 0) -> int Clears byte at ``((uint8_t*)addr)[ndx]`` from the cache and returns the removed value or `None` if the address was not completely set. Examples: >>> l = MemLeak(lambda a: None) >>> l.cache = {0:\'a\'} >>> l.n(0,1) == \'a\' True >>> l.clearb(0) == unpack(\'a\', 8) True >>> l.cache >>> l.cle...
def clearb(self, addr, ndx=0):
return self._clear(addr, ndx, 1)
'clearw(addr, ndx = 0) -> int Clears word at ``((uint16_t*)addr)[ndx]`` from the cache and returns the removed value or `None` if the address was not completely set. Examples: >>> l = MemLeak(lambda a: None) >>> l.cache = {0:\'a\', 1: \'b\'} >>> l.n(0, 2) == \'ab\' True >>> l.clearw(0) == unpack(\'ab\', 16) True >>> l....
def clearw(self, addr, ndx=0):
return self._clear(addr, ndx, 2)
'cleard(addr, ndx = 0) -> int Clears dword at ``((uint32_t*)addr)[ndx]`` from the cache and returns the removed value or `None` if the address was not completely set. Examples: >>> l = MemLeak(lambda a: None) >>> l.cache = {0:\'a\', 1: \'b\', 2: \'c\', 3: \'d\'} >>> l.n(0, 4) == \'abcd\' True >>> l.cleard(0) == unpack(...
def cleard(self, addr, ndx=0):
return self._clear(addr, ndx, 4)
'clearq(addr, ndx = 0) -> int Clears qword at ``((uint64_t*)addr)[ndx]`` from the cache and returns the removed value or `None` if the address was not completely set. Examples: >>> c = MemLeak(lambda addr: \'\') >>> c.cache = {x:\'x\' for x in range(0x100, 0x108)} >>> c.clearq(0x100) == unpack(\'xxxxxxxx\', 64) True >>...
def clearq(self, addr, ndx=0):
return self._clear(addr, ndx, 8)
'Sets byte at ``((uint8_t*)addr)[ndx]`` to `val` in the cache. Examples: >>> l = MemLeak(lambda x: \'\') >>> l.cache == {} True >>> l.setb(33, 0x41) >>> l.cache == {33: \'A\'} True'
def setb(self, addr, val, ndx=0):
return self._set(addr, val, ndx, 1)
'Sets word at ``((uint16_t*)addr)[ndx]`` to `val` in the cache. Examples: >>> l = MemLeak(lambda x: \'\') >>> l.cache == {} True >>> l.setw(33, 0x41) >>> l.cache == {33: \'A\', 34: \'\x00\'} True'
def setw(self, addr, val, ndx=0):
return self._set(addr, val, ndx, 2)
'Sets dword at ``((uint32_t*)addr)[ndx]`` to `val` in the cache. Examples: See :meth:`setw`.'
def setd(self, addr, val, ndx=0):
return self._set(addr, val, ndx, 4)
'Sets qword at ``((uint64_t*)addr)[ndx]`` to `val` in the cache. Examples: See :meth:`setw`.'
def setq(self, addr, val, ndx=0):
return self._set(addr, val, ndx, 8)
'Set known string at `addr`, which will be optionally be null-terminated Note that this method is a bit dumb about how it handles the data. It will null-terminate the data, but it will not stop at the first null. Examples: >>> l = MemLeak(lambda x: \'\') >>> l.cache == {} True >>> l.sets(0, \'H\x00ello\') >>> l.cache =...
def sets(self, addr, val, null_terminate=True):
if null_terminate: val += '\x00' for (i, b) in enumerate(val): self.cache[(addr + i)] = b
'Wrapper for leak functions such that addresses which contain NULL bytes are not leaked. This is useful if the address which is used for the leak is read in via a string-reading function like ``scanf("%s")`` or smilar.'
@staticmethod def NoNulls(function):
@functools.wraps(function, updated=[]) def null_wrapper(address, *a, **kw): if ('\x00' in pack(address)): log.info(('Ignoring leak request for %#x: Contains NULL bytes' % address)) return None return function(address, *a, **kw) return MemLeak(null...
'Wrapper for leak functions such that addresses which contain whitespace bytes are not leaked. This is useful if the address which is used for the leak is read in via e.g. ``scanf()``.'
@staticmethod def NoWhitespace(function):
@functools.wraps(function, updated=[]) def whitespace_wrapper(address, *a, **kw): if (set(pack(address)) & set(string.whitespace)): log.info(('Ignoring leak request for %#x: Contains whitespace' % address)) return None return function(address, *a, **kw) ...
'Wrapper for leak functions such that addresses which contain newline bytes are not leaked. This is useful if the address which is used for the leak is provided by e.g. ``fgets()``.'
@staticmethod def NoNewlines(function):
@functools.wraps(function, updated=[]) def whitespace_wrapper(address, *a, **kw): if ('\n' in pack(address)): log.info(('Ignoring leak request for %#x: Contains newlines' % address)) return None return function(address, *a, **kw) return MemLeak(white...
'Wrapper for leak functions which leak strings, such that a NULL terminator is automaticall added. This is useful if the data leaked is printed out as a NULL-terminated string, via e.g. ``printf()``.'
@staticmethod def String(function):
@functools.wraps(function, updated=[]) def string_wrapper(address, *a, **kw): result = function(address, *a, **kw) if isinstance(result, (str, bytes)): result += '\x00' return result return MemLeak(string_wrapper)
'Wrapps a callable in a scope which selects the current device.'
def __wrapped(self, function):
@functools.wraps(function) def wrapper(*a, **kw): with context.local(device=self): return function(*a, **kw) return wrapper
'Provides scoped access to ``adb`` module propertise, in the context of this device. >>> property = \'ro.build.fingerprint\' >>> device = adb.wait_for_device() >>> adb.getprop(property) == device.getprop(property) True'
def __getattr__(self, name):
with context.local(device=self): g = globals() if (name not in g): raise AttributeError(('%r object has no attribute %r' % (type(self).__name__, name))) value = g[name] if (not hasattr(value, '__call__')): return value return self.__wrapped(value)
'Returns a dictionary of kernel symbols'
@property @context.quietfunc def symbols(self):
result = {} for line in self.kallsyms.splitlines(): fields = line.split() address = int(fields[0], 16) name = fields[(-1)] result[name] = address return result
'Returns the raw output of kallsyms'
@property @context.quietfunc def kallsyms(self):
if (not self._kallsyms): self._kallsyms = {} root() write('/proc/sys/kernel/kptr_restrict', '1') self._kallsyms = read('/proc/kallsyms') return self._kallsyms
'Returns the kernel version of the device.'
@property @context.quietfunc def version(self):
root() return read('/proc/version').strip()
'Reboots the device with kernel logging to the UART enabled.'
def enable_uart(self):
model = str(properties.ro.product.model) known_commands = {'Nexus 4': None, 'Nexus 5': None, 'Nexus 6': 'oem config console enable', 'Nexus 5X': None, 'Nexus 6P': 'oem uart enable', 'Nexus 7': 'oem uart-on'} with log.waitfor('Enabling kernel UART') as w: if ...