Compare commits

...
27 Commits
Author SHA1 Message Date
Mathias Svensson 7ed118763b Merge branch 'dev' into beta 2016-12-24 11:54:21 +01:00
Mathias Svensson e997c17397 Merge branch 'beta' into dev 2016-12-24 11:10:10 +01:00
Mathias Svensson 0acc8ee499 Merge branch 'stable' into beta 2016-12-24 11:00:32 +01:00
Zach Riggle f14e0e5652 Reorder get_buffer_size so that the value is validated
This prevents silly things like tube.recv("abcdef") which will hang
2016-12-22 16:41:51 -05:00
Zach Riggle aaa83983ad Merge branch 'beta' into dev 2016-12-22 16:27:46 -05:00
Zach Riggle 1241073391 Remove support for installation without psutil (#821)
* Remove support for installation without psutil.

OpenBSD was the edge case we cared about, it is supported for over a year (giampaolo/psutil#615)

* Bump psutil version to when they introduced OpenBSD support
2016-12-20 14:06:06 -05:00
Zach Riggle cfcd79e169 Update install strings to include libffi-dev and be consistent 2016-12-16 11:37:13 -06:00
Zach Riggle 706a784904 Directly invoke sock.close() when we hit POLLHUP 2016-12-15 20:20:07 -06:00
Zach Riggle 70c96330de Make sock.connected much more robust by using socket.poll (#817)
* Make sock.connected much more robust by using socket.poll

* Fix use of socket.socket.recv vs. ssh transport recv
2016-12-15 20:15:19 -06:00
Zach Riggle cae3cddc07 Fix incorrect error message in serialtube 2016-12-15 20:04:12 -06:00
Zach Riggle 5373dcdeed Fix dev-only regression in serialtube constructor, and use Timeout object properties 2016-12-15 20:04:12 -06:00
Zach Riggle 5d4bf3db6c Add MemLeak.u64/u32/... aliases 2016-12-15 17:15:10 -06:00
Zach Riggle fbfa54ad61 Fix failing doctestse on dev 2016-12-15 16:45:08 -06:00
Zach Riggle b323264032 Merge branch 'beta' into dev 2016-12-15 15:05:16 -06:00
Zach Riggle 2c841eaa21 Add adb.{unlink,mkdir,makedirs,isdir,exists} (#809)
* Add adb.{unlink,mkdir,makedirs,isdir,exists}

* Change unlink() to throw an exception rather than return a string

* Fix doctest and code for isdir

* Remove unused variable
2016-12-14 16:49:41 -06:00
Zach Riggle d2c6184a00 Add missing changelog entry 2016-12-14 14:58:00 -06:00
Zach Riggle e5645e7b53 Update CHANGELOG missing links 2016-12-14 14:49:54 -06:00
Zach Riggle 09dbe0a54d Update CHANGELOG links 2016-12-14 14:49:27 -06:00
Zach Riggle 0bd0de78f9 Update CHANGELOG 2016-12-14 14:48:19 -06:00
Zach Riggle 546061e577 Modify coredump_filter of spawned processes so that library contents are included 2016-12-12 18:26:46 -06:00
Zach Riggle 5ebc8b5bb7 Check the name before attempting to call startswith() 2016-12-12 18:26:46 -06:00
Zach Riggle b83a6c7db8 Fix process.leak by providing a sane default leak size 2016-12-05 15:44:04 -05:00
Owlz 5d9792fb4c Variable Size Buffer Fill (#806)
Support custom buffer-read sizes for `tube` objects via their internal `Buffer` object.  Default buffer size is 4096.  Buffer size can be set per-object at instantiation-time (`tube(buffer_fill_size=...)`), by attribute (`tube.buffer_fill_size=...`), or in a context (`context.buffer_size=...`).
2016-12-05 15:21:08 -05:00
Zach Riggle 1c54e347f2 Add 'shell' option for ssh.process to pass to "sh -c" (#800)
Add 'shell' option for ssh.process to pass to "sh -c"
2016-11-29 11:52:44 -07:00
Zach Riggle 7545dafffb Wrap context.log_console when using terminal I/O (#797)
Fixes Gallopsled/pwntools#792
2016-11-23 11:11:17 -07:00
Zach Riggle 3acec5421f Set shell=False 2016-11-12 23:16:32 -08:00
Mathias Svensson b441cf967a Start work on 3.4.0 2016-11-12 20:39:25 +01:00
21 changed files with 372 additions and 157 deletions

No files matched your search

+12
View File
@@ -31,6 +31,18 @@ To be released on Mar 18, 2017.
To be released on Feb 4, 2017.
- [#800][800] Add `shell=` option to `ssh.process()`
- [5d9792f][5d9792f] Add `context.buffer_size` for fine-tuning `tube` performance
+ Also adds `buffer_fill_size=` argument for all tubes
- [b83a6c7][b83a6c7] Fix undocumented `process.leak` function
- [546061e][546061e] Modify `coredump_filter` of all spawned processes, so that core dumps are more complete
[800]: https://github.com/Gallopsled/pwntools/pull/800
[5d9792f]: https://github.com/Gallopsled/pwntools/commit/5d9792f
[b83a6c7]: https://github.com/Gallopsled/pwntools/commit/b83a6c7
[546061e]: https://github.com/Gallopsled/pwntools/commit/546061e
## 3.3.0
- [b198ec8][b198ec8] Added `tube.stream()` function, which is like `tube.interact()` without a prompt or keyboard input.
+1 -1
View File
@@ -38,7 +38,7 @@ Most of the functionality of pwntools is self-contained and Python-only. You sh
```sh
apt-get update
apt-get install python2.7 python-pip python-dev git libssl-dev
apt-get install python2.7 python-pip python-dev git libssl-dev libffi-dev
pip install --upgrade pwntools
```
+2 -1
View File
@@ -24,7 +24,8 @@ pwntools is available as a ``pip`` package.
.. code-block:: bash
$ apt-get install python2.7 python2.7-dev python-pip
$ apt-get update
$ apt-get install python2.7 python-pip python-dev git libssl-dev libffi-dev
$ pip install --upgrade pwntools
Development
+147 -4
View File
@@ -599,6 +599,150 @@ def write(path, data=''):
misc.write(temp.name, data)
push(temp.name, path)
@context.quiet
@with_device
def mkdir(path):
"""Create a directory on the target device.
Note:
Silently succeeds if the directory already exists.
Arguments:
path(str): Directory to create.
Examples:
>>> adb.mkdir('/')
>>> path = '/data/local/tmp/mkdir_test'
>>> adb.exists(path)
False
>>> adb.mkdir(path)
>>> adb.exists(path)
True
>>> adb.mkdir('/init')
Traceback (most recent call last):
...
PwnlibException: mkdir failed for /init, File exists
"""
if not path.startswith('/'):
log.error("Must provide an absolute path: %r" % path)
with Client() as c:
st = c.stat(path)
# Don't re-create existing directories
if st and stat.S_ISDIR(st['mode']):
return
result = process(['mkdir', path]).recvall()
# Any output at all is an error
if result:
log.error(result)
@context.quiet
@with_device
def makedirs(path):
"""Create a directory and all parent directories on the target device.
Note:
Silently succeeds if the directory already exists.
Examples:
>>> adb.makedirs('/data/local/tmp/this/is/a/directory/heirarchy')
>>> adb.listdir('/data/local/tmp/this/is/a/directory')
['heirarchy']
"""
if path != '/':
makedirs(os.path.dirname(path))
mkdir(path)
@context.quiet
@with_device
def exists(path):
"""Return ``True`` if ``path`` exists on the target device.
Examples:
>>> adb.exists('/')
True
>>> adb.exists('/init')
True
>>> adb.exists('/does/not/exist')
False
"""
with Client() as c:
return bool(c.stat(path))
@context.quiet
@with_device
def isdir(path):
"""Return ``True`` if ``path`` is a on the target device.
Examples:
>>> adb.isdir('/')
True
>>> adb.isdir('/init')
False
>>> adb.isdir('/does/not/exist')
False
"""
with Client() as c:
st = c.stat(path)
return bool(st and stat.S_ISDIR(st['mode']))
@context.quiet
@with_device
def unlink(path, recursive=False):
"""Unlinks a file or directory on the target device.
Examples:
>>> adb.unlink("/does/not/exist")
Traceback (most recent call last):
...
PwnlibException: Could not unlink '/does/not/exist': Does not exist
>>> filename = '/data/local/tmp/unlink-test'
>>> adb.write(filename, 'hello')
>>> adb.exists(filename)
True
>>> adb.unlink(filename)
>>> adb.exists(filename)
False
>>> adb.mkdir(filename)
>>> adb.write(filename + '/contents', 'hello')
>>> adb.unlink(filename)
Traceback (most recent call last):
...
PwnlibException: Cannot delete non-empty directory '/data/local/tmp/unlink-test' without recursive=True
>>> adb.unlink(filename, recursive=True)
>>> adb.exists(filename)
False
"""
with Client() as c:
st = c.stat(path)
if not st:
log.error("Could not unlink %r: Does not exist" % path)
# If the directory is not empty, do not delete it
if isdir(path) and c.list(path) and not recursive:
log.error("Cannot delete non-empty directory %r without recursive=True" % path)
flags = '-rf' if recursive else '-r'
output = c.execute(['rm', flags, path]).recvall()
if output:
log.error(output)
@with_device
def process(argv, *a, **kw):
"""Execute a process on the device.
@@ -760,16 +904,15 @@ def listdir(directory='/'):
"""
return list(sorted(Client().list(directory)))
@with_device
def fastboot(args, *a, **kw):
"""Executes a fastboot command.
Returns:
The command output.
"""
serial = context.device
if not serial:
log.error("Unknown device")
return tubes.process.process(['fastboot', '-s', serial] + list(args), **kw).recvall()
argv = ['fastboot', '-s', str(context.device)] + list(args)
return tubes.process.process(argv, *a, **kw).recvall()
@with_device
def fingerprint():
+1 -1
View File
@@ -16,8 +16,8 @@ from . import scramble
from . import shellcraft
from . import unhex
from . import update
from .common import parser
from ..context import context
from .common import parser
commands = {
'asm': asm.main,
+1 -1
View File
@@ -21,7 +21,7 @@ p.add_argument('--pre', action='store_true', help='''
def main(a):
result = pwnlib.update.perform_check(prerelease=a.pre)
if a.install:
subprocess.check_call(result, shell=True)
subprocess.check_call(result, shell=False)
if __name__ == '__main__':
pwnlib.common.main(__file__)
+10 -1
View File
@@ -330,6 +330,7 @@ class ContextType(object):
'aslr': True,
'binary': None,
'bits': 32,
'buffer_size': 4096,
'device': os.getenv('ANDROID_SERIAL', None) or None,
'endian': 'little',
'kernel': None,
@@ -1146,6 +1147,15 @@ class ContextType(object):
return command
@_validator
def buffer_size(self, size):
"""Internal buffer size to use for ``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).
"""
return int(size)
@property
def cache_dir(self):
"""Directory used for caching data.
@@ -1185,7 +1195,6 @@ class ContextType(object):
return cache
#*************************************************************************
# ALIASES
#*************************************************************************
@@ -7,6 +7,7 @@ import re
import urllib
from bs4 import BeautifulSoup
from pwn import *
uas = set()
+11
View File
@@ -606,3 +606,14 @@ class MemLeak(object):
return result
return MemLeak(string_wrapper)
# Aliases for convenience
u64 = q
u32 = d
u16 = w
u8 = b
p64 = setq
p32 = setd
p16 = setw
p8 = setb
+6
View File
@@ -22,6 +22,7 @@ import threading
import traceback
from . import termcap
from ..context import ContextType
settings = None
_graphics_mode = False
@@ -127,6 +128,11 @@ def init():
sys.stdout = Wrapper(sys.stdout)
if sys.stderr.isatty():
sys.stderr = Wrapper(sys.stderr)
console = ContextType.defaults['log_console']
if console.isatty():
ContextType.defaults['log_console'] = Wrapper(console)
# freeze all cells if an exception is thrown
orig_hook = sys.excepthook
def hook(*args):
+21 -2
View File
@@ -1,5 +1,8 @@
#!/usr/bin/env python2
from ..context import context
class Buffer(Exception):
"""
List of strings with some helper routines.
@@ -28,10 +31,10 @@ class Buffer(Exception):
The ``0th`` item in the buffer is the oldest item, and
will be received first.
"""
def __init__(self):
def __init__(self, buffer_fill_size = None):
self.data = [] # Buffer
self.size = 0 # Length
self.buffer_fill_size = buffer_fill_size
def __len__(self):
"""
@@ -169,3 +172,19 @@ class Buffer(Exception):
self.size -= len(data)
return data
def get_fill_size(self, size=None):
"""
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.
"""
if size is None:
size = self.buffer_fill_size
with context.local(buffer_size=size):
return context.buffer_size
+2 -4
View File
@@ -20,13 +20,11 @@ class listen(sock):
bindaddr(str): The address to bind to.
fam: The string "any", "ipv4" or "ipv6" or an integer to pass to :func:`socket.getaddrinfo`.
typ: The string "tcp" or "udp" or an integer to pass to :func:`socket.getaddrinfo`.
timeout: A positive number, None
"""
def __init__(self, port=0, bindaddr = "0.0.0.0",
fam = "any", typ = "tcp",
timeout = Timeout.default, level = None):
super(listen, self).__init__(timeout, level = level)
fam = "any", typ = "tcp", *args, **kwargs):
super(listen, self).__init__(*args, **kwargs)
port = int(port)
fam = {socket.AF_INET: 'ipv4',
+6 -7
View File
@@ -44,8 +44,6 @@ class process(tube):
Working directory. Uses the current working directory by default.
env(dict):
Environment variables. By default, inherits from Python's environment.
timeout(int):
Timeout to use on ``tube`` ``recv`` operations.
stdin(int):
File object or file descriptor number to use for ``stdin``.
By default, a pipe is used. A pty can be used instead by setting
@@ -206,11 +204,9 @@ class process(tube):
executable = None,
cwd = None,
env = None,
timeout = Timeout.default,
stdin = PIPE,
stdout = PTY,
stderr = STDOUT,
level = None,
close_fds = True,
preexec_fn = lambda: None,
raw = True,
@@ -218,8 +214,11 @@ class process(tube):
setuid = None,
where = 'local',
display = None,
alarm = None):
super(process, self).__init__(timeout, level = level)
alarm = None,
*args,
**kwargs
):
super(process, self).__init__(*args,**kwargs)
# Permit using context.binary
if argv is None:
@@ -794,7 +793,7 @@ class process(tube):
import pwnlib.elf.corefile
return pwnlib.elf.corefile.Core(filename)
def leak(self, address, count=0):
def leak(self, address, count=1):
"""Leaks memory within the process at the specified address.
Arguments:
+6 -10
View File
@@ -45,8 +45,8 @@ class remote(sock):
def __init__(self, host, port,
fam = "any", typ = "tcp",
timeout = Timeout.default, ssl=False, sock=None, level = None):
super(remote, self).__init__(timeout, level = level)
ssl=False, sock=None, *args, **kwargs):
super(remote, self).__init__(*args, **kwargs)
self.rport = int(port)
self.rhost = host
@@ -150,17 +150,13 @@ class remote(sock):
class tcp(remote):
__doc__ = remote.__doc__
def __init__(self, host, port,
fam = "any", typ = "tcp",
timeout = Timeout.default, ssl=False, sock=None, level = None):
return super(tcp, self).__init__(host, port, fam, typ, timeout, ssl, sock, level)
def __init__(self, host, port, *a, **kw):
return super(tcp, self).__init__(host, port, typ="tcp", *a, **kw)
class udp(remote):
__doc__ = remote.__doc__
def __init__(self, host, port,
fam = "any", typ = "udp",
timeout = Timeout.default, ssl=False, sock=None, level = None):
return super(udp, self).__init__(host, port, fam, typ, timeout, ssl, sock, level)
def __init__(self, host, port, *a, **kw):
return super(udp, self).__init__(host, port, typ="udp", *a, **kw)
class connect(remote):
__doc__ = remote.__doc__
+14 -23
View File
@@ -9,7 +9,6 @@ from . import tube
from .. import context
from .. import term
from ..log import getLogger
from ..timeout import Timeout
log = getLogger(__name__)
@@ -18,10 +17,8 @@ class serialtube(tube.tube):
self, port = None, baudrate = 115200,
convert_newlines = True,
bytesize = 8, parity='N', stopbits=1, xonxoff = False,
rtscts = False, dsrdtr = False,
timeout = Timeout.default,
level = None):
super(serialtube, self).__init__(timeout, level = level)
rtscts = False, dsrdtr = False, *a, **kw):
super(serialtube, self).__init__(*a, **kw)
if port is None:
if platform.system() == 'Darwin':
@@ -49,21 +46,14 @@ class serialtube(tube.tube):
if not self.conn:
raise EOFError
if self.timeout == None:
end = float('inf')
else:
end = time.time() + self.timeout
with self.countdown():
while self.conn and self.countdown_active():
data = self.conn.read(numb)
while self.conn:
data = self.conn.read(numb)
if data:
return data
if data:
return data
delta = end - time.time()
if delta <= 0:
break
else:
time.sleep(min(delta, 0.1))
time.sleep(min(self.timeout, 0.1))
return None
@@ -83,10 +73,11 @@ class serialtube(tube.tube):
pass
def can_recv_raw(self, timeout):
end = time.time()
while time.time() < end:
if self.conn.inWaiting():
return True
with self.countdown(timeout):
while self.conn and self.countdown_active():
if self.conn.inWaiting():
return True
time.sleep(min(self.timeout, 0.1))
return False
def connected_raw(self, direction):
@@ -99,7 +90,7 @@ class serialtube(tube.tube):
def fileno(self):
if not self.connected():
self.error("A stopped program does not have a file number")
self.error("A closed serialtube does not have a file number")
return self.conn.fileno()
+79 -11
View File
@@ -10,8 +10,8 @@ log = getLogger(__name__)
class sock(tube):
"""Methods available exclusively to sockets."""
def __init__(self, timeout, level = None):
super(sock, self).__init__(timeout, level = level)
def __init__(self, *args, **kwargs):
super(sock, self).__init__(*args, **kwargs)
self.closed = {"recv": False, "send": False}
# Overwritten for better usability
@@ -26,13 +26,13 @@ class sock(tube):
else:
return super(sock, self).recvall(timeout)
def recv_raw(self, numb):
def recv_raw(self, numb, *a):
if self.closed["recv"]:
raise EOFError
while True:
try:
data = self.sock.recv(numb)
data = self.sock.recv(numb, *a)
break
except socket.timeout:
return None
@@ -72,21 +72,89 @@ class sock(tube):
self.sock.settimeout(timeout)
def can_recv_raw(self, 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
"""
if not self.sock or self.closed["recv"]:
return False
return select.select([self.sock], [], [], timeout) == ([self.sock], [], [])
# select() will tell us data is available at EOF
can_recv = select.select([self.sock], [], [], timeout) == ([self.sock], [], [])
if not can_recv:
return False
# Ensure there's actually data, not just EOF
try:
self.recv_raw(1, socket.MSG_PEEK)
except EOFError:
return False
return True
def connected_raw(self, direction):
"""
Tests:
>>> l = listen()
>>> r = remote('localhost', l.lport)
>>> r.connected()
True
>>> l.close()
>>> time.sleep(1) # Avoid race condition
>>> r.connected()
False
"""
# If there's no socket, it's definitely closed
if not self.sock:
return False
if direction == 'any':
return True
elif direction == 'recv':
return not self.closed['recv']
elif direction == 'send':
return not self.closed['send']
# If we have noticed a connection close in a given direction before,
# return fast.
if self.closed.get(direction, False):
return False
# If a connection is closed in all manners, return fast
if all(self.closed.values()):
return False
# Use poll() to determine the connection state
want = {
'recv': select.POLLIN,
'send': select.POLLOUT,
'any': select.POLLIN | select.POLLOUT,
}[direction]
poll = select.poll()
poll.register(self, want | select.POLLHUP | select.POLLERR)
for fd, event in poll.poll(0):
if event & select.POLLHUP:
self.close()
return False
if event & select.POLLIN:
return True
if event & select.POLLOUT:
return True
return True
def close(self):
if not getattr(self, 'sock', None):
+38 -18
View File
@@ -59,7 +59,7 @@ class ssh_channel(sock):
#: Only valid when instantiated through :meth:`ssh.process`
pid = None
#: Executable of the process
#: Executable of the procesks
#: Only valid when instantiated through :meth:`ssh.process`
executable = None
@@ -67,8 +67,8 @@ class ssh_channel(sock):
#: Only valid when instantiated through :meth:`ssh.process`
argv = None
def __init__(self, parent, process = None, tty = False, wd = None, env = None, timeout = Timeout.default, level = 0, raw = True):
super(ssh_channel, self).__init__(timeout, level=level)
def __init__(self, parent, process = None, tty = False, wd = None, env = None, raw = True, *args, **kwargs):
super(ssh_channel, self).__init__(*args, **kwargs)
# keep the parent from being garbage collected in some cases
self.parent = parent
@@ -191,11 +191,11 @@ class ssh_channel(sock):
return self.returncode
def can_recv_raw(self, timeout):
end = time.time() + timeout
while time.time() < end:
if self.sock.recv_ready():
return True
time.sleep(0.05)
with self.countdown(timeout):
while self.countdown_active():
if self.sock.recv_ready():
return True
time.sleep(min(self.timeout, 0.05))
return False
def interactive(self, prompt = term.text.bold_red('$') + ' '):
@@ -366,8 +366,8 @@ class ssh_channel(sock):
return e
class ssh_connecter(sock):
def __init__(self, parent, host, port, timeout = Timeout.default, level = None):
super(ssh_connecter, self).__init__(timeout, level = level)
def __init__(self, parent, host, port, *a, **kw):
super(ssh_connecter, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
@@ -398,8 +398,8 @@ class ssh_connecter(sock):
class ssh_listener(sock):
def __init__(self, parent, bind_address, port, timeout = Timeout.default, level = None):
super(ssh_listener, self).__init__(timeout, level = level)
def __init__(self, parent, bind_address, port, *a, **kw):
super(ssh_listener, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
@@ -478,8 +478,7 @@ class ssh(Timeout, Logger):
def __init__(self, user, host, port = 22, password = None, key = None,
keyfile = None, proxy_command = None, proxy_sock = None,
timeout = Timeout.default, level = None, cache = True,
ssh_agent = False):
level = None, cache = True, ssh_agent = False, *a, **kw):
"""Creates a new ssh connection.
Arguments:
@@ -498,7 +497,7 @@ class ssh(Timeout, Logger):
NOTE: The proxy_command and proxy_sock arguments is only available if a
fairly new version of paramiko is used."""
super(ssh, self).__init__(timeout)
super(ssh, self).__init__(*a, **kw)
Logger.__init__(self)
if level is not None:
@@ -623,7 +622,8 @@ class ssh(Timeout, Logger):
return self.run(shell, tty, timeout = timeout)
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):
stdin=0, stdout=1, stderr=2, preexec_fn=None, preexec_args=[], raw=True, aslr=None, setuid=None,
shell=False):
r"""
Executes a process on the remote server, in the same fashion
as pwnlib.tubes.process.process.
@@ -680,6 +680,8 @@ class ssh(Timeout, Logger):
See ``pwnlib.tubes.process.process`` for more information.
setuid(bool):
See ``pwnlib.tubes.process.process`` for more information.
shell(bool):
Pass the command-line arguments to the shell.
Returns:
A new SSH channel, or a path to a script if ``run=False``.
@@ -737,6 +739,9 @@ class ssh(Timeout, Logger):
Traceback (most recent call last):
...
NameError: global name 'bar' is not defined
>>> s.process('echo hello', shell=True).recvall()
'hello\n'
"""
if not argv and not executable:
self.error("Must specify argv or executable")
@@ -750,6 +755,11 @@ class ssh(Timeout, Logger):
if not isinstance(argv, (list, tuple)):
self.error('argv must be a list or tuple')
if shell:
if len(argv) != 1:
self.error('Cannot provide more than 1 argument if shell=True')
argv = ['/bin/sh', '-c'] + argv
# Python doesn't like when an arg in argv contains '\x00'
# -> execve() arg 2 must contain only strings
for i, arg in enumerate(argv):
@@ -862,6 +872,13 @@ if not %(aslr)r:
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
# Attempt to dump ALL core file regions
try:
with open('/proc/self/coredump_filter', 'w') as core_filter:
core_filter.write('0x3f\n')
except Exception:
pass
# Assume that the user would prefer to have core dumps.
resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))
@@ -941,7 +958,7 @@ os.execve(exe, argv, os.environ)
return result
def system(self, process, tty = True, wd = None, env = None, timeout = Timeout.default, raw = True):
def system(self, process, tty = True, wd = None, env = None, timeout = None, raw = True):
r"""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,
@@ -967,7 +984,10 @@ os.execve(exe, argv, os.environ)
if wd is None:
wd = self.cwd
return ssh_channel(self, process, tty, wd, env, timeout, level = self.level, raw = raw)
if timeout is None:
timeout = self.timeout
return ssh_channel(self, process, tty, wd, env, timeout = timeout, level = self.level, raw = raw)
#: Backward compatibility. Use :meth:`system`
run = system
+7 -5
View File
@@ -30,18 +30,18 @@ class tube(Timeout, Logger):
#: and related functions.
newline = '\n'
def __init__(self, timeout = default, level = None):
def __init__(self, timeout = default, level = None, *a, **kw):
super(tube, self).__init__(timeout)
Logger.__init__(self, None)
if level is not None:
self.setLevel(level)
self.buffer = Buffer()
self.buffer = Buffer(*a, **kw)
atexit.register(self.close)
# Functions based on functions from subclasses
def recv(self, numb = 4096, timeout = default):
def recv(self, numb = None, timeout = default):
r"""recv(numb = 4096, timeout = default) -> str
Receives up to `numb` bytes of data from the tube, and returns
@@ -72,6 +72,7 @@ class tube(Timeout, Logger):
[...] Received 0xc bytes:
'Hello, world'
"""
numb = self.buffer.get_fill_size(numb)
return self._recv(numb, timeout) or ''
def unrecv(self, data):
@@ -122,7 +123,7 @@ class tube(Timeout, Logger):
data = ''
with self.local(timeout):
data = self.recv_raw(4096)
data = self.recv_raw(self.buffer.get_fill_size())
if data and self.isEnabledFor(logging.DEBUG):
self.debug('Received %#x bytes:' % len(data))
@@ -141,12 +142,13 @@ class tube(Timeout, Logger):
return data
def _recv(self, numb = 4096, timeout = default):
def _recv(self, numb = None, timeout = default):
"""_recv(numb = 4096, timeout = default) -> str
Receives one chunk of from the internal buffer or from the OS if the
buffer is empty.
"""
numb = self.buffer.get_fill_size(numb)
data = ''
# No buffered data, could not put anything in the buffer
+3 -61
View File
@@ -2,19 +2,14 @@ import errno
import socket
import time
import psutil
from .. import tubes
from ..log import getLogger
try:
import psutil
_ok_import = True
except ImportError:
_ok_import = False
log = getLogger(__name__)
if _ok_import:
all_pids = psutil.pids
all_pids = psutil.pids
def pidof(target):
"""pidof(target) -> int list
@@ -305,56 +300,3 @@ def wait_for_debugger(pid):
while tracer(pid) is None:
time.sleep(0.01)
l.success()
if not _ok_import:
def _make_stub(func):
func.__doc__ = 'Stubbed out function, because psutil is not available.'
return func
@_make_stub
def all_pids():
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def pidof(target):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def pid_by_name(name):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def name(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def parent(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def children(ppid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def ancestors(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def descendants(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def exe(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def cwd(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def cmdline(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
@_make_stub
def starttime(pid):
log.error("Called stubbed-out function. Get psutil to work on your platform, then come back.")
+1 -1
View File
@@ -1 +1 @@
__version__ = '3.3.0'
__version__ = '3.4.0beta0'
+3 -6
View File
@@ -54,11 +54,8 @@ install_requires = ['paramiko>=1.15.2',
'pysocks',
'python-dateutil',
'pypandoc',
'packaging']
# This is a hack until somebody ports psutil to OpenBSD
if platform.system() != 'OpenBSD':
install_requires.append('psutil>=2.1.3')
'packaging',
'psutil>=3.3.0']
# Check that the user has installed the Python development headers
PythonH = os.path.join(get_python_inc(), 'Python.h')
@@ -83,7 +80,7 @@ except ImportError:
setup(
name = 'pwntools',
packages = find_packages(),
version = '3.3.0',
version = '3.4.0beta0',
data_files = [('',
glob.glob('*.md') + glob.glob('*.txt')),
],