1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import ctypes
import errno
import logging
import os
import select
import signal
import stat
import subprocess
import sys
import time
from collections import namedtuple
IS_WINDOWS = sys.platform.startswith('win')
if IS_WINDOWS:
import queue
import threading
else:
import fcntl
import pty
import resource
import tty
from pwnlib import qemu
from pwnlib.context import context
from pwnlib.log import getLogger
from pwnlib.timeout import Timeout
from pwnlib.tubes.tube import tube
from pwnlib.util.hashes import sha256file
from pwnlib.util.misc import parse_ldd_output
from pwnlib.util.misc import which
from pwnlib.util.misc import normalize_argv_env
from pwnlib.util.packing import _decode
log = getLogger(__name__)
class PTY(object): pass
PTY=PTY()
STDOUT = subprocess.STDOUT
PIPE = subprocess.PIPE
signal_names = {-v:k for k,v in signal.__dict__.items() if k.startswith('SIG')}
class process(tube):
r"""
Spawns a new process, and wraps it with a tube for communication.
Arguments:
argv(list):
List of arguments to pass to the spawned process.
shell(bool):
Set to `True` to interpret `argv` as a string
to pass to the shell for interpretation instead of as argv.
executable(str):
Path to the binary to execute. If :const:`None`, uses ``argv[0]``.
Cannot be used with ``shell``.
cwd(str):
Working directory. Uses the current working directory by default.
env(dict):
Environment variables to add to the environment.
ignore_environ(bool):
Ignore Python's environment. By default use Python's environment iff env not specified.
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
this to ``PTY``. This will cause programs to behave in an
interactive manner (e.g.., ``python`` will show a ``>>>`` prompt).
If the application reads from ``/dev/tty`` directly, use a pty.
stdout(int):
File object or file descriptor number to use for ``stdout``.
By default, a pty is used so that any stdout buffering by libc
routines is disabled.
May also be ``PIPE`` to use a normal pipe.
stderr(int):
File object or file descriptor number to use for ``stderr``.
By default, ``STDOUT`` is used.
May also be ``PIPE`` to use a separate pipe,
although the :class:`pwnlib.tubes.tube.tube` wrapper will not be able to read this data.
close_fds(bool):
Close all open file descriptors except stdin, stdout, stderr.
By default, :const:`True` is used.
preexec_fn(callable):
Callable to invoke immediately before calling ``execve``.
raw(bool):
Set the created pty to raw mode (i.e. disable echo and control
characters). :const:`True` by default. If no pty is created, this
has no effect.
aslr(bool):
If set to :const:`False`, disable ASLR via ``personality`` (``setarch -R``)
and ``setrlimit`` (``ulimit -s unlimited``).
This disables ASLR for the target process. However, the ``setarch``
changes are lost if a ``setuid`` binary is executed.
The default value is inherited from ``context.aslr``.
See ``setuid`` below for additional options and information.
setuid(bool):
Used to control `setuid` status of the target binary, and the
corresponding actions taken.
By default, this value is :const:`None`, so no assumptions are made.
If :const:`True`, treat the target binary as ``setuid``.
This modifies the mechanisms used to disable ASLR on the process if
``aslr=False``.
This is useful for debugging locally, when the exploit is a
``setuid`` binary.
If :const:`False`, prevent ``setuid`` bits from taking effect on the
target binary. This is only supported on Linux, with kernels v3.5
or greater.
where(str):
Where the process is running, used for logging purposes.
display(list):
List of arguments to display, instead of the main executable name.
alarm(int):
Set a SIGALRM alarm timeout on the process.
creationflags(int):
Windows only. Flags to pass to ``CreateProcess``.
Examples:
>>> p = process('python3')
>>> p.sendline(b"print('Hello world')")
>>> p.sendline(b"print('Wow, such data')")
>>> b'' == p.recv(timeout=0.01)
True
>>> p.shutdown('send')
>>> p.proc.stdin.closed
True
>>> p.connected('send')
False
>>> p.recvline()
b'Hello world\n'
>>> p.recvuntil(b',')
b'Wow,'
>>> p.recvregex(b'.*data')
b' such data'
>>> p.recv()
b'\n'
>>> p.recv() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
EOFError
>>> p = process('cat')
>>> d = open('/dev/urandom', 'rb').read(4096)
>>> p.recv(timeout=0.1)
b''
>>> p.write(d)
>>> p.recvrepeat(0.1) == d
True
>>> p.recv(timeout=0.1)
b''
>>> p.shutdown('send')
>>> p.wait_for_close()
>>> p.poll()
0
>>> p = process('cat /dev/zero | head -c8', shell=True, stderr=open('/dev/null', 'w+b'))
>>> p.recv()
b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> p = process(['python3','-c','import os; print(os.read(2,1024).decode())'],
... preexec_fn = lambda: os.dup2(0,2))
>>> p.sendline(b'hello')
>>> p.recvline()
b'hello\n'
>>> stack_smashing = ['python3','-c','open("/dev/tty","wb").write(b"stack smashing detected")']
>>> process(stack_smashing).recvall()
b'stack smashing detected'
>>> process(stack_smashing, stdout=PIPE).recvall()
b''
>>> getpass = ['python3','-c','import getpass; print(getpass.getpass("XXX"))']
>>> p = process(getpass, stdin=PTY)
>>> p.recv()
b'XXX'
>>> p.sendline(b'hunter2')
>>> p.recvall()
b'\nhunter2\n'
>>> process('echo hello 1>&2', shell=True).recvall()
b'hello\n'
>>> process('echo hello 1>&2', shell=True, stderr=PIPE).recvall()
b''
>>> a = process(['cat', '/proc/self/maps']).recvall()
>>> b = process(['cat', '/proc/self/maps'], aslr=False).recvall()
>>> with context.local(aslr=False):
... c = process(['cat', '/proc/self/maps']).recvall()
>>> a == b
False
>>> b == c
True
>>> process(['sh','-c','ulimit -s'], aslr=0).recvline()
b'unlimited\n'
>>> io = process(['sh','-c','sleep 10; exit 7'], alarm=2)
>>> io.poll(block=True) == -signal.SIGALRM
True
>>> binary = ELF.from_assembly('nop', arch='mips')
>>> p = process(binary.path)
>>> binary_dir, binary_name = os.path.split(binary.path)
>>> p = process('./{}'.format(binary_name), cwd=binary_dir)
>>> p = process(binary.path, cwd=binary_dir)
>>> p = process('./{}'.format(binary_name), cwd=os.path.relpath(binary_dir))
>>> p = process(binary.path, cwd=os.path.relpath(binary_dir))
"""
STDOUT = STDOUT
PIPE = PIPE
PTY = PTY
#: Have we seen the process stop? If so, this is a unix timestamp.
_stop_noticed = 0
proc = None
def __init__(self, argv = None,
shell = False,
executable = None,
cwd = None,
env = None,
ignore_environ = None,
stdin = PIPE,
stdout = PTY if not IS_WINDOWS else PIPE,
stderr = STDOUT,
close_fds = True,
preexec_fn = lambda: None,
raw = True,
aslr = None,
setuid = None,
where = 'local',
display = None,
alarm = None,
creationflags = 0,
*args,
**kwargs
):
super(process, self).__init__(*args,**kwargs)
# Permit using context.binary
if argv is None:
if context.binary:
argv = [context.binary.path]
else:
raise TypeError('Must provide argv or set context.binary')
if IS_WINDOWS and PTY in (stdin, stdout, stderr):
raise NotImplementedError("ConPTY isn't implemented yet")
#: :class:`subprocess.Popen` object that backs this process
self.proc = None
# We need to keep a copy of the un-_validated environment for printing
original_env = env
if shell:
executable_val, argv_val, env_val = executable, argv, env
if executable is None:
if IS_WINDOWS:
executable_val = os.environ.get('ComSpec', 'cmd.exe')
else:
executable_val = '/bin/sh'
else:
executable_val, argv_val, env_val = self._validate(cwd, executable, argv, env)
# Avoid the need to have to deal with the STDOUT magic value.
if stderr is STDOUT:
stderr = stdout
if IS_WINDOWS:
self.pty = None
self.raw = False
self.aslr = True
self._setuid = False
self.suid = self.uid = None
self.sgid = self.gid = None
internal_preexec_fn = None
else:
# Determine which descriptors will be attached to a new PTY
handles = (stdin, stdout, stderr)
#: Which file descriptor is the controlling TTY
self.pty = handles.index(PTY) if PTY in handles else None
#: Whether the controlling TTY is set to raw mode
self.raw = raw
#: Whether ASLR should be left on
self.aslr = aslr if aslr is not None else context.aslr
#: Whether setuid is permitted
self._setuid = setuid if setuid is None else bool(setuid)
# Create the PTY if necessary
stdin, stdout, stderr, master, slave = self._handles(*handles)
internal_preexec_fn = self.__preexec_fn
#: Arguments passed on argv
self.argv = argv_val
#: Full path to the executable
self.executable = executable_val
if ignore_environ is None:
ignore_environ = env is not None # compat
#: Environment passed on envp
self.env = {} if ignore_environ else dict(getattr(os, "environb", os.environ))
# Add environment variables as needed
self.env.update(env_val or {})
self._cwd = os.path.realpath(cwd or os.path.curdir)
#: Alarm timeout of the process
self.alarm = alarm
self.preexec_fn = preexec_fn
self.display = display or self.program
self._qemu = False
self._corefile = None
message = "Starting %s process %r" % (where, self.display)
if self.isEnabledFor(logging.DEBUG):
if argv != [self.executable]: message += ' argv=%r ' % self.argv
if original_env not in (os.environ, None): message += ' env=%r ' % self.env
with self.progress(message) as p:
if not self.aslr:
self.warn_once("ASLR is disabled!")
# In the event the binary is a foreign architecture,
# and binfmt is not installed (e.g. when running on
# Travis CI), re-try with qemu-XXX if we get an
# 'Exec format error'.
prefixes = [([], self.executable)]
exception = None
for prefix, executable in prefixes:
try:
args = self.argv
if prefix:
args = prefix + args
self.proc = subprocess.Popen(args = args,
shell = shell,
executable = executable,
cwd = cwd,
env = self.env,
stdin = stdin,
stdout = stdout,
stderr = stderr,
close_fds = close_fds,
preexec_fn = internal_preexec_fn,
creationflags = creationflags)
break
except OSError as exception:
if exception.errno != errno.ENOEXEC:
raise
prefixes.append(self.__on_enoexec(exception))
p.success('pid %i' % self.pid)
if IS_WINDOWS:
self._read_thread = None
self._read_queue = queue.Queue()
if self.proc.stdout:
# Read from stdout in a thread
self._read_thread = threading.Thread(target=_read_in_thread, args=(self._read_queue, self.proc.stdout))
self._read_thread.daemon = True
self._read_thread.start()
return
if self.pty is not None:
if stdin is slave:
self.proc.stdin = os.fdopen(os.dup(master), 'r+b', 0)
if stdout is slave:
self.proc.stdout = os.fdopen(os.dup(master), 'r+b', 0)
if stderr is slave:
self.proc.stderr = os.fdopen(os.dup(master), 'r+b', 0)
os.close(master)
os.close(slave)
# Set in non-blocking mode so that a call to call recv(1000) will
# return as soon as a the first byte is available
if self.proc.stdout:
fd = self.proc.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# Save off information about whether the binary is setuid / setgid
self.suid = self.uid = os.getuid()
self.sgid = self.gid = os.getgid()
st = os.stat(self.executable)
if self._setuid:
if (st.st_mode & stat.S_ISUID):
self.suid = st.st_uid
if (st.st_mode & stat.S_ISGID):
self.sgid = st.st_gid
def __preexec_fn(self):
"""
Routine executed in the child process before invoking execve().
Handles setting the controlling TTY as well as invoking the user-
supplied preexec_fn.
"""
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 = 0x0040000
ctypes.CDLL('libc.so.6').personality(ADDR_NO_RANDOMIZE)
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
except Exception:
self.exception("Could not disable ASLR")
# Assume that the user would prefer to have core dumps.
try:
resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))
except Exception:
pass
# Given that we want a core file, assume that we want the whole thing.
try:
with open('/proc/self/coredump_filter', 'w') as f:
f.write('0xff')
except Exception:
pass
if self._setuid is False:
try:
PR_SET_NO_NEW_PRIVS = 38
ctypes.CDLL('libc.so.6').prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
except Exception:
pass
# Avoid issues with attaching to processes when yama-ptrace is set
try:
PR_SET_PTRACER = 0x59616d61
PR_SET_PTRACER_ANY = -1
ctypes.CDLL('libc.so.6').prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0)
except Exception:
pass
if self.alarm is not None:
signal.alarm(self.alarm)
self.preexec_fn()
def __on_enoexec(self, exception):
"""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.
"""
# Get the ELF binary for the target executable
with context.quiet:
# XXX: Cyclic imports :(
from pwnlib.elf import ELF
binary = ELF(self.executable)
# If we're on macOS, this will never work. Bail now.
# if platform.mac_ver()[0]:
# self.error("Cannot run ELF binaries on macOS")
# Determine what architecture the binary is, and find the
# appropriate qemu binary to run it.
qemu_path = qemu.user_path(arch=binary.arch)
if not qemu_path:
raise exception
qemu_path = which(qemu_path)
if qemu_path:
self._qemu = qemu_path
args = [qemu_path]
if self.argv:
args += ['-0', self.argv[0]]
args += ['--']
return [args, qemu_path]
# If we get here, we couldn't run the binary directly, and
# we don't have a qemu which can run it.
self.exception(exception)
@property
def program(self):
"""Alias for ``executable``, for backward compatibility.
Example:
>>> p = process('/bin/true')
>>> p.executable == '/bin/true'
True
>>> p.executable == p.program
True
"""
return self.executable
@property
def cwd(self):
"""Directory that the process is working in.
Example:
>>> p = process('sh')
>>> p.sendline(b'cd /tmp; echo AAA')
>>> _ = p.recvuntil(b'AAA')
>>> p.cwd == '/tmp'
True
>>> p.sendline(b'cd /proc; echo BBB;')
>>> _ = p.recvuntil(b'BBB')
>>> p.cwd
'/proc'
"""
try:
from pwnlib.util.proc import cwd
self._cwd = cwd(self.pid)
except Exception:
pass
return self._cwd
def _validate(self, cwd, executable, argv, env):
"""
Perform extended validation on the executable path, argv, and envp.
Mostly to make Python happy, but also to prevent common pitfalls.
"""
orig_cwd = cwd
cwd = cwd or os.path.curdir
argv, env = normalize_argv_env(argv, env, self, 4)
if env:
if sys.platform == 'win32':
# Windows requires that all environment variables be strings
env = {_decode(k): _decode(v) for k, v in env}
else:
env = {bytes(k): bytes(v) for k, v in env}
if argv:
argv = list(map(bytes, argv))
#
# Validate executable
#
# - Must be an absolute or relative path to the target executable
# - If not, attempt to resolve the name in $PATH
#
if not executable:
if not argv:
self.error("Must specify argv or executable")
executable = argv[0]
if not isinstance(executable, str):
executable = executable.decode('utf-8')
path = env and env.get(b'PATH')
if path:
path = path.decode()
else:
path = os.environ.get('PATH')
# Do not change absolute paths to binaries
if executable.startswith(os.path.sep):
pass
# If there's no path component, it's in $PATH or relative to the
# target directory.
#
# For example, 'sh'
elif os.path.sep not in executable and which(executable, path=path):
executable = which(executable, path=path)
# Either there is a path component, or the binary is not in $PATH
# For example, 'foo/bar' or 'bar' with cwd=='foo'
elif os.path.sep not in executable:
tmp = executable
executable = os.path.join(cwd, executable)
self.warn_once("Could not find executable %r in $PATH, using %r instead" % (tmp, executable))
# There is a path component and user specified a working directory,
# it must be relative to that directory. For example, 'bar/baz' with
# cwd='foo' or './baz' with cwd='foo/bar'
elif orig_cwd:
executable = os.path.join(orig_cwd, executable)
if not os.path.exists(executable):
self.error("%r does not exist" % executable)
if not os.path.isfile(executable):
self.error("%r is not a file" % executable)
if not os.access(executable, os.X_OK):
self.error("%r is not marked as executable (+x)" % executable)
return executable, argv, env
def _handles(self, stdin, stdout, stderr):
master = slave = None
if self.pty is not None:
# Normally we could just use PIPE and be happy.
# Unfortunately, this results in undesired behavior when
# printf() and similar functions buffer data instead of
# sending it directly.
#
# By opening a PTY for STDOUT, the libc routines will not
# buffer any data on STDOUT.
master, slave = pty.openpty()
if self.raw:
# By giving the child process a controlling TTY,
# the OS will attempt to interpret terminal control codes
# like backspace and Ctrl+C.
#
# If we don't want this, we set it to raw mode.
tty.setraw(master)
tty.setraw(slave)
if stdin is PTY:
stdin = slave
if stdout is PTY:
stdout = slave
if stderr is PTY:
stderr = slave
return stdin, stdout, stderr, master, slave
def __getattr__(self, attr):
"""Permit pass-through access to the underlying process object for
fields like ``pid`` and ``stdin``.
"""
if not attr.startswith('_') and hasattr(self.proc, attr):
return getattr(self.proc, attr)
raise AttributeError("'process' object has no attribute '%s'" % attr)
def kill(self):
"""kill()
Kills the process.
"""
self.close()
def poll(self, block = False):
"""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.
"""
# In order to facilitate retrieving core files, force an update
# to the current working directory
_ = self.cwd
if block:
self.wait_for_close()
self.proc.poll()
returncode = self.proc.returncode
if returncode is not None and not self._stop_noticed:
self._stop_noticed = time.time()
signame = ''
if returncode < 0:
signame = ' (%s)' % (signal_names.get(returncode, 'SIG???'))
self.info("Process %r stopped with exit code %d%s (pid %i)" % (self.display,
returncode,
signame,
self.pid))
return returncode
def communicate(self, stdin = None):
"""communicate(stdin = None) -> str
Calls :meth:`subprocess.Popen.communicate` method on the process.
"""
return self.proc.communicate(stdin)
# Implementation of the methods required for tube
def recv_raw(self, numb):
# This is a slight hack. We try to notice if the process is
# dead, so we can write a message.
self.poll()
if not self.connected_raw('recv'):
raise EOFError
if not self.can_recv_raw(self.timeout):
return ''
if IS_WINDOWS:
data = b''
count = 0
while count < numb:
if self._read_queue.empty():
break
last_byte = self._read_queue.get(block=False)
data += last_byte
count += 1
return data
# This will only be reached if we either have data,
# or we have reached an EOF. In either case, it
# should be safe to read without expecting it to block.
data = ''
try:
data = self.proc.stdout.read(numb)
except IOError:
pass
if not data:
self.shutdown("recv")
raise EOFError
return data
def send_raw(self, data):
# This is a slight hack. We try to notice if the process is
# dead, so we can write a message.
self.poll()
if not self.connected_raw('send'):
raise EOFError
try:
self.proc.stdin.write(data)
self.proc.stdin.flush()
except IOError:
raise EOFError
def settimeout_raw(self, timeout):
pass
def can_recv_raw(self, timeout):
if not self.connected_raw('recv'):
return False
if IS_WINDOWS:
with self.countdown(timeout=timeout):
while self.timeout and self._read_queue.empty():
time.sleep(0.01)
return not self._read_queue.empty()
try:
if timeout is None:
return select.select([self.proc.stdout], [], []) == ([self.proc.stdout], [], [])
return select.select([self.proc.stdout], [], [], timeout) == ([self.proc.stdout], [], [])
except ValueError:
# Not sure why this isn't caught when testing self.proc.stdout.closed,
# but it's not.
#
# File "/home/user/pwntools/pwnlib/tubes/process.py", line 112, in can_recv_raw
# return select.select([self.proc.stdout], [], [], timeout) == ([self.proc.stdout], [], [])
# ValueError: I/O operation on closed file
raise EOFError
except select.error as v:
if v.args[0] == errno.EINTR:
return False
def connected_raw(self, direction):
if direction == 'any':
return self.poll() is None
elif direction == 'send':
return self.proc.stdin and not self.proc.stdin.closed
elif direction == 'recv':
return self.proc.stdout and not self.proc.stdout.closed
def close(self):
if self.proc is None:
return
# First check if we are already dead
self.poll()
if not self._stop_noticed:
try:
self.proc.kill()
self.proc.wait()
self._stop_noticed = time.time()
self.info('Stopped process %r (pid %i)' % (self.program, self.pid))
except OSError:
pass
# close file descriptors
for fd in [self.proc.stdin, self.proc.stdout, self.proc.stderr]:
if fd is not None:
try:
fd.close()
except IOError as e:
if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
raise
def fileno(self):
if not self.connected():
self.error("A stopped process does not have a file number")
return self.proc.stdout.fileno()
def shutdown_raw(self, direction):
if direction == "send":
self.proc.stdin.close()
if direction == "recv":
self.proc.stdout.close()
if all(fp is None or fp.closed for fp in [self.proc.stdin, self.proc.stdout]):
self.close()
def __pty_make_controlling_tty(self, tty_fd):
'''This makes the pseudo-terminal the controlling tty. This should be
more portable than the pty.fork() function. Specifically, this should
work on Solaris. '''
child_name = os.ttyname(tty_fd)
# Disconnect from controlling tty. Harmless if not already connected.
try:
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
if fd >= 0:
os.close(fd)
# which exception, shouldnt' we catch explicitly .. ?
except OSError:
# Already disconnected. This happens if running inside cron.
pass
os.setsid()
# Verify we are disconnected from controlling tty
# by attempting to open it again.
try:
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
if fd >= 0:
os.close(fd)
raise Exception('Failed to disconnect from '
'controlling tty. It is still possible to open /dev/tty.')
# which exception, shouldnt' we catch explicitly .. ?
except OSError:
# Good! We are disconnected from a controlling tty.
pass
# Verify we can open child pty.
fd = os.open(child_name, os.O_RDWR)
if fd < 0:
raise Exception("Could not open child pty, " + child_name)
else:
os.close(fd)
# Verify we now have a controlling tty.
fd = os.open("/dev/tty", os.O_WRONLY)
if fd < 0:
raise Exception("Could not open controlling tty, /dev/tty")
else:
os.close(fd)
def maps(self):
"""maps() -> [mapping]
Returns a list of process mappings.
A mapping object has the following fields:
addr, address (addr alias), start (addr alias), end, size, perms, path, rss, pss, shared_clean, shared_dirty, private_clean, private_dirty, referenced, anonymous, swap
perms is a permissions object, with the following fields:
read, write, execute, private, shared, string
Example:
>>> p = process(['cat'])
>>> p.sendline(b"meow")
>>> p.recvline()
b'meow\\n'
>>> proc_maps = open("/proc/" + str(p.pid) + "/maps", "r").readlines()
>>> pwn_maps = p.maps()
>>> len(proc_maps) == len(pwn_maps)
True
>>> checker_arr = []
>>> for proc, pwn in zip(proc_maps, pwn_maps):
... proc = proc.split(' ')
... p_addrs = proc[0].split('-')
... checker_arr.append(int(p_addrs[0], 16) == pwn.addr == pwn.address == pwn.start)
... checker_arr.append(int(p_addrs[1], 16) == pwn.end)
... checker_arr.append(pwn.size == pwn.end - pwn.start)
... checker_arr.append(pwn.perms.string == proc[1])
... proc_path = proc[-1].strip()
... checker_arr.append(pwn.path == proc_path or (pwn.path == '[anon]' and proc_path == ''))
...
>>> checker_arr == [True] * len(proc_maps) * 5
True
"""
"""
Useful information about this can be found at: https://man7.org/linux/man-pages/man5/proc.5.html
specifically the /proc/pid/maps section.
memory_maps() returns a list of pmmap_ext objects
The definition (from psutil/_pslinux.py) is:
pmmap_grouped = namedtuple(
'pmmap_grouped',
['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
pmmap_ext = namedtuple(
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
Here is an example of a pmmap_ext entry:
pmmap_ext(addr='15555551c000-155555520000', perms='r--p', path='[vvar]', rss=0, size=16384, pss=0, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=0, referenced=0, anonymous=0, swap=0)
"""
permissions = namedtuple("permissions", "read write execute private shared string")
mapping = namedtuple("mapping",
"addr address start end size perms path rss pss shared_clean shared_dirty private_clean private_dirty referenced anonymous swap")
# addr = address (alias) = start (alias)
from pwnlib.util.proc import memory_maps
raw_maps = memory_maps(self.pid)
maps = []
# raw_mapping
for r_m in raw_maps:
p_perms = permissions('r' in r_m.perms, 'w' in r_m.perms, 'x' in r_m.perms, 'p' in r_m.perms, 's' in r_m.perms, r_m.perms)
addr_split = r_m.addr.split('-')
p_addr = int(addr_split[0], 16)
p_mapping = mapping(p_addr, p_addr, p_addr, int(addr_split[1], 16), r_m.size, p_perms, r_m.path, r_m.rss,
r_m.pss, r_m.shared_clean, r_m.shared_dirty, r_m.private_clean, r_m.private_dirty,
r_m.referenced, r_m.anonymous, r_m.swap)
maps.append(p_mapping)
return maps
def get_mapping(self, path_value, single=True):
"""get_mapping(path_value, single=True) -> mapping
get_mapping(path_value, False) -> [mapping]
Arguments:
path_value(str): The exact path of the requested mapping,
valid values are also [stack], [heap], etc..
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns found mapping(s) in process memory according to
path_value.
Example:
>>> p = process(['cat'])
>>> mapping = p.get_mapping('[stack]')
>>> mapping.path == '[stack]'
True
>>> mapping.perms.execute
False
>>>
>>> mapping = p.get_mapping('does not exist')
>>> print(mapping)
None
>>>
>>> mappings = p.get_mapping(which('cat'), single=False)
>>> len(mappings) > 1
True
"""
all_maps = self.maps()
if single:
for mapping in all_maps:
if path_value == mapping.path:
return mapping
return None
m_mappings = []
for mapping in all_maps:
if path_value == mapping.path:
m_mappings.append(mapping)
return m_mappings
def stack_mapping(self, single=True):
"""stack_mapping(single=True) -> mapping
stack_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns :meth:`.process.get_mapping` with '[stack]' and single as arguments.
Example:
>>> p = process(['cat'])
>>> mapping = p.stack_mapping()
>>> mapping.path
'[stack]'
>>> mapping.perms.execute
False
>>> mapping.perms.write
True
>>> hex(mapping.address) # doctest: +SKIP
'0x7fffd99fe000'
>>> mappings = p.stack_mapping(single=False)
>>> len(mappings)
1
"""
return self.get_mapping('[stack]', single)
def heap_mapping(self, single=True):
"""heap_mapping(single=True) -> mapping
heap_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns :meth:`.process.get_mapping` with '[heap]' and single as arguments.
Example:
>>> p = process(['cat'])
>>> p.sendline(b'meow')
>>> p.recvline()
b'meow\\n'
>>> mapping = p.heap_mapping()
>>> mapping.path
'[heap]'
>>> mapping.perms.execute
False
>>> mapping.perms.write
True
>>> hex(mapping.address) # doctest: +SKIP
'0x557650fae000'
>>> mappings = p.heap_mapping(single=False)
>>> len(mappings)
1
"""
return self.get_mapping('[heap]', single)
def vdso_mapping(self, single=True):
"""vdso_mapping(single=True) -> mapping
vdso_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns :meth:`.process.get_mapping` with '[vdso]' and single as arguments.
Example:
>>> p = process(['cat'])
>>> mapping = p.vdso_mapping()
>>> mapping.path
'[vdso]'
>>> mapping.perms.execute
True
>>> mapping.perms.write
False
>>> hex(mapping.address) # doctest: +SKIP
'0x7ffcf13af000'
>>> mappings = p.vdso_mapping(single=False)
>>> len(mappings)
1
"""
return self.get_mapping('[vdso]', single)
def vvar_mapping(self, single=True):
"""vvar_mapping(single=True) -> mapping
vvar_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns :meth:`.process.get_mapping` with '[vvar]' and single as arguments.
Example:
>>> p = process(['cat'])
>>> mapping = p.vvar_mapping()
>>> mapping.path
'[vvar]'
>>> mapping.perms.execute
False
>>> mapping.perms.write
False
>>> hex(mapping.address) # doctest: +SKIP
'0x7ffee5f60000'
>>> mappings = p.vvar_mapping(single=False)
>>> len(mappings)
1
"""
return self.get_mapping('[vvar]', single)
def libc_mapping(self, single=True):
"""libc_mapping(single=True) -> mapping
libc_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns either the first libc mapping found in process memory,
or all libc mappings, depending on "single".
Example:
>>> p = process(['cat'])
>>> p.sendline(b'meow')
>>> p.recvline()
b'meow\\n'
>>> mapping = p.libc_mapping()
>>> mapping.path # doctest: +ELLIPSIS
'...libc...'
>>> mapping.perms.execute
False
>>> mapping.perms.write
False
>>> hex(mapping.address) # doctest: +SKIP
'0x7fbde7fd7000'
>>>
>>> mappings = p.libc_mapping(single=False)
>>> len(mappings) > 1
True
>>> hex(mappings[1].address) # doctest: +SKIP
'0x7fbde7ffd000'
>>> mappings[0].end == mappings[1].start
True
>>> mappings[1].perms.execute
True
"""
all_maps = self.maps()
if single:
for mapping in all_maps:
lib_basename = os.path.basename(mapping.path)
if 'libc.so' in lib_basename or ('libc-' in lib_basename and '.so' in lib_basename):
return mapping
return None
l_mappings = []
for mapping in all_maps:
lib_basename = os.path.basename(mapping.path)
if 'libc.so' in lib_basename or ('libc-' in lib_basename and '.so' in lib_basename):
l_mappings.append(mapping)
return l_mappings
def musl_mapping(self, single=True):
"""musl_mapping(single=True) -> mapping
musl_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns either the first musl mapping found in process memory,
or all musl mappings, depending on "single".
"""
all_maps = self.maps()
if single:
for mapping in all_maps:
lib_basename = os.path.basename(mapping.path)
if 'musl.so' in lib_basename or ('musl-' in lib_basename and '.so' in lib_basename):
return mapping
return None
m_mappings = []
for mapping in all_maps:
lib_basename = os.path.basename(mapping.path)
if 'musl.so' in lib_basename or ('musl-' in lib_basename and '.so' in lib_basename):
m_mappings.append(mapping)
return m_mappings
def elf_mapping(self, single=True):
"""elf_mapping(single=True) -> mapping
elf_mapping(False) -> [mapping]
Arguments:
single(bool=True): Whether to only return the first
mapping matched, or all of them.
Returns :meth:`.process.get_mapping` with the :meth:`.process.elf` path and single as arguments.
Example:
>>> p = process(['cat'])
>>> p.sendline(b'meow')
>>> p.recvline()
b'meow\\n'
>>> mapping = p.elf_mapping()
>>> mapping.path # doctest: +ELLIPSIS
'...cat...'
>>> mapping.perms.execute
False
>>> mapping.perms.write
False
>>> hex(mapping.address) # doctest: +SKIP
'0x55a2abba0000'
>>> mappings = p.elf_mapping(single=False)
>>> len(mappings) > 1
True
>>> hex(mappings[1].address) # doctest: +SKIP
'0x55a2abba2000'
>>> mappings[0].end == mappings[1].start
True
>>> mappings[1].perms.execute
True
"""
return self.get_mapping(self.elf.path, single)
def lib_size(self, path_value):
"""lib_size(path_value) -> int
Arguments:
path_value(str): The exact path of the shared library
loaded by the process
Returns the size of the shared library in process memory.
If the library is not found, zero is returned.
Example:
>>> from pwn import *
>>> p = process(['cat'])
>>> libc_size = p.lib_size(p.libc.path)
>>> hex(libc_size) # doctest: +SKIP
'0x1d5000'
>>> libc_mappings = p.libc_mapping(single=False)
>>> libc_size == (libc_mappings[-1].end - libc_mappings[0].start)
True
"""
# Expecting this to be sorted
lib_mappings = self.get_mapping(path_value, single=False)
if len(lib_mappings) == 0:
return 0
is_contiguous = True
total_size = lib_mappings[0].size
for i in range(1, len(lib_mappings)):
total_size += lib_mappings[i].size
if lib_mappings[i].start != lib_mappings[i - 1].end:
is_contiguous = False
if not is_contiguous:
log.warn("lib_size(): %s mappings aren't contiguous" % path_value)
return total_size
def address_mapping(self, address):
"""address_mapping(address) -> mapping
Returns the mapping at the specified address.
Example:
>>> p = process(['cat'])
>>> p.sendline(b'meow')
>>> p.recvline()
b'meow\\n'
>>> libc = p.libc_mapping().address
>>> heap = p.heap_mapping().address
>>> elf = p.elf_mapping().address
>>> p.address_mapping(libc).path # doctest: +ELLIPSIS
'.../libc...'
>>> p.address_mapping(heap + 0x123).path
'[heap]'
>>> p.address_mapping(elf + 0x1234).path # doctest: +ELLIPSIS
'.../cat'
>>> p.address_mapping(elf - 0x1234) == None
True
"""
all_maps = self.maps()
for mapping in all_maps:
if mapping.addr <= address < mapping.end:
return mapping
return None
def libs(self):
"""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.
"""
from pwnlib.util.proc import memory_maps
maps_raw = self.poll() is not None and memory_maps(self.pid)
if not maps_raw:
import pwnlib.elf.elf
with context.quiet:
return pwnlib.elf.elf.ELF(self.executable).maps
# Enumerate all of the libraries actually loaded right now.
maps = {}
for mapping in maps_raw:
path = mapping.path
if os.sep not in path: continue
path = os.path.realpath(path)
if path not in maps:
maps[path]=0
for lib in maps:
path = os.path.realpath(lib)
for mapping in maps_raw:
if mapping.path == path:
address = mapping.addr.split('-')[0]
maps[lib] = int(address, 16)
break
return maps
@property
def libc(self):
"""libc() -> ELF
Returns an ELF for the libc for the current process.
If possible, it is adjusted to the correct address
automatically.
Example:
>>> p = process("/bin/cat")
>>> libc = p.libc
>>> libc # doctest: +SKIP
ELF('/lib64/libc-...so')
>>> p.close()
"""
from pwnlib.elf import ELF
for lib, address in self.libs().items():
lib_basename = os.path.basename(lib)
if 'libc.so' in lib_basename or ('libc-' in lib_basename and '.so' in lib_basename):
e = ELF(lib)
e.address = address
return e
@property
def elf(self):
"""elf() -> pwnlib.elf.elf.ELF
Returns an ELF file for the executable that launched the process.
"""
import pwnlib.elf.elf
return pwnlib.elf.elf.ELF(self.executable)
@property
def corefile(self):
"""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.
"""
# If the process is still alive, try using GDB
import pwnlib.elf.corefile
import pwnlib.gdb
try:
if self.poll() is None:
corefile = pwnlib.gdb.corefile(self)
if corefile is None:
self.error("Could not create corefile with GDB for %s", self.executable)
return corefile
# Handle race condition against the kernel or QEMU to write the corefile
# by waiting up to 5 seconds for it to be written.
t = Timeout()
finder = None
with t.countdown(5):
while t.timeout and (finder is None or not finder.core_path):
finder = pwnlib.elf.corefile.CorefileFinder(self)
time.sleep(0.5)
if not finder.core_path:
self.error("Could not find core file for pid %i" % self.pid)
core_hash = sha256file(finder.core_path)
if self._corefile and self._corefile._hash == core_hash:
return self._corefile
self._corefile = pwnlib.elf.corefile.Corefile(finder.core_path)
except AttributeError as e:
raise RuntimeError(e) # AttributeError would route through __getattr__, losing original message
self._corefile._hash = core_hash
return self._corefile
def leak(self, address, count=1):
r"""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(which('bash-static'))
>>> p = process(e.path)
In order to make sure there's not a race condition against
the process getting set up...
>>> p.sendline(b'echo hello')
>>> p.recvuntil(b'hello')
b'hello'
Now we can leak some data!
>>> p.leak(e.address, 4)
b'\x7fELF'
"""
# If it's running under qemu-user, don't leak anything.
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
readmem = leak
def writemem(self, address, data):
r"""Writes memory within the process at the specified address.
Arguments:
address(int): Address to write memory
data(bytes): Data to write to the address
Example:
Let's write data to the beginning of the mapped memory of the ELF.
>>> context.clear(arch='i386')
>>> address = 0x100000
>>> data = cyclic(32)
>>> assembly = shellcraft.nop() * len(data)
Wait for one byte of input, then write the data to stdout
>>> assembly += shellcraft.write(1, address, 1)
>>> assembly += shellcraft.read(0, 'esp', 1)
>>> assembly += shellcraft.write(1, address, 32)
>>> assembly += shellcraft.exit()
>>> asm(assembly)[32:]
b'j\x01[\xb9\xff\xff\xef\xff\xf7\xd1\x89\xdaj\x04X\xcd\x801\xdb\x89\xe1j\x01Zj\x03X\xcd\x80j\x01[\xb9\xff\xff\xef\xff\xf7\xd1j Zj\x04X\xcd\x801\xdbj\x01X\xcd\x80'
Assemble the binary and test it
>>> elf = ELF.from_assembly(assembly, vma=address)
>>> io = elf.process()
>>> _ = io.recvuntil(b'\x90')
>>> _ = io.writemem(address, data)
>>> io.send(b'X')
>>> io.recvall()
b'aaaabaaacaaadaaaeaaafaaagaaahaaa'
"""
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, 'wb') as mem:
mem.seek(address)
return mem.write(data)
@property
def stdin(self):
"""Shorthand for ``self.proc.stdin``
See: :obj:`.process.proc`
"""
return self.proc.stdin
@property
def stdout(self):
"""Shorthand for ``self.proc.stdout``
See: :obj:`.process.proc`
"""
return self.proc.stdout
@property
def stderr(self):
"""Shorthand for ``self.proc.stderr``
See: :obj:`.process.proc`
"""
return self.proc.stderr
# Keep reading the process's output in a separate thread,
# since there's no non-blocking read in python on Windows.
def _read_in_thread(recv_queue, proc_stdout):
try:
while True:
b = proc_stdout.read(1)
if b:
recv_queue.put(b)
else:
break
except:
# Ignore any errors during Python shutdown
pass
|