pyrasite 2.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyrasite/__init__.py +30 -0
- pyrasite/injector.py +524 -0
- pyrasite/inspector.py +128 -0
- pyrasite/ipc.py +264 -0
- pyrasite/main.py +248 -0
- pyrasite/payloads/__init__.py +0 -0
- pyrasite/payloads/dump_memory.py +14 -0
- pyrasite/payloads/dump_modules.py +4 -0
- pyrasite/payloads/dump_stacks.py +7 -0
- pyrasite/payloads/force_garbage_collection.py +3 -0
- pyrasite/payloads/helloworld.py +1 -0
- pyrasite/payloads/reverse_python_shell.py +31 -0
- pyrasite/payloads/reverse_shell.py +37 -0
- pyrasite/reverse.py +186 -0
- pyrasite/tests/__init__.py +0 -0
- pyrasite/tests/conftest.py +23 -0
- pyrasite/tests/test_cli.py +101 -0
- pyrasite/tests/test_code_injection.py +165 -0
- pyrasite/tests/test_injector.py +88 -0
- pyrasite/tests/test_ipc.py +117 -0
- pyrasite/tests/test_utils.py +18 -0
- pyrasite/tests/utils.py +209 -0
- pyrasite/tools/__init__.py +0 -0
- pyrasite/tools/memory_viewer.py +184 -0
- pyrasite/tools/shell.py +78 -0
- pyrasite/utils.py +38 -0
- pyrasite/win/inject_python.cpp +265 -0
- pyrasite-2.1.0.dist-info/METADATA +163 -0
- pyrasite-2.1.0.dist-info/RECORD +33 -0
- pyrasite-2.1.0.dist-info/WHEEL +5 -0
- pyrasite-2.1.0.dist-info/entry_points.txt +4 -0
- pyrasite-2.1.0.dist-info/licenses/LICENSE +674 -0
- pyrasite-2.1.0.dist-info/top_level.txt +1 -0
pyrasite/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
__version__ = "2.1.0"
|
|
2
|
+
__all__ = (
|
|
3
|
+
"InjectionError",
|
|
4
|
+
"PyrasiteIPC",
|
|
5
|
+
"ReverseConnection",
|
|
6
|
+
"ReversePythonConnection",
|
|
7
|
+
"inject",
|
|
8
|
+
"inspect",
|
|
9
|
+
)
|
|
10
|
+
__license__ = """\
|
|
11
|
+
pyrasite is free software: you can redistribute it and/or modify
|
|
12
|
+
it under the terms of the GNU General Public License as published by
|
|
13
|
+
the Free Software Foundation, either version 3 of the License, or
|
|
14
|
+
(at your option) any later version.
|
|
15
|
+
|
|
16
|
+
pyrasite is distributed in the hope that it will be useful,
|
|
17
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
18
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
19
|
+
GNU General Public License for more details.
|
|
20
|
+
|
|
21
|
+
You should have received a copy of the GNU General Public License
|
|
22
|
+
along with pyrasite. If not, see <http://www.gnu.org/licenses/>.\
|
|
23
|
+
"""
|
|
24
|
+
__copyright__ = "Copyright (C) 2011-2013 Red Hat, Inc."
|
|
25
|
+
|
|
26
|
+
from pyrasite import utils # noqa: F401 - used by the reverse_shell payload
|
|
27
|
+
from pyrasite.injector import InjectionError, inject
|
|
28
|
+
from pyrasite.inspector import inspect
|
|
29
|
+
from pyrasite.ipc import PyrasiteIPC
|
|
30
|
+
from pyrasite.reverse import ReverseConnection, ReversePythonConnection
|
pyrasite/injector.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
# This file is part of pyrasite.
|
|
2
|
+
#
|
|
3
|
+
# pyrasite is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# pyrasite is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with pyrasite. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
#
|
|
16
|
+
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
|
|
17
|
+
|
|
18
|
+
"""Inject a Python file into a running interpreter using gdb.
|
|
19
|
+
|
|
20
|
+
There are two ways of running code in the target process. :func:`inject`
|
|
21
|
+
picks one automatically based on the number of threads in the target, and
|
|
22
|
+
``method`` can be used to force a particular choice:
|
|
23
|
+
|
|
24
|
+
``pending``
|
|
25
|
+
Ask CPython to execute the payload at its next bytecode boundary using
|
|
26
|
+
:c:func:`Py_AddPendingCall`. This is safe with multi-threaded programs:
|
|
27
|
+
the code runs on a thread that already holds the GIL, so we never wait for
|
|
28
|
+
a GIL owned by a thread that gdb has stopped. The bootstrap starts the
|
|
29
|
+
payload in a fresh daemon thread so that the interrupted thread can resume
|
|
30
|
+
immediately.
|
|
31
|
+
|
|
32
|
+
``direct``
|
|
33
|
+
Acquire the GIL with :c:func:`PyGILState_Ensure` and call
|
|
34
|
+
:c:func:`PyRun_SimpleString` from gdb. This can execute code in a process
|
|
35
|
+
that is blocked in C, but deadlocks if another thread owns the GIL, which
|
|
36
|
+
is why it is only used for single-threaded targets. The payload runs
|
|
37
|
+
inline, so gdb returns once it has finished.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
import contextlib
|
|
41
|
+
import os
|
|
42
|
+
import platform
|
|
43
|
+
import re
|
|
44
|
+
import subprocess
|
|
45
|
+
import tempfile
|
|
46
|
+
import time
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class InjectionError(RuntimeError):
|
|
50
|
+
"""Raised when gdb could not inject the payload into the target."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _c_string(value):
|
|
54
|
+
"""Return *value* as a double-quoted C string literal.
|
|
55
|
+
|
|
56
|
+
gdb evaluates the commands we pass it as C expressions, so the payload
|
|
57
|
+
path has to be escaped using C rules. We deliberately do not use
|
|
58
|
+
:func:`repr`, because gdb treats single quotes as character literals.
|
|
59
|
+
"""
|
|
60
|
+
escaped = (
|
|
61
|
+
value.replace("\\", "\\\\")
|
|
62
|
+
.replace('"', '\\"')
|
|
63
|
+
.replace("\n", "\\n")
|
|
64
|
+
.replace("\r", "\\r")
|
|
65
|
+
.replace("\t", "\\t")
|
|
66
|
+
)
|
|
67
|
+
return '"%s"' % escaped
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _python_string(value):
|
|
71
|
+
"""Return *value* as a Python string literal."""
|
|
72
|
+
return repr(value)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def build_code(filename, marker=None, threaded=False):
|
|
76
|
+
"""Return the Python source that gdb should execute in the target.
|
|
77
|
+
|
|
78
|
+
The payload is executed with ``exec(compile(...))`` rather than
|
|
79
|
+
``exec(open(...).read())`` so that tracebacks point at the real file and
|
|
80
|
+
encoding declarations are honoured. Both the payload's directory and the
|
|
81
|
+
pyrasite source tree are added to ``sys.path`` so that payloads can import
|
|
82
|
+
both their neighbours and pyrasite itself.
|
|
83
|
+
|
|
84
|
+
When *marker* is given the wrapper writes ``ok`` to that file after the
|
|
85
|
+
payload finishes, or ``error`` followed by the traceback if it raises.
|
|
86
|
+
Catching the exception inside the target is important for the pending-call
|
|
87
|
+
method: leaving an exception set in the interpreter can corrupt the next
|
|
88
|
+
operation performed by the target.
|
|
89
|
+
|
|
90
|
+
With *threaded* set the payload runs in a new daemon thread. This is used
|
|
91
|
+
for the pending-call method, where the bootstrap itself runs at an
|
|
92
|
+
arbitrary bytecode boundary and must return as quickly as possible so that
|
|
93
|
+
the target's interrupted thread can continue. The direct method runs the
|
|
94
|
+
payload inline instead, so that gdb's call returns only after the payload
|
|
95
|
+
has finished.
|
|
96
|
+
"""
|
|
97
|
+
filename = os.path.abspath(filename)
|
|
98
|
+
payload_dir = os.path.dirname(filename)
|
|
99
|
+
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
100
|
+
lines = [
|
|
101
|
+
"import sys",
|
|
102
|
+
"sys.path.insert(0, %s)" % _python_string(payload_dir),
|
|
103
|
+
"sys.path.insert(0, %s)" % _python_string(package_root),
|
|
104
|
+
"",
|
|
105
|
+
# Format the traceback by hand instead of importing the traceback
|
|
106
|
+
# module. Importing anything from the injected thread triggers the
|
|
107
|
+
# import machinery, which can take seconds (or longer) in a busy
|
|
108
|
+
# multi-threaded process because every import releases and reacquires
|
|
109
|
+
# the GIL. Everything below only uses builtins and sys.
|
|
110
|
+
"def __pyrasite_traceback(exc):",
|
|
111
|
+
' lines = ["Traceback (most recent call last):"]',
|
|
112
|
+
" tb = exc.__traceback__",
|
|
113
|
+
# Drop the frame belonging to this bootstrap; the useful part of the
|
|
114
|
+
# traceback starts at the payload.
|
|
115
|
+
' if tb is not None and tb.tb_frame.f_code.co_name == "__pyrasite_inject":',
|
|
116
|
+
" tb = tb.tb_next",
|
|
117
|
+
" while tb is not None:",
|
|
118
|
+
" code = tb.tb_frame.f_code",
|
|
119
|
+
" lines.append(",
|
|
120
|
+
" ' File \"%s\", line %d, in %s' %",
|
|
121
|
+
" (code.co_filename, tb.tb_lineno, code.co_name))",
|
|
122
|
+
" tb = tb.tb_next",
|
|
123
|
+
' lines.append("%s: %s" % (type(exc).__name__, exc))',
|
|
124
|
+
' return "\\n".join(lines) + "\\n"',
|
|
125
|
+
]
|
|
126
|
+
if marker is not None:
|
|
127
|
+
marker_literal = _python_string(marker)
|
|
128
|
+
lines.extend(
|
|
129
|
+
[
|
|
130
|
+
"",
|
|
131
|
+
"def __pyrasite_report(status):",
|
|
132
|
+
" try:",
|
|
133
|
+
' with open(%s, "w") as marker_file:' % marker_literal,
|
|
134
|
+
" marker_file.write(status)",
|
|
135
|
+
" except BaseException:",
|
|
136
|
+
" pass",
|
|
137
|
+
]
|
|
138
|
+
)
|
|
139
|
+
lines.extend(
|
|
140
|
+
[
|
|
141
|
+
"",
|
|
142
|
+
"def __pyrasite_inject():",
|
|
143
|
+
" try:",
|
|
144
|
+
' exec(compile(open(%s, "rb").read(), %s, "exec"),'
|
|
145
|
+
" globals())" % (_python_string(filename), _python_string(filename)),
|
|
146
|
+
" except BaseException as exc:",
|
|
147
|
+
" try:",
|
|
148
|
+
" detail = __pyrasite_traceback(exc)",
|
|
149
|
+
" except BaseException:",
|
|
150
|
+
' detail = "Payload raised %s\\n" % type(exc).__name__',
|
|
151
|
+
" try:",
|
|
152
|
+
" sys.stderr.write(detail)",
|
|
153
|
+
" sys.stderr.flush()",
|
|
154
|
+
" except BaseException:",
|
|
155
|
+
" pass",
|
|
156
|
+
]
|
|
157
|
+
)
|
|
158
|
+
if marker is not None:
|
|
159
|
+
lines.extend(
|
|
160
|
+
[
|
|
161
|
+
' __pyrasite_report("error\\n" + detail)',
|
|
162
|
+
" else:",
|
|
163
|
+
' __pyrasite_report("ok")',
|
|
164
|
+
]
|
|
165
|
+
)
|
|
166
|
+
if threaded:
|
|
167
|
+
lines.extend(
|
|
168
|
+
[
|
|
169
|
+
"",
|
|
170
|
+
"import threading",
|
|
171
|
+
'threading.Thread(target=__pyrasite_inject, name="pyrasite",'
|
|
172
|
+
" daemon=True).start()",
|
|
173
|
+
]
|
|
174
|
+
)
|
|
175
|
+
else:
|
|
176
|
+
lines.append("")
|
|
177
|
+
lines.append("__pyrasite_inject()")
|
|
178
|
+
return "\n".join(lines) + "\n"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _gdb_base(pid, gdb_prefix=""):
|
|
182
|
+
return [
|
|
183
|
+
(gdb_prefix or "") + "gdb",
|
|
184
|
+
"-p",
|
|
185
|
+
str(pid),
|
|
186
|
+
"-batch",
|
|
187
|
+
"-nx", # ignore the user's ~/.gdbinit
|
|
188
|
+
"-eval-command=set pagination off",
|
|
189
|
+
"-eval-command=set confirm off",
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_gdb_argv(pid, filename, gdb_prefix="", method="pending", marker=None):
|
|
194
|
+
"""Build the gdb command line used to inject *filename* into *pid*."""
|
|
195
|
+
if method not in ("pending", "direct"):
|
|
196
|
+
raise ValueError("unknown injection method: %r" % (method,))
|
|
197
|
+
|
|
198
|
+
argv = _gdb_base(pid, gdb_prefix=gdb_prefix)
|
|
199
|
+
code = _c_string(
|
|
200
|
+
build_code(filename, marker=marker, threaded=(method == "pending"))
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
if method == "direct":
|
|
204
|
+
argv.extend(
|
|
205
|
+
[
|
|
206
|
+
"-eval-command=call (void*) PyGILState_Ensure()",
|
|
207
|
+
"-eval-command=call (int) PyRun_SimpleString(%s)" % code,
|
|
208
|
+
"-eval-command=call (void) PyGILState_Release($1)",
|
|
209
|
+
]
|
|
210
|
+
)
|
|
211
|
+
else: # method == 'pending'
|
|
212
|
+
# Py_AddPendingCall takes an int (*)(void *) callback. PyRun_SimpleString
|
|
213
|
+
# has a compatible calling convention (const char * -> int), so we can
|
|
214
|
+
# use it directly. strdup moves the source into the target's memory so
|
|
215
|
+
# it outlives this gdb invocation. The caller waits for the marker
|
|
216
|
+
# file (or for the direct call to return) to know when the payload is
|
|
217
|
+
# done.
|
|
218
|
+
argv.extend(
|
|
219
|
+
[
|
|
220
|
+
"-eval-command=break PyRun_SimpleString",
|
|
221
|
+
"-eval-command=call (int) Py_AddPendingCall("
|
|
222
|
+
"(int (*)(void *)) PyRun_SimpleString, (void *) strdup(%s))" % code,
|
|
223
|
+
"-eval-command=continue",
|
|
224
|
+
"-eval-command=detach",
|
|
225
|
+
]
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
return argv
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# These strings are printed by gdb when it fails to attach, find the
|
|
232
|
+
# interpreter, or call into it. gdb itself often still exits with status 0 in
|
|
233
|
+
# these cases, so we have to inspect its output as well.
|
|
234
|
+
_GDB_ERROR_MARKERS = (
|
|
235
|
+
"No such process",
|
|
236
|
+
"ptrace: ",
|
|
237
|
+
"No symbol table is loaded",
|
|
238
|
+
"No symbol ",
|
|
239
|
+
"Cannot access memory",
|
|
240
|
+
"Could not attach",
|
|
241
|
+
"Cannot call functions",
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _check_result(output, method):
|
|
246
|
+
"""Raise if gdb reported that our injection call failed."""
|
|
247
|
+
if method == "pending":
|
|
248
|
+
match = re.search(r"^\$1 = (-?\d+)\s*$", output, re.MULTILINE)
|
|
249
|
+
if match and int(match.group(1)) != 0:
|
|
250
|
+
raise InjectionError("Py_AddPendingCall failed with %s" % match.group(1))
|
|
251
|
+
elif method == "direct":
|
|
252
|
+
match = re.search(r"^\$2 = (-?\d+)\s*$", output, re.MULTILINE)
|
|
253
|
+
if match and int(match.group(1)) != 0:
|
|
254
|
+
raise InjectionError(
|
|
255
|
+
"PyRun_SimpleString failed with %s; the payload may have "
|
|
256
|
+
"raised an exception (see the target's stderr)" % match.group(1)
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _thread_count(pid):
|
|
261
|
+
"""Return the number of threads in *pid* on Linux, or None."""
|
|
262
|
+
try:
|
|
263
|
+
with open("/proc/%d/status" % pid) as status:
|
|
264
|
+
for line in status:
|
|
265
|
+
if line.startswith("Threads:"):
|
|
266
|
+
return int(line.split()[1])
|
|
267
|
+
except (OSError, ValueError):
|
|
268
|
+
pass
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _pending_was_scheduled(output):
|
|
273
|
+
match = re.search(r"^\$1 = (-?\d+)\s*$", output, re.MULTILINE)
|
|
274
|
+
return match is not None and int(match.group(1)) == 0
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _new_marker():
|
|
278
|
+
fd, path = tempfile.mkstemp(prefix="pyrasite-", suffix=".status")
|
|
279
|
+
os.close(fd)
|
|
280
|
+
os.unlink(path)
|
|
281
|
+
return path
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _read_marker(path):
|
|
285
|
+
try:
|
|
286
|
+
with open(path) as marker:
|
|
287
|
+
status = marker.read()
|
|
288
|
+
except OSError:
|
|
289
|
+
return None
|
|
290
|
+
return status or None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _wait_for_marker(path, deadline):
|
|
294
|
+
while True:
|
|
295
|
+
status = _read_marker(path)
|
|
296
|
+
if status is not None:
|
|
297
|
+
return status
|
|
298
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
299
|
+
return None
|
|
300
|
+
time.sleep(0.05)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _marker_error(status):
|
|
304
|
+
if status.startswith("error"):
|
|
305
|
+
detail = status[len("error") :].lstrip("\n")
|
|
306
|
+
return "The payload raised an exception:\n%s" % detail
|
|
307
|
+
return None
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _remaining(deadline):
|
|
311
|
+
if deadline is None:
|
|
312
|
+
return None
|
|
313
|
+
return max(0.0, deadline - time.monotonic())
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _partial_output(exc):
|
|
317
|
+
partial = ""
|
|
318
|
+
if exc.stdout:
|
|
319
|
+
partial += (
|
|
320
|
+
exc.stdout
|
|
321
|
+
if isinstance(exc.stdout, str)
|
|
322
|
+
else exc.stdout.decode("utf-8", "replace")
|
|
323
|
+
)
|
|
324
|
+
if exc.stderr:
|
|
325
|
+
partial += (
|
|
326
|
+
exc.stderr
|
|
327
|
+
if isinstance(exc.stderr, str)
|
|
328
|
+
else exc.stderr.decode("utf-8", "replace")
|
|
329
|
+
)
|
|
330
|
+
return partial
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def inject(
|
|
334
|
+
pid, filename, verbose=False, gdb_prefix="", timeout=60, fallback=True, method=None
|
|
335
|
+
):
|
|
336
|
+
"""Execute a file in a running Python process.
|
|
337
|
+
|
|
338
|
+
:param pid: process id of the target interpreter
|
|
339
|
+
:param filename: path to the payload that should be executed
|
|
340
|
+
:param verbose: print gdb's stdout and stderr
|
|
341
|
+
:param gdb_prefix: prefix prepended to the ``gdb`` executable
|
|
342
|
+
:param timeout: total number of seconds to wait for gdb and for the
|
|
343
|
+
payload to finish. Pass ``None`` to wait forever.
|
|
344
|
+
:param fallback: if the pending-call request could not be scheduled, try
|
|
345
|
+
the direct GIL-based method as a fallback. The fallback is never used
|
|
346
|
+
after a pending call has been successfully scheduled, since that would
|
|
347
|
+
execute the payload twice.
|
|
348
|
+
:param method: force a specific method (``'pending'`` or ``'direct'``).
|
|
349
|
+
By default pyrasite uses ``direct`` for single-threaded processes and
|
|
350
|
+
``pending`` for multi-threaded ones.
|
|
351
|
+
:raises InjectionError: if gdb could not inject the payload or the payload
|
|
352
|
+
raised an exception
|
|
353
|
+
"""
|
|
354
|
+
filename = os.path.abspath(filename)
|
|
355
|
+
if method is None:
|
|
356
|
+
if _thread_count(pid) == 1:
|
|
357
|
+
methods = ("direct",)
|
|
358
|
+
else:
|
|
359
|
+
methods = ("pending", "direct") if fallback else ("pending",)
|
|
360
|
+
elif method in ("pending", "direct"):
|
|
361
|
+
methods = (method,)
|
|
362
|
+
else:
|
|
363
|
+
raise ValueError("unknown injection method: %r" % (method,))
|
|
364
|
+
|
|
365
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
366
|
+
errors = []
|
|
367
|
+
|
|
368
|
+
for current_method in methods:
|
|
369
|
+
marker = _new_marker()
|
|
370
|
+
try:
|
|
371
|
+
argv = build_gdb_argv(
|
|
372
|
+
pid,
|
|
373
|
+
filename,
|
|
374
|
+
gdb_prefix=gdb_prefix,
|
|
375
|
+
method=current_method,
|
|
376
|
+
marker=marker,
|
|
377
|
+
)
|
|
378
|
+
try:
|
|
379
|
+
p = subprocess.run(
|
|
380
|
+
argv,
|
|
381
|
+
capture_output=True,
|
|
382
|
+
timeout=_remaining(deadline),
|
|
383
|
+
text=True,
|
|
384
|
+
)
|
|
385
|
+
except FileNotFoundError:
|
|
386
|
+
raise InjectionError(
|
|
387
|
+
"Could not find the gdb executable (%r). Please install "
|
|
388
|
+
"gdb." % argv[0]
|
|
389
|
+
) from None
|
|
390
|
+
except subprocess.TimeoutExpired as e:
|
|
391
|
+
partial = _partial_output(e)
|
|
392
|
+
scheduled = current_method == "pending" and _pending_was_scheduled(
|
|
393
|
+
partial
|
|
394
|
+
)
|
|
395
|
+
errors.append(
|
|
396
|
+
"%s method timed out%s"
|
|
397
|
+
% (
|
|
398
|
+
current_method,
|
|
399
|
+
("\n" + partial.strip()) if partial.strip() else "",
|
|
400
|
+
)
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
status = _read_marker(marker)
|
|
404
|
+
if status is None and scheduled:
|
|
405
|
+
status = _wait_for_marker(marker, deadline)
|
|
406
|
+
if status is not None:
|
|
407
|
+
problem = _marker_error(status)
|
|
408
|
+
if problem:
|
|
409
|
+
raise InjectionError(problem) from None
|
|
410
|
+
return 0
|
|
411
|
+
|
|
412
|
+
if scheduled:
|
|
413
|
+
errors.append(
|
|
414
|
+
"The payload was queued with Py_AddPendingCall but "
|
|
415
|
+
"did not finish in time. It may still run later. Use "
|
|
416
|
+
"method='direct' for processes blocked in C."
|
|
417
|
+
)
|
|
418
|
+
break
|
|
419
|
+
continue
|
|
420
|
+
|
|
421
|
+
out, err = p.stdout, p.stderr
|
|
422
|
+
if verbose:
|
|
423
|
+
print(out)
|
|
424
|
+
print(err)
|
|
425
|
+
|
|
426
|
+
combined = out + err
|
|
427
|
+
failed = p.returncode != 0
|
|
428
|
+
if not failed:
|
|
429
|
+
failed = any(
|
|
430
|
+
marker_text in combined for marker_text in _GDB_ERROR_MARKERS
|
|
431
|
+
)
|
|
432
|
+
if not failed:
|
|
433
|
+
try:
|
|
434
|
+
_check_result(combined, current_method)
|
|
435
|
+
except InjectionError as e:
|
|
436
|
+
failed = True
|
|
437
|
+
errors.append(str(e))
|
|
438
|
+
|
|
439
|
+
status = _read_marker(marker)
|
|
440
|
+
scheduled = current_method == "pending" and _pending_was_scheduled(combined)
|
|
441
|
+
|
|
442
|
+
if current_method == "pending" and status is None and scheduled:
|
|
443
|
+
status = _wait_for_marker(marker, deadline)
|
|
444
|
+
|
|
445
|
+
if status is not None:
|
|
446
|
+
problem = _marker_error(status)
|
|
447
|
+
if problem:
|
|
448
|
+
raise InjectionError(problem) from None
|
|
449
|
+
# The payload finished successfully. gdb may have failed while
|
|
450
|
+
# detaching, but the work has been done.
|
|
451
|
+
return p.returncode if not failed else 0
|
|
452
|
+
|
|
453
|
+
if current_method == "pending":
|
|
454
|
+
if scheduled:
|
|
455
|
+
errors.append(
|
|
456
|
+
"The payload was queued with Py_AddPendingCall but "
|
|
457
|
+
"did not report completion in time. It may still run "
|
|
458
|
+
"later. Use method='direct' for processes blocked in "
|
|
459
|
+
"C."
|
|
460
|
+
)
|
|
461
|
+
break
|
|
462
|
+
# Nothing was queued, so trying the direct method is safe.
|
|
463
|
+
if failed:
|
|
464
|
+
errors.append(
|
|
465
|
+
"gdb exited with %s:\n%s" % (p.returncode, combined.strip())
|
|
466
|
+
)
|
|
467
|
+
continue
|
|
468
|
+
|
|
469
|
+
# The direct method is synchronous, so a missing marker only means
|
|
470
|
+
# the target could not write to /tmp. Trust gdb's result.
|
|
471
|
+
if not failed:
|
|
472
|
+
return p.returncode
|
|
473
|
+
errors.append("gdb exited with %s:\n%s" % (p.returncode, combined.strip()))
|
|
474
|
+
finally:
|
|
475
|
+
with contextlib.suppress(OSError):
|
|
476
|
+
os.unlink(marker)
|
|
477
|
+
|
|
478
|
+
raise InjectionError(
|
|
479
|
+
"Failed to inject %s into pid %s:\n%s" % (filename, pid, "\n".join(errors))
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
if platform.system() == "Windows":
|
|
484
|
+
|
|
485
|
+
def _inject_win(
|
|
486
|
+
pid,
|
|
487
|
+
filename,
|
|
488
|
+
verbose=False,
|
|
489
|
+
gdb_prefix="",
|
|
490
|
+
timeout=60,
|
|
491
|
+
fallback=True,
|
|
492
|
+
method=None,
|
|
493
|
+
):
|
|
494
|
+
if not gdb_prefix:
|
|
495
|
+
gdb_prefix = os.path.join(os.path.dirname(__file__), "win") + os.sep
|
|
496
|
+
filename = os.path.abspath(filename)
|
|
497
|
+
code = build_code(filename).replace("\\", "/")
|
|
498
|
+
argv = [gdb_prefix + "inject_python_32.exe", str(pid), code]
|
|
499
|
+
p = subprocess.run(
|
|
500
|
+
argv,
|
|
501
|
+
capture_output=True,
|
|
502
|
+
timeout=timeout,
|
|
503
|
+
text=True,
|
|
504
|
+
)
|
|
505
|
+
# The helper returns 25 when the target is a 64-bit interpreter.
|
|
506
|
+
if p.returncode == 25:
|
|
507
|
+
argv[0] = gdb_prefix + "inject_python_64.exe"
|
|
508
|
+
p = subprocess.run(
|
|
509
|
+
argv,
|
|
510
|
+
capture_output=True,
|
|
511
|
+
timeout=timeout,
|
|
512
|
+
text=True,
|
|
513
|
+
)
|
|
514
|
+
if verbose:
|
|
515
|
+
print(p.stdout)
|
|
516
|
+
print(p.stderr)
|
|
517
|
+
if p.returncode != 0:
|
|
518
|
+
raise InjectionError(
|
|
519
|
+
"Failed to inject %s into pid %s (exit code %s):\n%s"
|
|
520
|
+
% (filename, pid, p.returncode, (p.stdout + p.stderr).strip())
|
|
521
|
+
)
|
|
522
|
+
return p.returncode
|
|
523
|
+
|
|
524
|
+
inject = _inject_win
|
pyrasite/inspector.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# This file is part of pyrasite.
|
|
2
|
+
#
|
|
3
|
+
# pyrasite is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# pyrasite is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with pyrasite. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
#
|
|
16
|
+
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
|
|
17
|
+
|
|
18
|
+
import subprocess
|
|
19
|
+
|
|
20
|
+
_INSPECT_MARKER = "__PYRASITE_INSPECT__"
|
|
21
|
+
|
|
22
|
+
# Distribution Python builds are stripped, so gdb cannot resolve the PyObject
|
|
23
|
+
# type. The stable C API is available through the dynamic symbol table, so
|
|
24
|
+
# this script calls it from gdb's Python interpreter. gdb keeps the other
|
|
25
|
+
# threads running while an inferior call executes, which lets PyGILState_Ensure
|
|
26
|
+
# take the GIL even if another thread held it when gdb attached.
|
|
27
|
+
_GDB_SCRIPT = """
|
|
28
|
+
import gdb
|
|
29
|
+
|
|
30
|
+
inferior = gdb.selected_inferior()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def readable(address):
|
|
34
|
+
for size in (16, 1):
|
|
35
|
+
try:
|
|
36
|
+
inferior.read_memory(address, size)
|
|
37
|
+
return True
|
|
38
|
+
except Exception:
|
|
39
|
+
continue
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def evaluate(expression):
|
|
44
|
+
return int(gdb.parse_and_eval(expression))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def inspect(address):
|
|
48
|
+
if not readable(address):
|
|
49
|
+
return "<address is not readable>"
|
|
50
|
+
gil = evaluate("(int) PyGILState_Ensure()")
|
|
51
|
+
try:
|
|
52
|
+
obj = evaluate("(void*) PyObject_Repr((void*) %d)" % address)
|
|
53
|
+
if obj == 0:
|
|
54
|
+
gdb.execute("call (void) PyErr_Clear()")
|
|
55
|
+
return "<repr raised an exception>"
|
|
56
|
+
value = evaluate("(char*) PyUnicode_AsUTF8((void*) %d)" % obj)
|
|
57
|
+
if value == 0:
|
|
58
|
+
return "<value is not printable>"
|
|
59
|
+
try:
|
|
60
|
+
return gdb.parse_and_eval("(char*) %d" % value).string()
|
|
61
|
+
except Exception:
|
|
62
|
+
return "<value contains invalid characters>"
|
|
63
|
+
finally:
|
|
64
|
+
gdb.execute("call (void) PyGILState_Release(%d)" % gil)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
gdb.write("__MARKER__%s\\n" % inspect(__ADDRESS__))
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _run_gdb(gdb, pid, commands, timeout):
|
|
72
|
+
argv = [gdb, "--quiet", "-p", str(pid), "-batch", "-nx", *commands]
|
|
73
|
+
try:
|
|
74
|
+
return subprocess.run(
|
|
75
|
+
argv,
|
|
76
|
+
capture_output=True,
|
|
77
|
+
text=True,
|
|
78
|
+
timeout=timeout,
|
|
79
|
+
check=False,
|
|
80
|
+
)
|
|
81
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _inspect_with_c_api(gdb, pid, address, timeout):
|
|
86
|
+
"""Return the repr of the object using only exported C symbols."""
|
|
87
|
+
try:
|
|
88
|
+
numeric = int(address, 0) if isinstance(address, str) else int(address)
|
|
89
|
+
except (TypeError, ValueError):
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
script = _GDB_SCRIPT.replace("__ADDRESS__", str(numeric)).replace(
|
|
93
|
+
"__MARKER__", _INSPECT_MARKER
|
|
94
|
+
)
|
|
95
|
+
p = _run_gdb(gdb, pid, ["-eval-command=python exec(%r)" % script], timeout)
|
|
96
|
+
if p is None or _INSPECT_MARKER not in p.stdout:
|
|
97
|
+
return None
|
|
98
|
+
return p.stdout.split(_INSPECT_MARKER, 1)[1].splitlines()[0]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _inspect_with_gdb_types(gdb, pid, address, timeout):
|
|
102
|
+
"""Use gdb's type information when the target has Python debug symbols."""
|
|
103
|
+
p = _run_gdb(
|
|
104
|
+
gdb,
|
|
105
|
+
pid,
|
|
106
|
+
["-eval-command=print (PyObject *)%s" % address],
|
|
107
|
+
timeout,
|
|
108
|
+
)
|
|
109
|
+
if p is None:
|
|
110
|
+
return None
|
|
111
|
+
for line in p.stdout.splitlines():
|
|
112
|
+
if line.startswith("$1 = "):
|
|
113
|
+
return line[5:]
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def inspect(pid, address, gdb_prefix="", timeout=10):
|
|
118
|
+
"""Return the value of an object in a given process at the specified address.
|
|
119
|
+
|
|
120
|
+
The primary implementation uses the stable C API and therefore works with
|
|
121
|
+
stripped distribution Python builds. If that fails, ``gdb``'s knowledge of
|
|
122
|
+
the ``PyObject`` type is used, which requires the Python debug symbols.
|
|
123
|
+
"""
|
|
124
|
+
gdb = (gdb_prefix or "") + "gdb"
|
|
125
|
+
value = _inspect_with_c_api(gdb, pid, address, timeout)
|
|
126
|
+
if value is not None:
|
|
127
|
+
return value
|
|
128
|
+
return _inspect_with_gdb_types(gdb, pid, address, timeout)
|