Compare commits

...
265 Commits
Author SHA1 Message Date
Arusekk 56d43680f1 Release 4.6.0 2021-07-12 23:00:40 +02:00
heapcrash d7139997dd Merge branch 'stable' into beta 2021-05-31 15:55:40 -05:00
heapcrash 5b0bec0c09 [4.5.1] Update setup.py 2021-05-31 15:44:49 -05:00
Heap Crash 2d460e5738 [4.5.1] Update version.py (#1908) 2021-05-31 20:29:49 +00:00
Heap Crash dff64e2366 For tmux, always specify -F and -P (#1902)
* For tmux, always specify -F and -P

Fixes #1898

* [4.5.1] Update CHANGELOG
2021-05-31 15:20:35 -05:00
Arusekk fcf008b4fd Merge branch 'stable' into beta 2021-05-13 14:01:07 +02:00
tirefire b2c83a7cd0 Change the regex for the rop verifier to handle 2 character registers (#1884)
* Change the regex for the rop verifier to handle 2 character registers as well

* Update changelog
2021-05-13 06:52:48 +00:00
Arusekk 882fd6a926 [testing] Google strikes back once again 2021-05-07 15:59:04 +02:00
Arusekk f16cead9d7 [testing] Google strikes back 2021-05-07 10:46:01 +02:00
Arusekk d7e7ecce3f Merge branch 'stable' into beta 2021-05-07 10:39:35 +02:00
Arusekk 3914b212ae Get a sane CHANGELOG 2021-05-07 10:38:33 +02:00
Arusekk 6780c890cd Update CHANGELOG.md 2021-04-30 18:14:36 +02:00
Arusekk bf023053fc Release 4.6.0beta0 2021-04-30 18:11:16 +02:00
Arusekk c8681de1ee Merge branch 'beta' into dev 2021-04-30 18:10:57 +02:00
Arusekk 34bcb02a3f Release 4.5.0 2021-04-30 18:09:40 +02:00
Arusekk 4b8cac5557 Fix tests 2021-04-30 18:09:14 +02:00
Saleem RashidandArusekk 8926425aed Add ignore_config argument to pwnlib.tubes.ssh and improve allow_agent implementation (#1566)
* ssh: Use paramiko allow_agent parameter

* ssh: Add ignore_config parameter to opt out of using ~/.ssh

* [changelog] Add `ignore_config` argument to `pwnlib.tubes.ssh` and improve `allow_agent` implementation (#1566)

Co-authored-by: Arusekk <[email protected]>
2021-04-29 19:20:14 +02:00
mephi42andArusekk e27209469e Fix process() with executable relative to cwd (#1751)
* Add PyCharm project directory to .gitignore

* Fix process() with executable relative to cwd

* Update CHANGELOG.md

Co-authored-by: Arusekk <[email protected]>
2021-04-29 19:13:22 +02:00
Heap CrashandArusekk 797c3ee178 [process] Add writemem with tests, alias readmem == leak (#1652)
* [process] Add writemem with tests, alias readmem == leak

* Update CHANGELOG

* Explicitly show result for easier debugging on CI

* Explicitly set arch to i386

* Troubleshooting and avoid overwriting top-level asm

* Update pwnlib/tubes/process.py

* Fix nasty race condition

Co-authored-by: Arusekk <[email protected]>
2021-04-29 19:10:21 +02:00
Arusekk e3bd4212de Respect context.bytes when counting ROP padding
Closes #1862
2021-04-29 16:26:27 +02:00
Heap CrashandArusekk a7b34f7d79 [android] Split Android AVD testing into its own Workflow (#1594)
* [android] Split Android AVD testing into its own Workflow

* [android] Modify to trigger tests

* [android] Make paths more succinct and explicit

* Remove environment variable

* Rename to test

* Always run Android jobs for debugging

* Enhance Android workflow

* Disable gdbserver download

* Make the workflow actually work

* Travis missing gdbserver

* Try to fix travis

* Add good ol' SIGALRM-based debugs for tests

* Revert changes made to Travis

* But fix GHA

* Actually enable the android tests

* Actually enable

* Not necessary anymore

* Actually run the tests with AVD installation

Also fix incorrect text-vs-bytes usages in protocols.adb.

Co-authored-by: Arusekk <[email protected]>
2021-04-29 15:56:18 +02:00
Arusekk 4b196c7d96 Cleanup unconditional imports (#1753)
* Cleanup unconditional imports

This may aid #1725

* Import explicitly

* Add good ol' SIGALRM-based debugs for tests

* Fix py2 GDB tests somehow

XXX: see why this matters

* Update CHANGELOG.md
2021-04-29 11:23:09 +02:00
Heap CrashandArusekk ad251a8285 Make gdb.attach work with arrays instead of string concatenation (#1846)
* Make gdb.attach work with arrays instead of string concatenation

This results in a simpler set of code that is more resilient to
issues with quoting and files with spaces in their name.

* Remove detach_and_quit for now, this was for Docker CI testing

* Fix typo

* Fix lint errors

* shlex.quote is unavailable on Python3

* Update CHANGELOG.md

* With no escaping comes no escaping

Co-authored-by: Arusekk <[email protected]>
2021-04-28 22:11:29 +02:00
ArusekkandCptGibbon 603e5ba0f1 Another attempt for rop.ret2csu (#1429)
* Add rop.ret2csu()

* Removed magic numbers

* Replaced if elf.sym.has_key(u'__libc_csu_init') with if u'__libc_csu_init' in elf.symbols

* Consistently used unicode strings to search for symbols

* Used the Capstone SKIPDATA option to deal with endbr64 instructions

* Added comment to clarify why we set rbp and rbx

* Account for newer versions of gcc populating registers in a different order

* Code style issues

* Add padding functionality

* Split files and add tests at last

* Implement flat interface in ROP

* Make linters happy

* Update changelog

* Add a more detailed doctest

* Actually set uid and hopefully solve all the corefile problems

* Show me the bug

* More verbosity

BTW fix py3 sockets incosistency

* The most debug

* Should finally work

* It must work now

Co-authored-by: CptGibbon <[email protected]>
2021-04-28 22:10:46 +02:00
Heap CrashandArusekk cb24f376ce Prefer Python3 for the remotely-executed Python script (#1746)
* Prefer Python3 for the remotely-executed Python script

This should be done as part of our general transition to Python3,
but should also be done because some systems with e.g. Python2.6
do not support OrderedDict, but DO have a Python3 version that works.

* Make the script actually work in py2 and py3

* Fix & update CHANGELOG.md

This actually is a behavior change, and can be a breaking change for some,
so must be stated prominently in the changelog.

Co-authored-by: Arusekk <[email protected]>
2021-04-28 22:00:53 +02:00
Arusekk f3b08ed289 Merge branch 'beta' into dev 2021-04-19 10:21:02 +02:00
Arusekk 21da0e1c46 Release 4.5.0beta1 2021-04-19 10:06:31 +02:00
clubby789 9e9531ff0d Fix atexit on Python 3 (#1852)
* Fix atexit on Python 3

`sys.exitfunc` was removed in Python 3, meaning that any handlers
registered with the `pwnlib/atexit.py` module wouldn't run. This PR
reigsters the handlers with the stdlib atexit.

* Update changelog
2021-04-19 07:56:26 +00:00
Arusekk 835bc6ad56 Address code review from #1861 (#1866)
* Address code review from #1861

Review by @heapcrash

* Fix regression
2021-04-19 09:06:46 +02:00
Robert ReithandArusekk 2b71971821 fixed wrong description for shellcraft.amd64.linux.kill()... (#1739)
* fixed wrong description for shellcraft.amd64.linux.kill(). new desciption copied from pwntools/pwnlib/shellcraft/templates/common/linux/syscalls/kill.asm

* updated changelog with PR #1739

* Fix more syscalls and generify

Co-authored-by: Arusekk <[email protected]>
2021-04-15 13:01:35 +02:00
084890f739 mips: do not use $t0 temporary variable in dupio (#1776)
* mips: do not use $t0 temporary variable in dupio

dupio currently uses $t0 which is a temporary callee saved register.
The dup2 call is thus allowed to trash the register.
Use $v0 instead. $v0 is the return value register.
Either dup2 returns the provided $v0 (newfd) or -1 if it fails,
and therefore $v0 can be used safely here.

Reference:
 https://courses.cs.washington.edu/courses/cse410/09sp/examples/MIPSCallingConventionsSummary.pdf

* Update changelog

* Update dupio.asm

Make a small change to kick Github Actions

* Fix CHANGELOG

Co-authored-by: Heap Crash <[email protected]>
Co-authored-by: Arusekk <[email protected]>
2021-04-15 12:05:25 +02:00
Arusekk 3121f68e39 Try to catch more errors by using python -bb (#1861)
* Try to catch more errors by using python -bb

* Apply changes to travis dockerfiles as well

* Introduce context._need_bytes and context._need_text

...and resolve many issues
2021-04-15 12:04:56 +02:00
martinclauss 9066a68879 fix #1803 and #1860 (#1864)
* fix #1803 and #1860

* bring back Python2 shebang and imports
2021-04-15 12:03:20 +02:00
Arusekk 7e03bfd5a6 Fix unreliable doctest 2021-04-09 18:19:37 +02:00
Arusekk cf7ee859c9 Prevent CHANGELOG checks on non-code changes 2021-04-09 18:18:01 +02:00
Arusekk 7ececc6bce Support forking terminals (#1717)
* Support forking terminals

Closes #1677

* Update proc.py
2021-04-09 17:52:41 +02:00
Arusekk b3fe1eb6ed Enhance x86 bitsmode-switching templates (#1756) 2021-04-09 16:38:10 +02:00
Heap Crash 5d54e0d66d Work around bash complaining about setlocale on some servers (#1745)
Fixes #1744
2021-04-09 16:15:26 +02:00
Arusekk 3e0e0a5833 Merge branch 'beta' into dev 2021-03-31 23:10:34 +02:00
Arusekk 3d5ca378ec No more failing UI tests! (#1857)
* Better debug for UI tests

* No more failing UI tests!
2021-03-31 21:01:46 +00:00
Arusekk c6fd41b733 Begin working on 4.6.0 2021-03-29 12:02:45 +02:00
Arusekk faba1351fc Release 4.5.0beta0 2021-03-29 12:01:20 +02:00
Arusekk d07a86d556 Release 4.4.0 2021-03-29 11:49:32 +02:00
WGHandHeap Crash ec9dfe108b Support XDG_CONFIG_HOME dir for pwn.conf (#1827)
~/.pwn.conf support is not removed.

Co-authored-by: Heap Crash <[email protected]>
2021-03-07 20:48:38 -06:00
Heap Crash d20ceacd7b Fix typo (#1844) 2021-03-05 16:53:46 -05:00
Heap Crash 3bfb3ff135 Add colored_traceback for colorized exception tracebacks (#1841)
* Add colored_traceback for colorized exception tracebacks

* Add CHANGELOG
2021-03-05 16:13:22 -05:00
Heap Crash 2114708210 [ssh] Apparently this is broken? (#1842)
/bin/sh seems to be sending the cd command to the background, instead of
changing directories and then running the selected command.

This has worked forever, not sure why it's failing in CI now
2021-03-05 00:29:39 -05:00
Heap Crash e8c03edebf Add Pwnlib IO (#1833)
* [io] Introduce first draft of IO module

This is designed to make it easier to do file management when a piece of code
has to deal with creating a file that might need to be local, OR might need
to reside on some SSH server somewhere.

Specifically, the GDB code needs this for future enhancements

* [docs] Add documentation and doctests

* Update CHANGELOG

* Add pathlib2 requirement for Python2

* Use Python3 documentation

* Remove pwnlib.io module

* [filesystem] Add filesystem module, with Path and SSHPath

* Use @classmethod monkey patching instead of subclassing

This means that isinstance(Path, ssh_path_instance) returns True

* Make doctests work again

* Remove debugging code

* Rename context.ssh to context.ssh_session

This is needed because @LocalContext will pop off 'ssh' and some functions
take 'ssh' as an argument, and it would all break.

* [debug] Try to figure out why CI is failing

* [ssh] Fix failing doctest

* Fix README

* Fix README

* Fix failing doctest harder

* Remove unneeded internal file
2021-03-04 22:51:15 -05:00
Heap Crash 216d24875d [run_in_new_terminal] Create a wrapper script automatically if we are given a list or tuple (#1839)
* [run_in_new_terminal] Create a wrapper script automatically if we are given a list or tuple

* Update CHANGELOG
2021-03-03 16:20:27 -05:00
Heap Crash e8979928d6 Clean up some GDB doctests (#1834) 2021-02-28 22:53:45 -05:00
Heap Crash efce48cddf [gdb] Add a timeout to GDB faketerminal operations (#1836) 2021-02-28 22:47:04 -05:00
Heap Crash 19cf23b3ac [ssh] Add instructions for removing host key from known_hosts (#1770)
* [ssh] Add instructions for removing host key from known_hosts

* Fix hostname
2021-02-28 21:35:36 -05:00
Heap Crash d98d82d664 [ssh] Minor enhancements (#1831)
- ssh.runner() now accepts mixed bytes and strings, by forcing everything to a string
- ssh.runner() now takes e.g. log_level='debug' as a kwarg
- Simplify ">/dev/null 2>&1" into "&>/dev/null"
2021-02-28 21:10:57 -05:00
Heap Crash 639be2dc82 Add more doctests for context module around handling verbosity (#1832)
* [docs] Add docs and tests for context.quietfunc

* [docs] Add more doctests for context.quiet and context.verbose

* [docs] Fix doctests
2021-02-28 20:52:39 -05:00
XeonacidandHeap Crash 082de2cc7e Remove unnecessary pwn.toplevel.__all__ (#1811)
* Remove unnecessary pwn.toplevel.__all__

The default behavior of `from import *` is enough and better, to make Pylance work
fix #1810

* Update CHANGELOG.md

* Add a comment for removed pwn.toplevel.__all__

Co-authored-by: Heap Crash <[email protected]>
2021-02-27 00:55:47 -05:00
Heap Crash 95200fc351 Add DOCKER.md (#1802)
* Add DOCKER.md

* Add note about VS Code
2021-02-26 17:07:21 -05:00
Heap Crash b2274da946 [logging] Disable logging the calculated PLT entries of every loaded ELF object (#1817)
In the future, we can revisit this with something like a log.trace that doesnt show up with DEBUG
2021-02-26 17:06:39 -05:00
Heap Crash 5ff4375c7b [travis] Switch to a different server that still has the magic gdbserver, make RPyC tests work (#1825)
* [travis] Switch to a different server that still has the magic gdbserver

* [travis] Install rpyc using pwndbg's method for finding the GDB-built Python

* [travis] Forgot pip dropped support for Python 3.5

* [gdb] Rewrite timeout logic for GDB API and fix doctests to use "skipif"

* [gdb] I'm not sure how this GDB API stuff ever worked in the first place

But it works now, at least locally

* [gdb] Fix broken doctests

* Update timeout to 10 seconds
2021-02-26 17:06:22 -05:00
Heap CrashandArusekk 2f094b74e5 [corefile] Fix some broken tests, add several more (#1823)
* [corefile] Fix some broken tests, add several more

Notably, some were outright incorrect (corefile.libc for a statically-linked ELF)

Also fixed up some of the documentation to add more links, and added examples
of reading / writing / saving / reloading a corefile.

* [corefile] Some fixes for things but also some canaries for finding out what is happening on GHA

* [testing] More canaries to pull files down from GHA

* That was a bad idea

* Fix implementation bug in Corefile.exe

Basically we returned the segment that contained the entry point,
but need to return the first segment which shares the same filename

We also no longer handle the case where the mapping is anonymous
and set the name to AT_EXECFN.  This probably breaks some QEMU stuff.

* Yep, the code used AT_EXECFN for the QEMU case

For an ARM corefile generated by qemu-user, the mappings are:

In [10]: print(core.maps)
10000000-10001000 r-xp 1000
ff7ef000-ff7f0000 ---p 1000
ff7f0000-ffff0000 rw-p 800000 [stack]

So we need to pull the name out of AT_EXECFN

* [core] Eagerly fetch self.exe so that the Mapping always has the right name

This means that Corefile.maps and Corefile.mappings will be updated for the single mapping
that contains the AT_ENTRY

* Attempt to debug getenv failure

* Fix some temporary edits and broken tests

* [ssh] Lets try and see if this works

* Remove unnecessary test and disable diagnostic logging

* [misc] Refactor kill_at_exit code for simplicity

Also catch the OSError from when the process has already died, which
was showing up at the end of CI runs

* Remove debug print

* Hail mary debugging attempt

* Try workaround that manually sets SHELL, since it may not be set on GHA

* [corefile] Remove debugging code, and consume setdefault result

* [corefile] Hide the bash-static fuckery in the RST file setup

* Update docs/source/elf/corefile.rst

Co-authored-by: Arusekk <[email protected]>

* Update pwnlib/elf/corefile.py

Co-authored-by: Arusekk <[email protected]>

Co-authored-by: Arusekk <[email protected]>
2021-02-25 17:11:31 -05:00
Heap Crash 8f8adf7b71 Enable PWNLIB_COLOR=always environment variable (#1816)
This allows piping with color into tools like ansifilter, which take
ANSI-escape-coded colorized text and emits data in other formats,
notably HTML.

This is useful for writing blog posts with PWNLIB_DEBUG=1 to display
hex-dumped data written to stdout that would not normally be colorized.

Currently this ONLY works for the environment variable PWNLIB_COLOR,
and does not make use of pwnlib.args due to cyclic imports.
2021-02-25 20:29:37 +01:00
Heap Crash cc4210041b [docs] Use older sphinx that doesnt cause recursion errors (#1821)
Per these resources:
* https://github.com/sphinx-doc/sphinx/issues/8119
* https://github.com/sphinx-doc/sphinx/pull/8125

Sphinx 3.4.0 now handles autodoc-skip-member differently, causing us to run
some tests multiple times due to imported code getting tested.
2021-02-25 10:58:44 -05:00
Heap Crash 93316b724d [ci] Disable Android and ADB protocol tests for Dockerfile-based CI (#1822)
These modules are deprecated, so we don't test them anymore, and
the Docker image does not perform any setup to install an Android
SDK or AVD.
2021-02-25 07:18:19 -05:00
Heap Crash 8a6383a55d Refactor dockerfiles for simplicity (#1786)
* Remove likely-unused Dockerfiles, which are not being supported in the future anyway

This leaves base, stable, beta, and dev as the only Dockerfile images

Simplify extra/Docker so that Pwntools is already checked out, and build precedence works

* Base image always gets built first
* Branch-tracking Dockerfiles now require base to be built
* Use locally-checked-out-repo instead of e.g. git+https://github.com/Gallopsled/pwntools@beta
* Install tested with both Python2 and Python3
* Add Python3 user-script directory to $PATH

Update CHANGELOG with Docker changes

Add develop to Makefile, restore old Dockerfiles

Make development target separate, and automatically launch "docker run -it" with suggested arguments

Add develop Dockerfile

* Add README for the Dockerfiles

* Merge dependencies, add NOPASSWD, use hostname localhost to avoid sudo errors

* Better Dockerfile for testing, working on making all of the tests work

* wip

* WORK-IN-PROGRESS

* Remove from pwn import *

* Fix incorrect usage of progress() in SSH

* WIPWIPWIP

* MORE WIP

* [srop] Fix SROP unit tests by allocating enough stack

* [todo] Test canary in MIPS pushstr to make sure tests are actually being run

* [ROP] Make ROP doctests work from Docker and more minimal

* [srop] Simplify SROP imports

* [mips] Simplify MIPS doctest imports

* [corefile] Handle race condition against kernel / qemu

* [web] Handle file permission failure in Docker

* [core] Actually implement timeout

* Revert "[corefile] Handle race condition against kernel / qemu"

This reverts commit e02a3dce19.

* [context] Handle file permission issue in Docker

* [aarch64] Just run the shellcode, dont dump it out

* [tests] Remove test canary from mips pushstr

* [timeout] Use ELLIPSIS for time-flaky tests

* [update] Remove DONT_CHECK_FOR_UPDATES

* [context] Handle another path access error in Docker

* [timeout] Just leave it the way it was, hardly ever fails

* [context] Fix broken test because of quotes

* WIP save Docker stuff just in case

* [mips] Do not replace "asm" in the global scope with doctest

* Clear context between invocations so we dont end up with e.g. 64-bit i386

* [process] Fix timeout to actually work

* [mips] Do not replace "asm" in the global scope with doctest (Part 2)

* [rop] Fix ROP doctests

* [mips] Do not replace "asm" in the global scope with doctest (Part 3)

* Re-add all of the Py2OutputChecker stuff so I can start testing Python2

* Restore libcdb checks

* Tests work on Python2 now with "make -C travis/docker doctest2"

* Handle issue caught by Pylint

* Install pwndbg for the pwntools user

* Add trailing newline

* Remove un-necessary ELLIPSIS

* Add trailing newline

* Convert assert to simple statement

* This is an empty commit for testing webhook integrations

* [travis] Use bash as the default shell

* Commit compiled Dockerfile for use on hub.docker.com

* [gdb] Restore gdb.rst and manually disable doctests from inside Docker container
2021-02-25 11:34:56 +01:00
Heap Crash aa7b6f77a5 Add description= to subcommand parsers (#1814)
The help= does not show up in docs.pwntools.com, but description= does.
2021-02-24 04:16:42 -05:00
heapcrash a3870d3ede Fix typo in docs 2021-02-23 22:32:19 -05:00
heapcrash f716b4e9ff Need to reclaim a Cloudflare page rule, just use the real link 2021-02-23 22:04:06 -05:00
Heap Crash 559543984f Update installation instructions (#1813)
* Note newer Ubuntu versions
* State preference for Python3
* Provide working instructions for Python2 installation due to pip deprecation
* Provide information on command-line tools not being in $PATH
2021-02-23 21:22:45 -05:00
Xeonacid 3acbd0596b Fix feat_req issue template typo (#1809) 2021-02-19 10:19:13 +01:00
heapcrash 4e6ccb0da1 Make Discord invite link consistent and permanent 2021-02-16 23:15:24 -06:00
Arusekk 15f85de4d8 Add links to README (#1798)
* a Discord invite link from Discord #online badge
* a link to relevant GH Actions from GHA status badge
2021-02-16 21:18:27 +01:00
Heap Crash 3b909651aa [android] Skip all Android tests (#1791)
* [android] Skip all Android tests

* Update README to indicate Android tests are no longer supported

* Remove Android AVD setup from GHA setup
2021-02-15 00:43:21 -06:00
Heap Crash 7cc55d039d Add Discord badge (#1796) 2021-02-14 23:57:28 -06:00
Heap Crash c978ad0668 Fix test to use ellipsis, since which() may not return /bin/sh (#1795)
* Fix test to use ellipsis, since which() may not return /bin/sh

* Fix another case where /bin/true may not be used given $PATH

* Fix another absolute path failure in doctests

* Fix another issue where /usr/bin may intercede
2021-02-14 23:40:38 -06:00
Heap Crash 08a96ff859 Fix unreliable test (#1794)
Updated or alternative versions of binutils cannot be relied upon to create
very small versions of ELFs (e.g. when running on macos).

However, we can ensure that the non-symbolized version is SMALLER.
2021-02-14 23:01:33 -06:00
Heap Crash 4cf71b4593 Pin autoprogram to v0.1.5 which supports Python2 (#1793) 2021-02-14 22:14:43 -06:00
Heap Crash ea1301806d Add link to discord server (#1790) 2021-02-14 18:39:00 -06:00
Heap Crash 2086a31954 Re-add Python2 to the various Dockerfiles (#1780)
* Re-add Python2 to the various Dockerfiles

This fixes #1774

* Update CHANGELOG
2021-02-02 06:05:29 -06:00
heapcrash 747d30a3a6 Empty commit to force Docker Hub to rebuild images 2021-01-16 18:03:53 -06:00
Heap Crash 4c390c04d6 [docker] It looks like the symlink was breaking the "base" build, so replace it with the actual file from the Xenial subdirectory (#1768)
Fixes regression introduced in ddf5cdc
2021-01-16 17:39:33 -06:00
152334H 153b35ba68 Remove eval from cli (#1758)
* Remove eval from cli

* fix changelog

* shut up pylint
2021-01-10 16:25:58 +01:00
152334H 2f4c5cbf48 update cache directories (#1757)
* update cache directories

* changelog
2021-01-05 12:46:39 +01:00
Arusekk fd280b266b Fix ROP call miscalculating offsets (#1755) 2021-01-05 12:44:32 +01:00
Tim Gates 281b64bb96 docs: fix simple typo, inforation -> information (#1750)
There is a small typo in pwnlib/elf/corefile.py.

Should read `information` rather than `inforation`.
2020-12-29 11:27:34 +01:00
Andreas Oberritter af80848208 Add baremetal os (#1742)
* Add baremetal os

This allows to run and debug a raw binary, e.g. an MBR, with
the help of qemu-system-$(arch).

Tested with:
pwn.context.arch = "i386"
pwn.context.os = "baremetal"
pwn.gdb.debug(["./mbr.bin"])

* Add changelog entry for 'baremetal' os
2020-12-23 23:32:59 +01:00
naweissandArusekk 9de743810e Add PATH argument to which function (#1738)
* Add PATH argument to which function

* [changelog] Add info on the path argument for which

* Move comment back to original location

* Sort CHANGELOG.md

Co-authored-by: Arusekk <[email protected]>

Co-authored-by: Arusekk <[email protected]>
2020-12-07 20:28:13 +01:00
Arusekk f4237d9b7d Minimal fix in encoders (#1736)
This must have been somehow overlooked before.
2020-12-07 17:06:23 +01:00
Arusekk 52ba4b8a17 Add cpython 3.9 constant opcodes to safeeval (#1735)
* Add cpython 3.9 constant opcodes to safeeval

Closes #1734

* Update CHANGELOG.md
2020-12-07 17:06:06 +01:00
Atte Niemi db8df476b2 Fix typo in pwnlib.util.fiddling.bits docstring (#1730) 2020-11-30 01:06:22 +01:00
Arusekk d796cc7dc0 Fix DynELF issues mentioned by @zachriggle in #1426 (#1719)
https://github.com/Gallopsled/pwntools/pull/1426#discussion_r517086024
2020-11-30 01:05:00 +01:00
Jakub Nowak 679463220f Remove unused import from toplevel (#1731)
`debug` is overwritten by line 82 — `debug   = log.debug`.
2020-11-30 01:04:30 +01:00
Arusekk 145b606a06 Merge branch 'beta' into dev 2020-11-30 00:29:52 +01:00
Arusekk b76d045a40 Release 4.4.0beta1 2020-11-30 00:27:41 +01:00
Arusekk 957a5a5835 Release 4.3.1 2020-11-30 00:26:51 +01:00
Arusekk 2efb5a0a73 Merge branch 'issue-1427' into stable 2020-11-30 00:25:25 +01:00
Arusekk 442fedeef0 Auto-generated files 2020-11-30 00:24:01 +01:00
Arusekk 138188eb1c Fix pwntools shellcraft SSTI vulnerability
This looks like the first major pwntools vuln!
And it even got its own task on Hitcon CTF 2020.

Fixes #1427
2020-11-30 00:23:49 +01:00
Arusekk 5dfcb53964 Apparently python 2 does not have lru_cache. 2020-11-29 14:04:24 +01:00
mephi42andArusekk d466fa9017 Allow using GDB Python API (#1617) (#1695)
Co-authored-by: Arusekk <[email protected]>
2020-11-16 20:43:20 +01:00
Arusekk 0b1f430935 Fix #1261 regression
There is no such thing as rwb in py3 apparently
2020-11-03 23:49:05 +01:00
Ricky ZhouandArusekk 9e76e50c9a Misc run_in_new_terminal improvements. (#1261)
* run_in_new_terminal: Prefer tmux/screen over TERM_PROGRAM and x-terminal-emulator.

* run_in_new_terminal: Kill running commands when the main process exits.

Currently, when a gdb window is opened via gdb.debug(), terminating the
main pwntools process leaves the gdb window/process around. It is
inconvenient to have to close these leftover gdb windows when iterating
on an exploit.

Add a kill_at_exit parameter to run_in_new_terminal() which attempts to
terminate the command at main process exit.

This only works for terminals which do not daemonize, or for tmux, which
supports returning the command's PID.

This change also removes the special case for closing
stdin/stdout/stderr on Mac OS X, as the problem no longer reproduces
under tmux 2.8.

* Fix regression and add CHANGELOG

Co-authored-by: Arusekk <[email protected]>
2020-11-01 20:02:58 +01:00
Arusekk 42b060e48a Improve tubes.ssh test coverage, fix discovered issues (#1711)
* Improve tubes.ssh test coverage, fix discovered issues

* Fix test under py2
2020-11-01 12:46:00 +01:00
Arusekk d98e60e4e5 Revert "alternative to PR #563; this works by simply never emitting CR" (#1716)
This reverts commit 08c8c2e8e4.

Closes #1653
2020-11-01 12:27:16 +01:00
Arusekk 4572f8711a Extend shellcraft forbidden names (#1715)
Closes #1664
2020-10-31 21:51:38 +01:00
Arusekk b6bb1ea17e Don't introduce null bytes in MIPS shellcode. (#1710)
* Don't introduce null bytes in MIPS shellcode.

As a verification, you can run:

```sh
pwn shellcraft mips.linux.sh |pwn phd
```

Closes #807

* Add a test

* Fix doctest under py2
2020-10-28 12:33:25 +01:00
Arusekk 681be1284c Apparently python 2 does not have lru_cache. 2020-10-27 10:09:30 +01:00
Arusekk 40b01582b8 Use caching to avoid being hit by rate limiting
Closes #1708
2020-10-27 09:18:07 +01:00
Arusekk 031b3cbadf Fix races in server tube from #1067 and apply #1569 (#1707) 2020-10-26 22:57:14 +01:00
peace-makerandArusekk 545f8dddd4 Try libc.rip for libc lookup (#1704)
* Try libc.rip for libc lookup

As of #1171 the libcdb repository isn't seeing any updates anymore. When looking up a libc by a hash or build_id try the libc database maintained by @niklasb as well.

The database uses a REST api documented at https://github.com/niklasb/libc-database/blob/master/searchengine/api.yml

* Catch exceptions properly

* Update CHANGELOG

* Add doctests

Co-authored-by: Arusekk <[email protected]>
2020-10-24 13:53:50 +02:00
Allen GuanandArusekk 7aa22dd6f5 Remove data_files (#1643)
Co-authored-by: Arusekk <[email protected]>
2020-10-20 18:17:29 +02:00
Arusekk 447aa551f6 Begin working on 4.5.0 2020-10-20 17:57:56 +02:00
Arusekk e004aa6566 Release 4.4.0beta0 2020-10-20 17:44:56 +02:00
Arusekk 5db149adc2 Release 4.3.0 2020-10-20 17:39:40 +02:00
Arusekk 23f5075d93 Merge branch 'beta' into dev 2020-10-20 17:12:12 +02:00
Arusekk ddb5798b8c Merge branch 'stable' into beta 2020-10-20 15:53:07 +02:00
peace-maker cde51065bf Update libcdb buildid offsets (#1703)
* Update libcdb buildid offsets

Recent libcs from Debian and Ubuntu have different offsets for the build id.

* Update CHANGELOG
2020-10-20 11:52:33 +02:00
Heap CrashandArusekk e47c65c6fc Implement property getter/setter for context.newline, and make tubes honor it (#1541)
* Implement property getter/setter for context.newline, and make tubes honor it

The default newline can now be set context-wide, or per-tube.

* [changelog] Update for 1541

* [docs] Use r-prefix for embedded newlines

Co-authored-by: Arusekk <[email protected]>
2020-10-14 01:08:37 +02:00
Kyle ZengandArusekk d6859eb744 FmtStr module enhancement (#1696)
* use non-greedy operator to handle corner cases where the program output contains END in it

* END can appear in the string leak

Co-authored-by: Arusekk <[email protected]>

Co-authored-by: Arusekk <[email protected]>
2020-10-13 22:33:50 +02:00
Aapo SaaristoandArusekk 79cd784383 Place ROP cache in user's homedir like "regular" cache (#1453)
* Keep ROP cache in user's home like regular cache

I don't have statistics numbers on which would be more likely to be writable, an user's home directory or the OS's temp directory, but seems to me it'd make sense to try and write all caches to the same location.

Optimally this would be easily configurable to allow adjusting to different set-ups, obviously.

* Use cache_dir instead

Co-authored-by: Arusekk <[email protected]>
2020-10-13 19:51:28 +02:00
Mariusz SkoneczkoandArusekk 1c0ca55627 Actually import requests when doing from pwn import * (#1687)
* Actually import `requests` when doing `from pwn import *`

As per documentation, we claim to be importing `requests` globally
(https://github.com/Gallopsled/pwntools/blame/dev/docs/source/globals.rst#L100)

We should actually do this :)

* Update CHANGELOG

Co-authored-by: Arusekk <[email protected]>
2020-10-05 12:49:16 +02:00
Mariusz Skoneczko 1d6aa2e276 Remove python2 shebangs where appropriate (#1692)
* Remove python2 shebangs where appropriate

* Update CHANGELOG.md
2020-10-05 12:32:02 +02:00
Ron a0b3b24984 Fix documentation of #1667 (#1693)
* add parameter max_subs to __init__

(cherry picked from commit d331be51d3bdb791d5d19d9d9b8d60706dddf5fa)

* Beautify doc string

(cherry picked from commit ceebf47a956073eee43efe0a5f6e9399e6a1ec65)

* Fix some typos

(cherry picked from commit 6bbbdcedf4c8ae075c30d01d447c372925f0a29d)

* Update CHANGELOG.md

* Revert changelog

https://github.com/Gallopsled/pwntools/pull/1693#discussion_r499236894

* Trigger CI
2020-10-05 11:08:53 +02:00
Arusekk 26ccb97f63 Speak as simple as it can be (#1694)
Fixes #1434
2020-10-04 22:42:59 +02:00
Arusekk 23ac852023 Make bruteforcewrap picklable (#1685)
Closes #1665
2020-10-01 20:08:51 +02:00
Mariusz SkoneczkoandArusekk bcb6e066aa Add __setattr__ and __call__ interfaces to ROP for setting registers (closes #1636) (#1688)
* Implement ROP.__call__ shorthand for setting registers

* Fix broken doctests by ensuring they set context.arch

* Implement ROP.__setattr__ shorthand for setting registers

* Update CHANGELOG.md

Co-authored-by: Arusekk <[email protected]>
2020-10-01 20:07:45 +02:00
152334H 2a5aac1101 ROPGadget multibr hotfix (#1682)
* fix --multibr issue

* modify changelong

* In which I learn how to count

* put doctest for ROP().syscall in unfortunate place

* fix context malapropism
2020-10-01 19:50:44 +02:00
RonandArusekk dc8d0e310c I386 ascii shellcode (#1667)
* Add module ascii_shellcode

* Add doctests

* Make the ascii_shellcode module accessible from pwn star import

* Remove unused imports

* Update docstr

* Update CHANGELOG.md

* Also test private functions

* Undo accidental modification of CHANGELOG.md

* Fix python 2

* Fix python 2 doctests

* Use bytes object in doctests instead of converting from/to hex strings

* Add doctest to shellcraft>asciify>run shellcode

* Move to pwnlib.encoders.i386

* Fix python 2

* Apply some of the suggestions from Arusekk's code review

Co-authored-by: Arusekk <[email protected]>

* Fix some broken code from the suggestions

https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491699166
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491700154
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491700397

* Beautify code by using bytearrays everywhere

https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491698062
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491701007
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491700313
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491700853
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491698916
https://github.com/Gallopsled/pwntools/pull/1667#discussion_r491699243

* Fix python2 doctests

Forgot to update a few doctests to use bytearrays instead of bytes

* Try to improve test coverage

Test correctness of avoid parameter processing

* Remove unused imports

Co-authored-by: Arusekk <[email protected]>
2020-09-26 10:59:21 +02:00
152334H 72ca730f4b ROPGadget multibr (#1678)
* ROPGadget multibr

* Update CHANGELOG.md

* Fix docstrings to match
2020-09-19 16:09:05 +02:00
Jan Mazur 6b7c3d99c4 Gdbserver now correctly accepts multiple libraries in LD_PRELOAD and LD_LIBRARY_PATH (#1675)
* Gdbserver now correctly accepts multiple libraries in LD_PRELOAD and
LD_LIBRARY_PATH.

* modify changelog
2020-09-17 19:23:02 +02:00
152334H 4dec08b4bd ROP: add base= argument for .chain() and .dump() (#1673)
* Allow using specific base for ROP.chain() and ROP.dump()

* Update CHANGELOG.md
2020-09-13 20:32:29 +02:00
Jacopo Tediosi 9ccf404dde Wrong doc for recvline_endswith() (#1661)
* Wrong doc of recvline_endswith()

* Fixed "see also" link
2020-08-29 20:10:23 +02:00
magrasandArusekk 4b5969f582 Fix syscall instruction lists for SROP on i386 and amd64 (#1669)
All three instructions: `int 0x80`, `sysenter`, and `syscall` require
different stack frames and registers to pass arguments, but
`ROP._srop_call` uses them interchangeably.

This fix limits syscall instruction lists to gadgets that work.

Co-authored-by: Arusekk <[email protected]>
2020-08-29 14:24:52 +02:00
magras fb2bf934ac Fix migration to another ROP (#1668) 2020-08-29 14:22:32 +02:00
Arusekk df76e24e7c Fix SSL timeout error on py2 (#1660)
Turns out that python 2 does not raise correct socket.timeout, but
SSLError instead.  With no errno.  Just a message that might be
localized in some circumstances.

**THIS IS NOT THE ONLY TIME PYTHON 2 IS CAUSING PROBLEMS.**
Time to stop using it, dear exploit developers.  It is dead now.
But here you are: the simple fix.

Closes #1356
2020-08-17 18:37:37 +02:00
Arusekk f98c4fbe2a Disable term if initialization fails (#1659)
Closes #1658
2020-08-17 18:37:13 +02:00
Heap Crash 9e0aa3200c [docker] Upgrade Docker images of Pwntools to use Python3 (#1654)
* [docker] Upgrade Docker images of Pwntools to use Python3

Also installs qemu-user-static and various binutils packages for building (binutils)
and running (qemu) cross-arch binaries.

Fixes #1500

* Update CHANGELOG

* Switch to Python3 for stable/beta/dev Docker images

* [changelog] Add missing links
2020-07-29 23:56:06 -05:00
Heap Crash 8080af8866 [shellcraft] Avoid recursive walk of all templates for command line (#1651)
* [shellcraft] Avoid recursive walk of all templates for command line

Fixes #1650

* Avoid double-fetch

* Add changelog

* [pylint] Only warn for additions
2020-07-27 19:24:31 -05:00
peace-maker f227796a09 Fix detection of WSL2 to open new terminal (#1646)
The osrelease is e.g., `4.19.104-microsoft-standard` in WSL2. microsoft being lowercase. Ignore casing for detection.
2020-07-25 10:36:14 +02:00
Mrmaxmeier b6fc0f3536 tubes/remote: Support Server Name Indication and enable by default (#1644)
* tubes/remote: Support Server Name Indication and enable by default

This allows customizing the server_name via sni="custom" or sending the
name specified in the host parameter via sni=True.

We switch to the SSLContext.wrap_socket API because ssl.wrap_socket is
deprecated and does not support SNI.

Unfortunately, SSLContext.wrap_socket dropped some of the parameters
that are supported by ssl.wrap_socket. These parameters have been moved
to the SSLContext API and can now be used by passing a custom SSLContext
to the ssl_context parameter of `remote`.

* update CHANGELOG.md
2020-07-25 10:31:13 +02:00
Heap Crash 556685e150 [ci] Disable pwnlib.ui tests for branch dev (#1647)
These still run for all other branches and tags
2020-07-22 01:39:04 -05:00
Arusekk eb60b5d6b6 Enhance gdb error message when unable to launch binary (#1614)
* Enhance gdb error message when unable to launch

A common issue is when the binary is not executable,
or the binary is simply missing.

* Use six.ensure_str
2020-07-11 23:39:24 -05:00
Heap Crash 84a139f55b [template] Drop into a shell if downloading the file fails (#1633)
* [ssh] An error should be thrown when download fails, not a silent failure

* [changelog] Add to changelog
2020-07-11 23:38:40 -05:00
Heap Crash 70f3b6fa79 [tests] Change test slightly so that failing output will be emitted (#1634)
* [tests] Change test slightly so that failing output will be emitted

* Disable flaky UI test on Github Actions

* [ui] Try a sleep rather than disabling tests
2020-07-11 23:37:54 -05:00
Arusekk 2d45903ee3 Merge branch 'beta' into dev 2020-07-11 16:26:10 +02:00
Arusekk baa4fc5a9f Merge branch 'stable' into beta 2020-07-11 16:12:03 +02:00
Heap Crash a8d34166c4 [ci] Prevent And-roid AVD tests from running every force-push (#1641)
Dash is to prevent triggering installation due to And-roid reference
2020-07-10 13:33:52 -05:00
Heap Crash a6edf2689d [ci] Add pylint stage (#1640) 2020-07-10 13:25:53 -05:00
heapcrash 3940631e21 Silence module-not-imported warning from coverage 2020-07-10 12:29:34 -05:00
heapcrash 7141e93243 Merge branch 'beta' into dev 2020-07-10 12:26:04 -05:00
heapcrash 53ecb27948 [six] Add missing imports to six 2020-07-10 12:09:57 -05:00
Heap Crash f1d8d5b8fe [term] Automatically set PWNLIB_NOTERM when running inside Jupyter (#1632)
* [term] Automatically set PWNLIB_NOTERM when running inside Jupyter

* [changelog] Update changelog
2020-07-10 00:58:52 -05:00
ArusekkandHeap Crash 48a482df24 Enhance tubes.ssh bytes handling (#1602)
* Enhance tubes.ssh bytes handling

Closes #1437

* Add tests

* grep is actually nasty

* Update CHANGELOG.md

Co-authored-by: Heap Crash <[email protected]>
2020-07-10 00:37:21 -05:00
Heap Crash 08ab1b6adf [docs] Add a link to the tutorials (#1631) 2020-07-10 00:29:58 -05:00
Jakub KądziołkaandArusekk 2c33601a86 Add a bfdname for msp430 to make asm and disasm work (#1606)
* Add a bfdname for msp430 to make asm and disasm work

* Add a bfdname for s390 to make asm and disasm work for all architectures

* Add tests for new bfdnames

* ci: Add binutils for newly-tested architectures

Co-authored-by: Arusekk <[email protected]>
2020-07-08 01:15:46 +02:00
Arusekk 55552cd6a2 Merge branch 'beta' into dev 2020-07-07 22:01:20 +02:00
Asger Hautop Drewsen 7e0e644564 Fix cyclic cli for 64 bit integers (#1616)
* Fix cyclic cli for 64 bit integers

* Update changelog

* Use bytes instead of word_size
2020-07-07 21:48:28 +02:00
Arusekk 8b1c25f441 Fix python2 regression from #1608 (#1629)
Closes #1627
2020-07-05 18:49:10 -05:00
Jakub Kądziołka ca06098649 Fix documentation formatting for pwnlib.util.packing.flat (#1624) 2020-07-03 23:30:28 -05:00
heapcrash d2b0a5913b [changelog] Update release date and version list 2020-07-03 20:31:52 -05:00
heapcrash 2fafbfb291 Merge branch 'beta-staging' into dev 2020-07-03 20:13:35 -05:00
Heap Crash 08d900994d [changelog] Update changelog for new release (#1626) 2020-07-03 20:13:17 -05:00
heapcrash 427066d937 [memleak] Fix missing import 2020-07-03 20:12:32 -05:00
heapcrash db0312e0fe Merge branch 'stable' into beta-staging 2020-07-03 19:48:48 -05:00
heapcrash 0337387f97 Add Python3 to supported languages for PyPi 2020-07-03 19:45:49 -05:00
heapcrash 6afccefb01 Merge branch 'beta' into dev 2020-07-03 19:42:03 -05:00
heapcrash db7312b43f Merge branch 'stable' into beta 2020-07-03 19:41:45 -05:00
heapcrash 89e3f2bee0 [dev] Version bump for dev 2020-07-03 19:39:19 -05:00
heapcrash 7b130aec79 [4.3.0] dev is now beta 2020-07-03 19:24:47 -05:00
heapcrash 13960bac08 Merge branch 'beta' into dev 2020-07-03 19:08:00 -05:00
Kyle Zeng 230a42ffc0 OSError is not subscriptable (#1608) 2020-07-02 22:37:20 +02:00
Heap Crash 31465d7570 Permit negative indices in fit() and flat() (#1621)
* [packing] Support negative indices for flat() and fit()

Fixes #1531

* [changelog] Add Changelog for PR

* [packing] Only take negative path if there are any

min([]) is not valid Python

* [packing] Move out_negative to a higher scope
2020-06-30 02:02:36 -05:00
heapcrash 07c7dd6242 Merge branch 'beta' into dev 2020-06-29 23:56:01 -05:00
heapcrash 6f8319519b Merge branch 'beta' into dev 2020-06-29 20:22:46 -05:00
heapcrash 3469f4a4f7 [changelog] Fix release schedule 2020-06-27 20:33:27 -05:00
heapcrash b22e3e611d [changelog] Fix release schedule 2020-06-27 20:33:12 -05:00
Heap Crash 3be97b7ab5 [pwn template] Permit --password in addition to --pass (#1613)
* [pwn template] Permit --password in addition to --pass

* Add to CHANGELOG
2020-06-27 20:31:19 -05:00
Heap Crash 1a9dce025f [asm] Fix disasm() for mips64, powerpc64, sparc64 (#1603)
* [asm] Fix disasm() for mips64, powerpc64, sparc64

Closes #1564

* [asm] Add tests for disasm on mips/powerpc/sparc 64-bit

* [asm] Find powerpc, sparc, mips utilities even for 64-bit variants

* [asm] Remove leftover debug trace

* [ci] Add Sparc64 binutils

* [changelog] Add entry
2020-06-27 20:30:49 -05:00
heapcrash cbb57c0148 [example] Add ssh.process to example code 2020-06-27 19:24:34 -05:00
Arusekk 92810cbeb2 Follow-up after #1611 2020-06-28 01:22:15 +02:00
Arusekk 039f2439b5 Don't pollute global namespace
Fixes #1611
2020-06-28 01:16:13 +02:00
Arusekk a190726caf Type fix 2020-06-28 01:13:32 +02:00
heapcrash 745f8e7716 Merge branch 'beta' into dev 2020-06-27 15:52:49 -05:00
heapcrash a3bf833a9a Merge branch 'beta' into dev 2020-06-26 18:06:21 -05:00
Heap Crash f2cb7babcf [docker] Get Travis CI dockerfile working more (#1607)
* [docker] Get Travis CI dockerfile working more

* [docker] Do not upgrade all packages, only update if required

* [docker] Move requirements installation higher up before the copy
2020-06-26 17:22:26 -05:00
Saullo Carvalho Castelo Branco ce0966d186 Add to fiddling.hexdump a way to suppress the total at the end (#1605)
* Add `total=` argument to `hexdump` and `hexdump_iter`

* Update `hexdump` docstring

* Add PR to CHANGELOG.md
2020-06-24 11:44:14 +02:00
heapcrash d143af398e Merge branch 'beta' into dev-staging 2020-06-23 20:56:10 -05:00
Heap Crash a1b0ff6b29 Fix extremely verbosel logging of environment when no changes were made (#1592)
* Fix extremely verbosel logging of environment when no changes were made

* [changelog] Update changelog for #1592

Fixes #1448
2020-06-23 11:05:58 -05:00
Heap Crash 1b130cfe5d [ci] Delete foo-staging branch after merging and pushing foo (#1600) 2020-06-23 11:04:55 -05:00
Arusekk c3e39f57f8 Code style enhancements and less sphinx warnings (#1570)
* Fix several sphinx warnings

* Several code style fixes

Mostly grep -Er '[=!]= (None|True|False)'

* Compile-time str concat

also reduced redundant characters at line ends

* Fix python2 toplevel regression

* No equality comparison with singletons again

* Clarification: lambda: [] is just list

* Reintroduce reverted fragment
2020-06-23 11:04:19 -05:00
heapcrash ede4ed13e0 [ci] Add NOTERM to invocation 2020-06-23 11:03:16 -05:00
heapcrash 316cf359c1 [pwn version] Include branch name in output 2020-06-23 11:03:16 -05:00
heapcrash 343dff5c51 [changelog] Update dev changelog 2020-06-23 11:03:16 -05:00
heapcrash a0d61dcea5 [ci] Add "pwn version" step during CI 2020-06-23 11:03:16 -05:00
heapcrash f02e5b5e45 [pwn[ Add "pwn version" command to show installed version 2020-06-23 11:03:16 -05:00
heapcrash c293318cbd [ci] Re-enable Corefile tests on Github Actions 2020-06-22 23:52:48 -05:00
heapcrash ddf5cdcb3f [docker] Update Docker images to use Bionic 2020-06-22 22:23:58 -05:00
heapcrash 761d446fa3 Add to changelog 2020-06-22 20:18:17 -05:00
heapcrash 5e012ebf95 [ui] Colorize output of "pwn template" if it is a TTY 2020-06-22 20:18:17 -05:00
heapcrash 7d6cb3f61f Merge branch 'beta' into dev
Conflicts:
	CHANGELOG.md
	pwnlib/util/proc.py
2020-06-21 20:59:23 -05:00
Saullo Carvalho Castelo Branco a414d788fe Add PR #1576 to CHANGELOG.md (#1588) 2020-06-17 20:51:41 -05:00
Saullo Carvalho Castelo Branco 4134e60c8d Add jmp_esp/jmp_rsp attribute to ROP (#1584) 2020-06-17 15:51:20 -05:00
heapcrash 88084975ad [GHA] Add workflow to require modifications to CHANGELOG.md 2020-06-16 19:31:01 -05:00
heapcrash 4b14e27523 Ask users to update the changelog in the Pull Request template 2020-06-16 19:31:01 -05:00
heapcrash 45eb8bcc81 Re-enable UI tests in Github Actions
I suspect this will not work because of curses failing to initialize in GHA
2020-06-15 23:28:47 -05:00
Arusekk 8b6e6ed67d Enhance py2 32-bit archs support
This was a quick `grep -r isinstance | grep '\<int\>'`
2020-06-15 23:28:32 -05:00
Arusekk 18a7a9458c Ensure tag matches files version 2020-06-15 23:14:03 -05:00
Arusekk 3cca881881 Cyclic CLI functionality 2020-06-15 23:12:29 -05:00
Arusekk 2a68da3dad More coverage 2020-06-15 23:12:29 -05:00
Arusekk 9f5b24d889 Move socket matching to util.net. 2020-06-15 23:12:15 -05:00
Arusekk e9b24a6159 Add support fox mixed-stack connections in proc 2020-06-15 23:12:15 -05:00
Arusekk 39a3b2e8ff Use dual-stack sockets when family is 'any'
Also a minor cleanup in sock.py.
Tested on Linux and FreeBSD.
Closes #1552
2020-06-15 23:12:15 -05:00
ShiftCrops 09caa4ba63 add ".plt.sec" to search section (#1577)
* add .plt.sec to search section

* add test ELFs for .plt.sec
2020-06-14 12:13:00 +02:00
Saullo Carvalho Castelo Branco a0eeb30e0b Add executable= argument to ELF.search (#1576)
* Add `executable=` argument like `writable=` to ELF.search

* Add doctest using ELF.search with `executable = True`

* Fix `__next__()` issue.
2020-06-11 22:10:06 +02:00
jlewis200andArusekk f1628b80fe Update pwnlib/gdb.py
Identity comparison

Co-authored-by: Arusekk <[email protected]>
2020-06-07 19:05:34 -05:00
jlewis200 5c65b8a03e gdb.debug() environment variables fix
If passed an empty dictionary defining the environment variables, the process invoked by gdb.debug() has environment variable 'PWD' set to the directory containing the executable.  This behaviour is not observered when NOPTRACE is enabled:  the program runs without any environment variables set.  Similarly, if an empty environment variable dictionary is passed to process(), it appears to also run under a truly empty environment.  Additionally, attempts to overwrite the "PWD" environment variable with a dictionary entry are not successful under gdb.debug().

This fix brings the gdb.debug() treatment of environment variables in line with and process() and gdb.debug() with NOPTRACE enabled. 
 It allows both empty environments, and overwriting of the 'PWD' environment variable.
2020-06-07 19:05:34 -05:00
heapcrash c2a61b30db [README] Update Twitter badge to include follower count 2020-06-07 14:01:00 -05:00
heapcrash 82a7074d86 [README] Add Coveralls badge logo 2020-06-07 13:58:56 -05:00
heapcrash 8a21b0306d [README] Urlencode badge URL 2020-06-07 13:57:40 -05:00
heapcrash c0afb8ef29 [README] Add Travis logo to Travis CI build badge 2020-06-07 13:56:16 -05:00
heapcrash baed2d5bbc [README] Add Github Workflow status badge 2020-06-07 13:54:02 -05:00
heapcrash cccbc4555c [docs] Add Ubuntu 20.04, remove 12.04 2020-06-07 13:18:38 -05:00
heapcrash df3835a611 [docs] Version should come before docs 2020-06-07 13:17:23 -05:00
heapcrash 758b86c4b0 [docs] Reformat filepointer documentation 2020-06-07 13:15:52 -05:00
heapcrash 16f8c419bc Remove unused update_demo.sh script 2020-06-07 12:27:26 -05:00
heapcrash 1eca50e421 [changelog] Update 4.1.2 2020-06-07 12:24:52 -05:00
heapcrash d2e84c1a30 [travis] Update CI image in README.md 2020-06-07 12:21:49 -05:00
heapcrash 1c1615da2f [docs] Update FmtStr documentation to use pre-compiled binary 2020-06-06 17:58:44 -05:00
heapcrash cb4e01b4df [docs] Make the ret2dlresolve documentation useful 2020-06-06 17:58:44 -05:00
heapcrash 00f65f2c53 [docs] Remove compilation step from ret2dlresolve 2020-06-06 17:58:44 -05:00
heapcrash ac2522fe91 [GHA] Remove dependencies on cross-arch compilers 2020-06-06 17:58:44 -05:00
heapcrash 82f20b28cf [travis] Use gcc-multilib for i386/amd64 compilation 2020-06-06 17:58:44 -05:00
heapcrash fd8ed5883e [travis] Enable IPv6 interfaces, fixes net.interfaces() test 2020-06-06 17:58:44 -05:00
heapcrash 5fea8d25a8 [docs] Fix __doc__ block indentation 2020-06-06 17:58:44 -05:00
heapcrash 01fb378320 [docs] Fix warnings generated during "make doctest" 2020-06-06 17:58:44 -05:00
heapcrash 3f8c92b233 [docs] Silence warning generated by Sphinx about missing code-block language 2020-06-06 17:58:44 -05:00
heapcrash c846f94c8e [shellcraft] Update loader_append examples to build ELFs on the fly
This removes our dependencies against having various compilers installed
2020-06-06 17:58:44 -05:00
Jakub Kądziołka a5bf7c50f4 Make AVR's binutils detection strategy a fallback for all architectures 2020-06-06 14:45:47 -05:00
Jakub Kądziołka 8066b2353b Specify the _bfdname for AVR 2020-06-06 14:45:47 -05:00
Jakub Kądziołka b81c61cae4 Detect AVR binutils
Both Debian and Ubuntu provide a `binutils-avr` package, which contains
an assembler for AVR as `avr-as`. However, pwntools was looking for
something with `linux` in the name, such as `avr-linux-gnu-as`. Of course,
such a target triplet is nonsense, Linux does not run on AVRs
(apart from that one hack that actually emulated some other CPU which
therefore doesn't count).
2020-06-06 14:45:47 -05:00
heapcrash 54d3f674e1 [GHA] Move the lint step to its own workflow 2020-06-05 20:53:19 -05:00
heapcrash 14f5ab6b90 Merge branch 'beta' into dev 2020-06-05 20:26:07 -05:00
Heap Crash 555dec78d9 Recommend people use "pip install --upgrade pwntools" (#1558)
We should not encourage most users to use the `dev` branch
2020-06-05 23:07:16 +02:00
heapcrash 267879c91a Set timeout to 30 minutes 2020-06-05 14:34:49 -05:00
Arusekk 2d48220165 Enhance the tests 2020-06-05 11:05:04 +02:00
Arusekk 4d9242ae89 Merge branch 'beta' into dev 2020-06-05 10:50:59 +02:00
heapcrash fae86c3dec Remove demo link
Fixes #1495
2020-06-05 01:52:07 -05:00
heapcrash 24211219d8 Use tmux or screen if the environment variables are present, even if we detect an X11 terminal.
See #1261 for original comments
2020-06-05 01:47:16 -05:00
Yonghwi Jin 2c0d63b569 Cache iter_symbols and iter_sections 2020-06-05 01:41:35 -05:00
heapcrash e254c5fa62 Increase fetch depth to 100 to increase cache hits
AVD installation is one of the longest parts of the CI process
2020-06-05 01:20:19 -05:00
heapcrash aba16247b4 Add workaround for #1538 until Unicorn is fixed 2020-06-05 01:19:28 -05:00
Heap Crash 6fc0914dc0 Convert logging status messages to text (#1540)
Fixes #1510
2020-06-05 01:08:32 -05:00
Heap Crash 8137494932 Make Github Actions pass, even if we have to disable some things (#1546)
* Disable corefile tests for Github Actions

* Disable the UI tests, as theyre broken

* Install gdbserver

* Rename step

* Remove SIGALARM to see if it fixes tests

* Set PWNLIB_NOTERM for command-line runs
2020-06-05 00:41:48 -05:00
Arusekk baad3927b9 Merge branch 'beta' into dev 2020-06-04 00:00:35 +02:00
Arusekk 94647d6c10 Merge branch 'beta' into dev 2020-06-03 23:32:08 +02:00
mauricesvp e1aedff092 remove unused argument and add missing documentation 2020-05-31 01:45:46 -05:00
Antinomique 8a2b77131e Repair download_dir 2020-05-29 15:23:00 -05:00
heapcrash b5dd858897 Update issue templates 2020-05-29 15:19:00 -05:00
heapcrash 70d42fb076 Update issue templates 2020-05-29 15:15:57 -05:00
heapcrash 9ede4b8eea Add "Question" issue template 2020-05-29 15:08:10 -05:00
laydervus d944a9ec68 __str__ to __bytes__ in python2 (#1521) 2020-05-29 11:50:38 +02:00
Jinmo bbd82ac6fe Initialize unicorn outside loop in plt emulation (#1515) 2020-05-28 23:17:01 +02:00
layderv 4439849d66 ROP representation with short chars (#1505)
Closes #1494
2020-05-28 15:33:13 +02:00
Sacha KOZMA 061d0fd953 Take numbwritten bytes into account in FmtString (#1471)
The number of bytes already written is now taken into account when executing format string writes.
2020-05-27 23:06:46 +02:00
Bruce Chen 43c4eef53b Fix CHANGELOG.md (#1504)
* Fix bunch of invalid PR/commit link  
* Merge two 3.12.1 into one 3.12.1  
* Add 3.12.2
2020-05-27 22:14:20 +02:00
peace-maker ef40a31ac8 Support opening of new windows in WSL (#1503)
Detect if pwntools is running in a Windows Subsystem for Linux "VM" and set the terminal to open a new `cmd.exe` window on the host.

This replaces the need to add `context.terminal = ['cmd.exe', '/c', 'start', 'ubuntu', 'run']` to every script.

Debugging using `gdb.attach` under WSL with gdb in a new window out of the box!
2020-05-27 22:11:01 +02:00
Arusekk 59ce329431 Begin working on 4.3.0 2020-05-08 14:27:09 +02:00
640 changed files with 6142 additions and 2581 deletions

No files matched your search

+3 -2
View File
@@ -7,5 +7,6 @@ omit =
source =
pwn
pwnlib
~/.pwntools-cache-2.7/
~/.pwntools-cache-3.8/
~/.cache/.pwntools-cache-2.7/
~/.cache/.pwntools-cache-3.8/
disable_warnings = module-not-imported
+1 -1
View File
@@ -12,7 +12,7 @@ Thanks for contributing to Pwntools! Ideas from the community help make Pwntoo
If you've got an idea for a new feature, please provide information about:
* What the feature does
* Why the feature should exit
* Why the feature should exist
* What tests should be included
If you think you can write the feature yourself, please submit a Pull Request and we can review your changes!
+60
View File
@@ -0,0 +1,60 @@
name: Android Tests
on: [push, pull_request]
jobs:
test:
strategy:
matrix:
python-version: [3.8]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 30
steps:
- uses: actions/checkout@v2
- name: Cache for pip
uses: actions/cache@v1
id: cache-pip
with:
path: ~/.cache/pip
key: ${{ matrix.os }}-cache-pip
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 \
gdb gdbserver socat \
qemu-user-static \
binutils-aarch64-linux-gnu \
binutils-arm-linux-gnueabihf \
libc6-dbg \
openjdk-8-jre-headless
- name: Install Android AVD
run: |
USER=travis source travis/setup_avd.sh
sed -i 's/skip_android = True/skip_android = False/' docs/source/conf.py
set | egrep '^(ANDROID|PATH)' >.android.env
- name: Install dependencies
run: |
pip install --upgrade pip
python setup.py egg_info
pip install --upgrade --editable .
- name: Sanity checks
run: PWNLIB_NOTERM=1 python -c 'from pwn import *; print(pwnlib.term.term_mode)'
- name: Install documentation dependencies
run: pip install -r docs/requirements.txt
- name: Coverage Doctests (Android Only)
run: |
source .android.env
PWNLIB_NOTERM=1 coverage run -m sphinx -b doctest docs/source docs/build/doctest docs/source/adb.rst
+2 -2
View File
@@ -4,7 +4,7 @@ env:
GITHUB_BASE: origin/${{ github.event.pull_request.base.ref }}
jobs:
build:
check:
strategy:
matrix:
os: [ubuntu-latest]
@@ -20,7 +20,7 @@ jobs:
if git log --stat ${GITHUB_BASE}..HEAD | grep CHANGELOG.md; then
echo 'Changelog updated :D'
else
if git log --stat ${GITHUB_BASE}..HEAD | grep '++\|--'; then
if git log --stat ${GITHUB_BASE}..HEAD pwnlib pwn | grep '++\|--'; then
echo 'Major changes detected, changelog required!'
false
else
+32 -43
View File
@@ -14,8 +14,10 @@ jobs:
with:
fetch-depth: 0
- name: Git History 2
run: git log --oneline --graph -10
- name: Git History
run: |
git fetch origin
git log --oneline --graph -10
- name: Cache for pip
uses: actions/cache@v1
@@ -42,28 +44,7 @@ jobs:
[ "$vsetup" = "$vpwnlib" ]
[ "$GITHUB_TAG" = "$vsetup" ]
- name: Detect whether java is needed
id: java-needed
env:
GITHUB_REF: ${{ github.event.ref }}
GITHUB_COMMIT_RANGE: ${{ github.event.before }}...${{ github.event.after }}
run: |
if echo "$GITHUB_REF" | grep -Eq 'staging|tags'; then
echo "Found release or important branch ($GITHUB_REF), forcing tests."
elif ! git show "$GITHUB_COMMIT_RANGE" >/dev/null; then
echo 'Incorrect commit range, forcing android tests.'
elif git log --stat "$GITHUB_COMMIT_RANGE" | grep -iE 'android|\<adb\>'; then
echo 'Found Android-related commits, forcing tests.'
else
# clear files that cause Android doctests
: > docs/source/adb.rst > docs/source/protocols/adb.rst
exit 0
fi
echo ::set-output name=need::openjdk-8-jre-headless
- name: Install Linux dependencies
env:
ANDROID_JRE: ${{ steps.java-needed.outputs.need }}
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 \
@@ -73,16 +54,25 @@ jobs:
binutils-aarch64-linux-gnu \
binutils-arm-linux-gnueabihf \
binutils-mips-linux-gnu \
binutils-msp430 \
binutils-powerpc-linux-gnu \
binutils-s390x-linux-gnu \
binutils-sparc64-linux-gnu \
gcc-multilib \
libc6-dbg \
$ANDROID_JRE
libc6-dbg
- name: Install android avd
if: steps.java-needed.outputs.need
- name: Install RPyC for GDB
run: |
USER=travis source travis/install.sh
set | egrep '^(ANDROID|PATH)' >.android.env
sudo apt-get install -y python3-pip
/usr/bin/python3 -m pip install rpyc
- name: Testing Corefiles
run: |
ulimit -a
ulimit -c unlimited
cat /proc/sys/kernel/core_pattern
cat /proc/sys/kernel/core_uses_pid
( cd $(mktemp -d); sh -c 'kill -11 $$' || true; ls -la ./*core* /var/crash/*.crash;) || true
- name: Set up SSH
run: |
@@ -96,39 +86,37 @@ jobs:
pip install --upgrade --editable .
- name: Sanity checks
run: PWNLIB_NOTERM=1 python -c 'from pwn import *; print(pwnlib.term.term_mode)'
run: PWNLIB_NOTERM=1 python -bb -c 'from pwn import *; print(pwnlib.term.term_mode)'
- name: Install documentation dependencies
run: pip install -r docs/requirements.txt
- name: Disable broken tests
run: |
rm -f docs/source/elf/corefile.rst
- name: Manually install non-broken Unicorn
run: pip install unicorn==1.0.2rc3
- name: Disable yama ptrace_scope
run: |
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope # required by some gdb doctests
- name: Coverage doctests
run: |
source .android.env || :
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope # required by some gdb doctests
PWNLIB_NOTERM=1 coverage run -m sphinx -b doctest docs/source docs/build/doctest
PWNLIB_NOTERM=1 python -bb -m coverage run -m sphinx -b doctest docs/source docs/build/doctest
- name: Coverage running examples
run: |
export TERM=linux
set -x
python travis/coverage_chdir.py examples/fmtstr examples/fmtstr/exploit.py
python travis/coverage_chdir.py examples/fmtstr examples/fmtstr/exploit2.py || : # can fail randomly?
coverage run examples/asm.py
coverage run examples/asm.py
coverage run examples/text.py
python -bb travis/coverage_chdir.py examples/fmtstr examples/fmtstr/exploit.py
python -bb travis/coverage_chdir.py examples/fmtstr examples/fmtstr/exploit2.py || : # can fail randomly?
python -bb -m coverage run examples/asm.py
python -bb -m coverage run examples/asm.py
python -bb -m coverage run examples/text.py
# for f in examples/sigreturn_corefile_*.py; do coverage run "$f"; done # XXX something is wrong
- name: Coverage running commandline tools
run: |
export TERM=linux
pwn() { ( set +x; cmd=$1; shift; PYTHONUNBUFFERED=1 exec coverage run -m pwnlib.commandline."$cmd" "$@" ) }
pwn() { ( set +x; cmd=$1; shift; PYTHONUNBUFFERED=1 exec python -bb -m coverage run -m pwnlib.commandline."$cmd" "$@" ) }
set -x
pwn cyclic 32
@@ -199,6 +187,7 @@ jobs:
TARGET=${BRANCH%-staging}
git branch -f "$TARGET"
git push origin "$TARGET"
git push origin --delete "$BRANCH"
pypi:
runs-on: ubuntu-latest
+8 -6
View File
@@ -11,9 +11,6 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Cache for pip
uses: actions/cache@v1
id: cache-pip
@@ -26,8 +23,13 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- name: Lint
- name: Critical lint
run: |
pip install flake8
flake8 . --count --select=E9,F63,F7 --show-source --statistics --exclude=android-?dk # TODO: Add F82
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics --exclude=pwnlib/constants,android-?dk,.git,__pycache__
flake8 . --count --select=E9,F63,F7,E71 --show-source --statistics --exclude=android-?dk # TODO: Add F82
- name: Style lint
run: |
flake8 pwnlib setup.py docs travis --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
flake8 examples --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics --ignore='F403,F405'
flake8 pwn --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics --ignore='F401,F403,F405'
+37
View File
@@ -0,0 +1,37 @@
name: PyLint
on: [pull_request]
jobs:
build:
strategy:
matrix:
python-version: [3.8]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 30
steps:
- uses: actions/checkout@v2
- name: Cache for pip
uses: actions/cache@v1
id: cache-pip
with:
path: ~/.cache/pip
key: ${{ matrix.os }}-cache-pip
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: PyLint
run: |
set -x
pip install pylint
pip install --upgrade -r requirements.txt
pylint --exit-zero --errors-only pwnlib > current.txt
git fetch origin
git checkout origin/"$GITHUB_BASE_REF"
pylint --exit-zero --errors-only pwnlib > base.txt
if diff base.txt current.txt | grep '>'; then
false
fi
+3
View File
@@ -17,3 +17,6 @@ venv
*.core
.coverage
.coverage.*
.idea
__pycache__
!.github
+5
View File
@@ -19,8 +19,12 @@ addons:
- binutils-aarch64-linux-gnu
- binutils-arm-linux-gnueabihf
- binutils-mips-linux-gnu
- binutils-msp430
- binutils-powerpc-linux-gnu
- binutils-s390x-linux-gnu
- binutils-sparc64-linux-gnu
- bash-static
- python3-pip
cache:
- pip
- directories:
@@ -39,6 +43,7 @@ before_install:
- source travis/ssh_setup.sh
- echo $-
install:
- /usr/bin/python3 -m pip install rpyc # for GDB
- pip install --upgrade pip
- pip install --upgrade flake8 appdirs # https://github.com/ActiveState/appdirs/issues/89#issuecomment-282326570
- python setup.py egg_info # pypa/pip#6275
+154 -7
View File
@@ -9,9 +9,15 @@ The table below shows which release corresponds to each branch, and what date th
| Version | Branch | Release Date |
| ---------------- | -------- | ---------------------- |
| [4.4.0](#440) | `dev` | Sep 1, 2020 (planned)
| [4.3.0](#430) | `beta` | Aug 1, 2020 (planned)
| [4.2.0](#420) | `stable` | Jul 3, 2020 (planned)
| [4.8.0](#480) | `dev` |
| [4.7.0](#470) | `beta` |
| [4.6.0](#460) | `stable` | Jul 12, 2021
| [4.5.1](#451) | | May 30, 2021
| [4.5.0](#450) | | Apr 30, 2021
| [4.4.0](#440) | | Mar 29, 2021
| [4.3.1](#431) | | Nov 29, 2020
| [4.3.0](#430) | | Oct 20, 2020
| [4.2.0](#420) | | Jul 3, 2020
| [4.1.7](#417) | | Jun 30, 2020
| [4.1.5](#415) | | Jun 27, 2020
| [4.1.4](#414) | | Jun 26, 2020
@@ -55,13 +61,152 @@ The table below shows which release corresponds to each branch, and what date th
| [3.0.0](#300) | | Aug 20, 2016
| [2.2.0](#220) | | Jan 5, 2015
## 4.4.0 (`dev`)
## 4.8.0 (`dev`)
## 4.7.0 (`beta`)
- [#1733][1733] Update libc headers -> more syscalls available!
- [#1876][1876] add `self.message` and change `sys.exc_type` to `sys.exec_info()` in PwnlibException
- [#1877][1877] encoders error message handles when `avoid` is bytes in python3
- [#1891][1891] Keep ROP gadgets when setting registers via setattr/call
- [#1892][1892] Silence SIGPIPE error for "pwn phd"
- [#1893][1893] Fix bytes warning in "pwn cyclic"
- [#1897][1897] Add basic support for RISC-V
- [#1903][1903] Add zsh completion script
- [#1904][1904] Add bash completion script
- [#1906][1906] Defer import of several modules to save on startup time
- [#1921][1921] Add basic support for the bare-metal ARM specific toolchain
[1733]: https://github.com/Gallopsled/pwntools/pull/1733
[1876]: https://github.com/Gallopsled/pwntools/pull/1876
[1877]: https://github.com/Gallopsled/pwntools/pull/1877
[1891]: https://github.com/Gallopsled/pwntools/pull/1891
[1892]: https://github.com/Gallopsled/pwntools/pull/1892
[1893]: https://github.com/Gallopsled/pwntools/pull/1893
[1897]: https://github.com/Gallopsled/pwntools/pull/1897
[1903]: https://github.com/Gallopsled/pwntools/pull/1903
[1904]: https://github.com/Gallopsled/pwntools/pull/1904
[1906]: https://github.com/Gallopsled/pwntools/pull/1906
[1921]: https://github.com/Gallopsled/pwntools/pull/1921
## 4.6.0 (`stable`)
- [#1429][1429] Add a mechanism for ret2csu (originally #1138)
- [#1566][1566] Add `ignore_config` argument to `pwnlib.tubes.ssh` and improve `allow_agent` implementation
- [#1652][1652] Add `process.readmem` and `process.writemem`
- [#1739][1739] Add/fix shellcraft.linux.kill() / shellcraft.linux.killparent()
- [#1746][1746] Prefer Python3 over Python2 for spawning remote processes over SSH
- [#1751][1751] Fix process() with executable relative to cwd
- [#1753][1753] major change: less unconditional imports in pwnlib
- [#1776][1776] mips: do not use $t0 temporary variable in dupio
- [#1846][1846] support launching GDB in more different terminals
[1429]: https://github.com/Gallopsled/pwntools/pull/1429
[1566]: https://github.com/Gallopsled/pwntools/pull/1566
[1652]: https://github.com/Gallopsled/pwntools/pull/1652
[1739]: https://github.com/Gallopsled/pwntools/pull/1739
[1746]: https://github.com/Gallopsled/pwntools/pull/1746
[1751]: https://github.com/Gallopsled/pwntools/pull/1751
[1753]: https://github.com/Gallopsled/pwntools/pull/1753
[1776]: https://github.com/Gallopsled/pwntools/pull/1776
[1846]: https://github.com/Gallopsled/pwntools/pull/1846
## 4.5.1
- [#1902][1902] Always specify -F and -P for tmux in `run_in_new_terminal`
[1902]: https://github.com/Gallopsled/pwntools/pull/1902
## 4.5.0
- [#1261][1261] Misc `run_in_new_terminal` improvements (notably gdb terminated by default)
- [#1695][1695] Allow using GDB Python API
- [#1735][1735] Python 3.9 support in safeeval
- [#1738][1738] Which function support custom search path
- process also looks now at `env['PATH']` to find the path for the executable
- [#1742][1742] New `baremetal` os to debug binaries executed with qemu-system-$(arch)
- [#1757][1757] update cache directories
- [#1758][1758] Remove eval from cli
- [#1780][1780] Re-add Python2 to the official Dockerfile
- [#1941][1941] Disable all Android tests, `pwnlib.adb` is no longer supported in CI
- [#1811][1811] Remove unnecessary `pwn.toplevel.__all__`
- [#1827][1827] Support `$XDG_CONFIG_HOME` dir for `pwn.conf`
- [#1841][1841] Add colored_traceback
- [#1839][1839] run_in_new_terminal now creates a runner script if given a list or tuple
- [#1833][1833] Add pwnlib.filesystem module
- [#1852][1852] Fix `atexit` on Python 3
- [#1883][1883] ROP gadget verifier accounts for 2 character registers
[1261]: https://github.com/Gallopsled/pwntools/pull/1261
[1695]: https://github.com/Gallopsled/pwntools/pull/1695
[1735]: https://github.com/Gallopsled/pwntools/pull/1735
[1738]: https://github.com/Gallopsled/pwntools/pull/1738
[1742]: https://github.com/Gallopsled/pwntools/pull/1742
[1757]: https://github.com/Gallopsled/pwntools/pull/1757
[1758]: https://github.com/Gallopsled/pwntools/pull/1758
[1780]: https://github.com/Gallopsled/pwntools/pull/1780
[1941]: https://github.com/Gallopsled/pwntools/pull/1941
[1811]: https://github.com/Gallopsled/pwntools/pull/1811
[1827]: https://github.com/Gallopsled/pwntools/pull/1827
[1841]: https://github.com/Gallopsled/pwntools/pull/1841
[1839]: https://github.com/Gallopsled/pwntools/pull/1839
[1833]: https://github.com/Gallopsled/pwntools/pull/1833
[1852]: https://github.com/Gallopsled/pwntools/pull/1852
[1883]: https://github.com/Gallopsled/pwntools/pull/1883
## 4.4.0
- [#1541][1541] Use `context.newline` for tubes by default
- [#1602][1602] Fix bytes handling in ssh tubes
- [#1606][1606] Fix `asm()` and `disasm()` for MSP430, S390
- [#1616][1616] Fix `cyclic` cli for 64 bit integers
- [#1632][1632] Enable usage of Pwntools in jupyter
- [#1633][1633] Open a shell if `pwn template` cannot download the remote file
- [#1644][1644] Enable and support SNI for SSL-wrapped tubes
- [#1651][1651] Make `pwn shellcraft` faster
- [#1654][1654] Docker images (`pwntools/pwntools:stable` etc) now use Python3 by default, and includes assemblers for a few common architectures
- [#1667][1667] Add i386 encoder `ascii_shellcode` (Fixed docs in #1693)
- Fix syscall instruction lists for SROP on `i386` and `amd64`
- Fix migration to another ROP
- [#1673][1673] Add `base=` argument to `ROP.chain()` and `ROP.dump()`
- [#1675][1675] Gdbserver now correctly accepts multiple libraries in `LD_PRELOAD` and `LD_LIBRARY_PATH`
- [#1678][1678] ROPGadget multibr
- [#1682][1682] ROPGadget multibr fix
- [#1687][1687] Actually import `requests` when doing `from pwn import *`
- [#1688][1688] Add `__setattr__` and `__call__` interfaces to `ROP` for setting registers
- [#1692][1692] Remove python2 shebangs where appropriate
- [#1703][1703] Update libcdb buildid offsets for amd64 and i386
- [#1704][1704] Try https://libc.rip/ for libcdb lookup
[1541]: https://github.com/Gallopsled/pwntools/pull/1541
[1602]: https://github.com/Gallopsled/pwntools/pull/1602
[1606]: https://github.com/Gallopsled/pwntools/pull/1606
[1616]: https://github.com/Gallopsled/pwntools/pull/1616
[1632]: https://github.com/Gallopsled/pwntools/pull/1632
[1633]: https://github.com/Gallopsled/pwntools/pull/1633
[1644]: https://github.com/Gallopsled/pwntools/pull/1644
[1651]: https://github.com/Gallopsled/pwntools/pull/1651
[1654]: https://github.com/Gallopsled/pwntools/pull/1654
[1667]: https://github.com/Gallopsled/pwntools/pull/1667
[1673]: https://github.com/Gallopsled/pwntools/pull/1673
[1675]: https://github.com/Gallopsled/pwntools/pull/1675
[1678]: https://github.com/Gallopsled/pwntools/pull/1678
[1682]: https://github.com/Gallopsled/pwntools/pull/1679
[1687]: https://github.com/Gallopsled/pwntools/pull/1687
[1688]: https://github.com/Gallopsled/pwntools/pull/1688
[1692]: https://github.com/Gallopsled/pwntools/pull/1692
[1703]: https://github.com/Gallopsled/pwntools/pull/1703
[1704]: https://github.com/Gallopsled/pwntools/pull/1704
## 4.3.0 (`beta`)
## 4.3.1
- [#1732][1732] Fix shellcraft SSTI vulnerability (first major pwntools vuln!)
[1732]: https://github.com/Gallopsled/pwntools/pull/1732
## 4.3.0
- [#1576][1576] Add `executable=` argument to `ELF.search`
- [#1584][1584] Add `jmp_esp`/`jmp_rsp` attribute to `ROP`
@@ -70,6 +215,7 @@ The table below shows which release corresponds to each branch, and what date th
- [#1601][1601] Add `pwn version` command line tool
- [#1605][1605] Add to `fiddling.hexdump` a way to suppress the total at the end
- [#1613][1613] Permit `--password` for `pwn template`
- [#1616][1616] Fix `cyclic` cli for 64 bit integers
- [#1564][1564] Fix `asm()` and `disasm()` for PowerPC64, MIPS64, Sparc64
- [#1621][1621] Permit negative values in flat() and fit()
@@ -80,10 +226,11 @@ The table below shows which release corresponds to each branch, and what date th
[1601]: https://github.com/Gallopsled/pwntools/pull/1601
[1605]: https://github.com/Gallopsled/pwntools/pull/1605
[1613]: https://github.com/Gallopsled/pwntools/pull/1613
[1616]: https://github.com/Gallopsled/pwntools/pull/1616
[1564]: https://github.com/Gallopsled/pwntools/pull/1564
[1621]: https://github.com/Gallopsled/pwntools/pull/1621
## 4.2.1 (`stable`)
## 4.2.1
- [#1625][1625] GDB now properly loads executables with QEMU
- [#1663][1663] Change lookup algorithm of `adb.which`
@@ -157,7 +304,7 @@ The table below shows which release corresponds to each branch, and what date th
[1001]: https://github.com/Gallopsled/pwntools/pull/1001
[1389]: https://github.com/Gallopsled/pwntools/pull/1389
[1241]: https://github.com/Gallopsled/pwntools/pull/1241
[1218]: https://github.com/Gallopsled/pwntools/pull/1218
[1218]: https://github.com/Gallopsled/pwntools/pull/1218
## 4.0.1
+76
View File
@@ -0,0 +1,76 @@
# Using Pwntools with Docker
Sometimes it's annoying to set up Pwntools on your workstation, and you want something that Just Works (TM).
[Docker](https://www.docker.com/) is here to the rescue! Using Docker means that you get a nice, standardized Linux environment and don't need to worry about pip or installing dependencies.
## Quick Start
First, install Docker for your OS, which you can find on their [Getting Started](https://www.docker.com/get-started) page.
Next, download and run the Pwntools stable docker image.
```sh
$ docker run -it pwntools/pwntools:stable
```
## Recommended Settings
In order to get the most from your docker image, we need to enable debugging of processes (`--privileged`) and expose the network ports from the guest to the host (`--net=host`).
```sh
$ docker run -it \
--privileged \
--net=host \
--hostname localhost \
--ulimit core=-1:-1 \
pwntools/pwntools:stable
```
## Sharing a Folder
It's really nice to be able to use your preferred native editor, and have the changes show up live inside your Docker image. This is easy to add, thanks to Docker's bind mounts (`--mount type=bind`).
With the command below, your `~/exploits` directory will magically show up inside the Docker image at `/home/pwntools/exploits` so that you can easily run them (from Docker) and edit them (from outside Docker).
```sh
$ mkdir $HOME/exploits
$ vim $HOME/exploits/my_exploit.py
$ docker run -it \
--privileged \
--net=host \
--hostname localhost \
--ulimit core=-1:-1 \
--mount type=bind,source="$HOME/exploits",target=/home/pwntools/exploits \
pwntools/pwntools:stable
$ python3 exploits/my_exploit.py
```
### Windows User Bind Mounts
If you're a Windows user `$HOME` doesn't exist in the same way as on Linux, instead it is `%UserProfile%`. The command from above would look like this, assuming your editor is Visual Studio Code and you have code.exe in your `%PATH%`.
```sh
C:\Users\user> mkdir Desktop\exploits
C:\Users\user> code Desktop\exploits\my_exploit.py
C:\Users\user> docker run -it \
--privileged \
--net=host \
--hostname localhost \
--ulimit core=-1:-1 \
--mount type=bind,source="%UserProfile%\Desktop\exploits",target=/home/pwntools/exploits \
pwntools/pwntools:stable
$ python3 exploits/my_exploit.py
```
+14 -16
View File
@@ -1,12 +1,14 @@
# pwntools - CTF toolkit
![pwntools logo](https://github.com/Gallopsled/pwntools/blob/stable/docs/source/logo.png?raw=true)
[![Docs](https://readthedocs.org/projects/pwntools/badge/?version=stable)](https://docs.pwntools.com/)
[![PyPI](https://img.shields.io/pypi/v/pwntools?style=flat)](https://pypi.python.org/pypi/pwntools/)
[![Travis](https://travis-ci.org/Gallopsled/pwntools.svg)](https://travis-ci.org/Gallopsled/pwntools)
[![Coveralls](https://img.shields.io/coveralls/Gallopsled/pwntools/dev.svg)](https://coveralls.io/github/Gallopsled/pwntools?branch=dev)
[![Twitter](https://img.shields.io/badge/twitter-pwntools-4099FF.svg?style=flat)](https://twitter.com/pwntools)
[![Docs](https://readthedocs.org/projects/pwntools/badge/?version=stable)](https://docs.pwntools.com/)
[![Travis](https://img.shields.io/travis/Gallopsled/pwntools/dev?logo=Travis)](https://travis-ci.org/Gallopsled/pwntools)
[![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/Gallopsled/pwntools/Continuous%20Integration/dev?logo=GitHub)](https://github.com/Gallopsled/pwntools/actions?query=workflow%3A%22Continuous+Integration%22+branch%3Adev)
[![Coveralls](https://img.shields.io/coveralls/github/Gallopsled/pwntools/dev?logo=coveralls)](https://coveralls.io/github/Gallopsled/pwntools?branch=dev)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://choosealicense.com/licenses/mit/)
[![Discord](https://img.shields.io/discord/809590285687980052?label=Discord&style=plastic)](https://discord.gg/96VA2zvjCB)
[![Twitter](https://img.shields.io/twitter/follow/Pwntools)](https://twitter.com/pwntools)
Pwntools is a CTF framework and exploit development library. Written in Python, it is designed for rapid prototyping and development, and intended to make exploit writing as simple as possible.
@@ -20,29 +22,28 @@ r.send(asm(shellcraft.sh()))
r.interactive()
```
# Try It Now!
You can now do a live demo of Pwntools, [right in your browser](https://demo.pwntools.com).
# Documentation
Our documentation is available at [docs.pwntools.com](https://docs.pwntools.com/)
A series of tutorials is also [available online](https://github.com/Gallopsled/pwntools-tutorial#readme)
To get you started, we've provided some example solutions for past CTF challenges in our [write-ups repository](https://github.com/Gallopsled/pwntools-write-ups).
# Installation
Pwntools is best supported on 64-bit Ubuntu LTE releases (12.04, 14.04, 16.04 and 18.04). Most functionality should work on any Posix-like distribution (Debian, Arch, FreeBSD, OSX, etc.). Python >= 2.7 is required (Python 3 suggested as best).
Pwntools is best supported on 64-bit Ubuntu LTS releases (14.04, 16.04, 18.04, and 20.04). Most functionality should work on any Posix-like distribution (Debian, Arch, FreeBSD, OSX, etc.).
Most of the functionality of pwntools is self-contained and Python-only. You should be able to get running quickly with
Python3 is suggested, but Pwntools still works with Python 2.7. Most of the functionality of pwntools is self-contained and Python-only. You should be able to get running quickly with
```sh
apt-get update
apt-get install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade git+https://github.com/Gallopsled/pwntools.git@dev
python3 -m pip install --upgrade pwntools
```
However, some of the features (assembling/disassembling foreign architectures) require non-Python dependencies. For more information, see the [complete installation instructions here](https://docs.pwntools.com/en/stable/install.html).
@@ -50,8 +51,5 @@ However, some of the features (assembling/disassembling foreign architectures) r
See [CONTRIBUTING.md](CONTRIBUTING.md)
# Contact
If you have any questions not worthy of a [bug report](https://github.com/Gallopsled/pwntools/issues), feel free to ping us
at [`#pwntools` on Freenode](irc://irc.freenode.net/pwntools) and ask away.
Click [here](https://kiwiirc.com/client/irc.freenode.net/pwntools) to connect.
There is also a [mailing list](https://groups.google.com/forum/#!forum/pwntools-users) for higher latency discussion.
# Contact and Community
If you have any questions not worthy of a [bug report](https://github.com/Gallopsled/pwntools/issues), join the Discord server at https://discord.gg/96VA2zvjCB
+1 -1
View File
@@ -45,7 +45,7 @@ help:
clean:
-rm -rf $(BUILDDIR)/*
-rm -rf /tmp/user/pwn*
-rm -rf $(HOME)/.pwntools-cache
-rm -rf $(HOME)/.cache/.pwntools-cache
-rm -rf /tmp/pwn* 2>/dev/null || true
-rm -rf build
+2 -2
View File
@@ -11,7 +11,7 @@ pypandoc
pyserial>=2.7
requests>=2.5.1
ropgadget>=5.3
sphinx
sphinx<3.4
sphinx_rtd_theme
sphinxcontrib-napoleon
sphinxcontrib-autoprogram
sphinxcontrib-autoprogram<=0.1.5
+1 -6
View File
@@ -2,12 +2,7 @@
import tempfile
import subprocess
from pwnlib.context import context
from pwnlib.asm import *
from pwnlib import shellcraft
from pwnlib.tubes.process import process
from pwnlib.util.fiddling import unhex
from pwn import *
:mod:`pwnlib.asm` --- Assembler functions
=========================================
+2
View File
@@ -12,6 +12,8 @@ Command Line Tools
pwntools comes with a handful of useful command-line utilities which serve as wrappers for some of the internal functionality.
If these tools do not appear to be installed, make sure that you have added ``~/.local/bin`` to your ``$PATH`` environment variable.
.. toctree::
.. autoprogram:: pwnlib.commandline.main:parser
+36 -14
View File
@@ -25,7 +25,8 @@ build_dash = tags.has('dash')
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../..'))
import pwnlib
import pwnlib.update
pwnlib.update.disabled = True
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
@@ -70,10 +71,14 @@ doctest_global_setup = '''
import sys, os
os.environ['PWNLIB_NOTERM'] = '1'
os.environ['PWNLIB_RANDOMIZE'] = '0'
import pwnlib, logging
import pwnlib.update
import pwnlib.util.fiddling
import logging
pwnlib.update.disabled = True
pwnlib.context.context.reset_local()
pwnlib.context.ContextType.defaults['log_level'] = logging.ERROR
pwnlib.context.ContextType.defaults['randomize'] = False
# pwnlib.context.ContextType.defaults['terminal'] = ['sh', '-c']
pwnlib.util.fiddling.default_style = {}
pwnlib.term.text.when = 'never'
pwnlib.log.install_default_handler()
@@ -91,6 +96,9 @@ pwnlib.context.ContextType.defaults['log_console'] = stdout()
github_actions = os.environ.get('USER') == 'runner'
travis_ci = os.environ.get('USER') == 'travis'
local_doctest = os.environ.get('USER') == 'pwntools'
branch_dev = os.environ.get('GITHUB_BASE_REF') == 'dev'
skip_android = True
'''
autoclass_content = 'both'
@@ -257,7 +265,7 @@ latex_documents = [
u'2016, Gallopsled et al.', 'manual'),
]
intersphinx_mapping = {'python': ('https://docs.python.org/2.7', None),
intersphinx_mapping = {'python': ('https://docs.python.org/3.8', None),
'paramiko': ('https://paramiko-docs.readthedocs.org/en/2.1/', None)}
# The name of an image file (relative to this directory) to place at the top of
@@ -340,7 +348,7 @@ def linkcode_resolve(domain, info):
val = mod
for k in info['fullname'].split('.'):
val = getattr(val, k, None)
if val == None:
if val is None:
break
# Special case for shellcraft
@@ -381,7 +389,9 @@ import sphinx.ext.autodoc
# Test hidden members (e.g. def _foo(...))
def dont_skip_any_doctests(app, what, name, obj, skip, options):
return False
return None
autodoc_default_options = {'special-members': None, 'private-members': None}
class _DummyClass(object): pass
@@ -403,24 +413,36 @@ class Py2OutputChecker(_DummyClass, doctest.OutputChecker):
if sup(rly_want, got, optionflags):
return True
rly_want = ' '.join(x[:2].replace('b"',' "').replace("b'"," '")+x[2:] for x in want.replace('\n','\n ').split(' ')).replace('\n ','\n')
return sup(rly_want, got, optionflags)
if sup(rly_want, got, optionflags):
return True
for wantl, gotl in six.moves.zip_longest(want.splitlines(), got.splitlines(), fillvalue=''):
rly_want1 = '['.join(x[:2].replace('b"','"').replace("b'","'")+x[2:] for x in wantl.split('['))
rly_want2 = ' '.join(x[:2].replace('b"',' "').replace("b'"," '")+x[2:] for x in wantl.split(' '))
if not sup(rly_want1, gotl, optionflags) and not sup(rly_want2, gotl, optionflags):
return False
return True
def py2_doctest_init(self, checker=None, verbose=None, optionflags=0):
if checker is None:
checker = Py2OutputChecker()
doctest.DocTestRunner.__init__(self, checker, verbose, optionflags)
class EndlessLoop(Exception): pass
def alrm_handler(sig, frame):
signal.alarm(180) # three minutes
raise EndlessLoop()
signal.signal(signal.SIGALRM, alrm_handler)
signal.alarm(600) # ten minutes
if 'doctest' in sys.argv:
def setup(app):
app.connect('autodoc-skip-member', dont_skip_any_doctests)
pass # app.connect('autodoc-skip-member', dont_skip_any_doctests)
if sys.version_info[:1] < (3,):
import sphinx.ext.doctest
sphinx.ext.doctest.SphinxDocTestRunner.__init__ = py2_doctest_init
else:
# monkey patching paramiko due to https://github.com/paramiko/paramiko/pull/1661
import paramiko.client
import binascii
paramiko.client.hexlify = lambda x: binascii.hexlify(x).decode()
paramiko.util.safe_string = lambda x: '' # function result never *actually used*
class EndlessLoop(Exception): pass
def alrm_handler(sig, frame):
signal.alarm(180) # three minutes
raise EndlessLoop()
signal.signal(signal.SIGALRM, alrm_handler)
signal.alarm(600) # ten minutes
+16
View File
@@ -3,6 +3,22 @@
from glob import glob
from pwn import *
# The Linux kernel won't overwrite an existing corefile, so in case
# some other part of the doctests caused a segfault and core dump,
# we need to get rid of it before our tests run.
#
# We DONT need to worry about e.g. ./core existing when using Corefile()
# because we always move and rename the corefile to prevent this situation.
if os.path.exists('core'):
os.unlink('core')
# bash-static is a statically linked version of bash, but if $SHELL is not
# set to anything, it decides to up and load ld.so and libc.so which breaks
# our example of showing `corefile.libc == None` for a statically linked bin.
# Set the environment here so it's not in the middle of our tests.
os.environ.setdefault('SHELL', '/bin/sh')
:mod:`pwnlib.elf.corefile` --- Core Files
===========================================================
+6 -1
View File
@@ -1,13 +1,18 @@
.. testsetup:: *
from pwn import *
:mod:`pwnlib.encoders` --- Encoding Shellcode
===============================================
.. automodule:: pwnlib.encoders.encoder
:members:
.. automodule:: pwnlib.encoders.i386.ascii_shellcode
:members:
:special-members:
:exclude-members: __init__
.. automodule:: pwnlib.encoders.i386.xor
:members:
+17
View File
@@ -0,0 +1,17 @@
.. testsetup:: *
import time
import six
from pwnlib.context import context
from pwnlib.tubes.ssh import ssh
from pwnlib.filesystem import *
:mod:`pwnlib.filesystem` --- Manipulating Files Locally and Over SSH
====================================================================
Provides a Python2-compatible :py:mod:`pathlib` interface for paths
on the local filesystem (`.Path`) as well as on remote filesystems,
via SSH (`.SSHPath`).
.. automodule:: pwnlib.filesystem
:members:
+10
View File
@@ -55,6 +55,7 @@ Each of the ``pwntools`` modules is documented here.
elf
exception
filepointer
filesystem
flag
fmtstr
gdb
@@ -91,3 +92,12 @@ Each of the ``pwntools`` modules is documented here.
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Bytes
-----
The bytes vs text distinction is so important that it even made it to this main page.
See the pwntools-tutorial_ repo for the latest tutorial finally
explaining the difference once and for all (hopefully).
.. _pwntools-tutorial: https://github.com/Gallopsled/pwntools-tutorial/blob/master/bytes.md
+36 -4
View File
@@ -1,9 +1,7 @@
Installation
============
pwntools is best supported on Ubuntu 12.04 and 14.04, but most
functionality should work on any Posix-like distribution (Debian, Arch,
FreeBSD, OSX, etc.).
Pwntools is best supported on 64-bit Ubuntu LTS releases (14.04, 16.04, 18.04, and 20.04). Most functionality should work on any Posix-like distribution (Debian, Arch, FreeBSD, OSX, etc.).
Prerequisites
-------------
@@ -20,7 +18,10 @@ following system libraries installed.
Released Version
-----------------
pwntools is available as a ``pip`` package.
pwntools is available as a ``pip`` package for both Python2 and Python3.
Python3
^^^^^^^
.. code-block:: bash
@@ -29,6 +30,37 @@ pwntools is available as a ``pip`` package.
$ python3 -m pip install --upgrade pip
$ python3 -m pip install --upgrade pwntools
Python2 (Deprecated)
^^^^^^^^^^^^^^^^^^^^
NOTE: Pwntools maintainers STRONGLY recommend using Python3 for all future Pwntools-based scripts and projects.
Additionally, due to `pip` dropping support for Python2, a specfic version of `pip` must be installed.
.. code-block:: bash
$ apt-get update
$ apt-get install python python-pip python-dev git libssl-dev libffi-dev build-essential
$ python2 -m pip install --upgrade pip==20.3.4
$ python2 -m pip install --upgrade pwntools
Command-Line Tools
------------------
When installed with ``sudo`` the above commands will install Pwntools' command-line tools to somewhere like ``/usr/bin``.
However, if you run as an unprivileged user, you may see a warning message that looks like this:
.. code-block::
WARNING: The scripts asm, checksec, common, constgrep, cyclic, debug, disablenx, disasm,
elfdiff, elfpatch, errno, hex, main, phd, pwn, pwnstrip, scramble, shellcraft, template,
unhex, update and version are installed in '/home/user/.local/bin' which is not on PATH.
Follow the instructions listed and add ``~/.local/bin`` to your ``$PATH`` environment variable.
Development
--------------
+1 -1
View File
@@ -12,7 +12,7 @@ Building `binutils` from source takes about 60 seconds on a modern 8-core machin
Ubuntu
^^^^^^^^^^^^^^^^
For Ubuntu 12.04 through 15.10, you must first add the pwntools `Personal Package Archive repository <http://binutils.pwntools.com>`__.
For Ubuntu 12.04 through 15.10, you must first add the pwntools `Personal Package Archive repository <https://launchpad.net/~pwntools/+archive/ubuntu/binutils>`__.
Ubuntu Xenial (16.04) has official packages for most architectures, and does not require this step.
+10 -3
View File
@@ -17,6 +17,13 @@ assemble, disassemble, pack, unpack, and many other things with a single functio
A full list of everything that is imported is available on :doc:`globals`.
Tutorials
---------
A series of tutorials for Pwntools exists online, at
https://github.com/Gallopsled/pwntools-tutorial#readme
Making Connections
------------------
@@ -188,10 +195,10 @@ Never write another hexdump, thanks to :mod:`pwnlib.util.fiddling`.
Find offsets in your buffer that cause a crash, thanks to :mod:`pwnlib.cyclic`.
>>> print(cyclic(20).decode())
aaaabaaacaaadaaaeaaa
>>> cyclic(20)
b'aaaabaaacaaadaaaeaaa'
>>> # Assume EIP = 0x62616166 (b'faab' which is pack(0x62616166)) at crash time
>>> print(cyclic_find(b'faab'))
>>> cyclic_find(b'faab')
120
ELF Manipulation
-14
View File
@@ -1,15 +1 @@
:mod:`pwnlib.protocols` --- Wire Protocols
=============================================
.. automodule:: pwnlib.protocols
Supported Protocols
-------------------
.. toctree::
:maxdepth: 3
:glob:
protocols/*
-11
View File
@@ -1,11 +0,0 @@
.. testsetup:: *
from pwn import *
from pwnlib.protocols.adb import AdbClient
AdbClient().wait_for_device()
:mod:`pwnlib.protocols.adb` --- ADB Protocol Implementation
===========================================================
.. automodule:: pwnlib.protocols.adb
:members:
-4
View File
@@ -1,7 +1,3 @@
.. testsetup:: *
from pwn import *
:mod:`pwnlib.rop` --- Return Oriented Programming
=================================================
+9
View File
@@ -0,0 +1,9 @@
.. testsetup:: *
from pwnlib.rop.call import *
:mod:`pwnlib.rop.call` --- Return Oriented Programming Function Calling
=======================================================================
.. automodule:: pwnlib.rop.call
:members:
+18 -1
View File
@@ -1,6 +1,23 @@
.. testsetup:: *
from pwn import *
import time
from glob import glob
from pwnlib.asm import asm
from pwnlib import constants
from pwnlib.context import context
from pwnlib.elf import ELF
from pwnlib.rop import ROP
from pwnlib.rop.call import Call, AppendedArgument
from pwnlib.elf.maps import CAT_PROC_MAPS_EXIT
from pwnlib.util.packing import *
from pwnlib.util.fiddling import *
from pwnlib.tubes.process import process
from pwnlib import shellcraft
from pwnlib.util.misc import which
context.clear()
:mod:`pwnlib.rop.rop` --- Return Oriented Programming
==========================================================
+6 -1
View File
@@ -1,6 +1,11 @@
.. testsetup:: *
from pwn import *
from pwnlib.rop.srop import *
from pwnlib import constants
from pwnlib import shellcraft
from pwnlib.elf import ELF
from pwnlib.tubes.process import process
:mod:`pwnlib.rop.srop` --- Sigreturn Oriented Programming
==========================================================
+2 -1
View File
@@ -1,6 +1,7 @@
.. testsetup:: *
from pwn import *
from pwnlib.runner import *
from pwnlib.asm import asm
:mod:`pwnlib.runner` --- Running Shellcode
===========================================
+10 -1
View File
@@ -1,6 +1,15 @@
.. testsetup:: *
from pwn import *
import tempfile
from pwnlib import shellcraft
from pwnlib.asm import asm
from pwnlib.context import context
from pwnlib.runner import run_assembly
from pwnlib.util.fiddling import enhex
from pwnlib.util.misc import write
context.clear(arch='mips')
:mod:`pwnlib.shellcraft.mips` --- Shellcode for MIPS
+4
View File
@@ -14,6 +14,10 @@
:members: kill, poll, interactive
:show-inheritance:
.. autoclass:: pwnlib.tubes.ssh.ssh_process
:members:
:show-inheritance:
.. autoclass:: pwnlib.tubes.ssh.ssh_connecter()
:show-inheritance:
+16 -16
View File
@@ -17,19 +17,19 @@
count ,
cycle ,
dropwhile ,
filter ,
filterfalse ,
groupby ,
ifilter ,
ifilterfalse ,
imap ,
islice ,
izip ,
izip_longest ,
map ,
permutations ,
product ,
repeat ,
starmap ,
takewhile ,
tee
tee ,
zip ,
zip_longest
.. function:: chain
@@ -63,29 +63,29 @@
Alias for :func:`itertools.groupby`
.. function:: ifilter
.. function:: filter
Alias for :func:`itertools.ifilter`
Alias for python3-style :func:`filter`
.. function:: ifilterfalse
.. function:: filterfalse
Alias for :func:`itertools.ifilterfalse`
Alias for :func:`itertools.filterfalse`
.. function:: imap
.. function:: map
Alias for :func:`itertools.imap`
Alias for python3-style :func:`map`
.. function:: islice
Alias for :func:`itertools.islice`
.. function:: izip
.. function:: zip
Alias for :func:`itertools.izip`
Alias for python3-style :func:`zip`
.. function:: izip_longest
.. function:: zip_longest
Alias for :func:`itertools.izip_longest`
Alias for :func:`itertools.zip_longest`
.. function:: permutations
-1
View File
@@ -3,7 +3,6 @@
from pprint import pprint
from pwnlib.util.misc import *
import os, subprocess
os.chdir("..")
:mod:`pwnlib.util.misc` --- We could not fit it any other place
===============================================================
-1
View File
@@ -2,7 +2,6 @@
from pwnlib.util.net import *
:mod:`pwnlib.util.net` --- Networking interfaces
===================================================
+2
View File
@@ -1,5 +1,7 @@
.. testsetup:: *
import tempfile
from pwnlib.context import context
from pwnlib.util.web import *
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""An example of using GDB Python API with Pwntools."""
from pwn import *
def check_write(gdb, exp_buf):
"""Check that write() was called with the expected arguments."""
fd = gdb.parse_and_eval('$rdi').cast(gdb.lookup_type('int'))
assert fd == 1, fd
buf_addr = gdb.parse_and_eval('$rsi').cast(gdb.lookup_type('long'))
count = gdb.parse_and_eval('$rdx').cast(gdb.lookup_type('long'))
buf = gdb.selected_inferior().read_memory(buf_addr, count).tobytes()
assert buf == exp_buf, buf
def demo_sync_breakpoint(cat, gdb, txt):
"""Demonstrate a synchronous breakpoint."""
# set the synchronous breakpoint on ``write``
gdb.Breakpoint('write', temporary=True)
# resume the program
gdb.continue_nowait()
# send the line
cat.sendline(txt)
# wait until we hit the breakpoint
gdb.wait()
# inspect program state
check_write(gdb, (txt + '\n').encode())
# resume the program
gdb.continue_nowait()
# expect to observe the line we just sent
cat.recvuntil(txt)
def demo_async_breakpoint(cat, gdb, txt):
"""Demonstrate asynchronous breakpoint."""
# set the asynchronous breakpoint on ``write``
class WriteBp(gdb.Breakpoint):
def __init__(self):
super().__init__('write')
self.count = 0
def stop(self):
# called in a separate thread
check_write(gdb, (txt + '\n').encode())
self.count += 1
bp = WriteBp()
# resume the program
gdb.continue_nowait()
# send the line and immediately expect to observe it
cat.sendline(txt)
cat.recvuntil(txt)
# check that we hit the breakpoint
assert bp.count == 1, bp.count
# interrupt the program
gdb.interrupt_and_wait()
# delete the breakpoint
bp.delete()
# resume the program
gdb.continue_nowait()
def main():
# start ``cat`` under GDB
with gdb.debug('cat', gdbscript='''
set logging on
set pagination off
''', api=True) as cat:
# the process is stopped
# set the synchronous breakpoint on ``read``
cat.gdb.Breakpoint('read', temporary=True)
# resume and wait until we hit it
cat.gdb.continue_and_wait()
# demonstrate a more interesting synchronous breakpoint
demo_sync_breakpoint(cat, cat.gdb, 'foo')
# terminate GDB
cat.gdb.quit()
# now start ``cat`` normally
with process('cat') as cat:
# attach GDB
_, cat_gdb = gdb.attach(cat, gdbscript='''
set logging on
set pagination off
''', api=True)
# the process is stopped
# demonstrate asynchronous breakpoint
demo_async_breakpoint(cat, cat_gdb, 'bar')
# terminate GDB
cat_gdb.quit()
if __name__ == '__main__':
main()
+9
View File
@@ -36,5 +36,14 @@ print(shell.echo("single string"))
print(shell.echo(["list","of","strings"]))
print(shell["echo single statement"])
# ssh.process() is the most flexible way to run a command)
io = shell.process(['/bin/bash', '-c', 'echo Hello $FOO'],
env={'FOO': 'World'}, # Set environment
stderr='/dev/null', # Override file descriptors
aslr=False, # Disable ASLR on processes
setuid=False, # Disable setuid bit so processes can be debugged
shell=False) # Enable or disable shell evaluation
print(io.recvall())
# Show off the interactive shell
shell.interactive()
+28 -7
View File
@@ -1,13 +1,34 @@
subdirs=xenial stable $(wildcard */)
makefiles=$(wildcard */Makefile)
subdirs=$(shell find . -type d -depth 1 | xargs basename)
tags=base stable beta dev
all: $(makefiles) $(subdirs)
all: $(subdirs) $(tags)
$(subdirs):
tags: $(tags)
base:
@echo "Building $@"
docker build -t pwntools/pwntools:$(shell basename $(@)) "$@"
$(makefiles):
make -C $(shell dirname $@)
stable beta dev: base
@echo "Building $@"
docker build -t pwntools/pwntools:$(shell basename $(@)) "$@"
.PHONY: all $(subdirs) $(makefiles)
develop:
@echo "Building $@"
docker build -t pwntools/pwntools:$(shell basename $(@)) "$@"
docker run -it --privileged --net=host --hostname localhost \
--ulimit core=-1:-1 \
--mount type=bind,source="$(shell git rev-parse --show-toplevel)",target=/home/pwntools/pwntools \
pwntools/pwntools:$(shell basename $(@))
debug:
@echo "Subdirs $(subdirs)"
@echo "Tags $(tags)"
clean:
docker container prune
docker
FORCE:
.PHONY: all $(subdirs) $(makefiles) $(tags)
+53
View File
@@ -0,0 +1,53 @@
# Pwntools Docker Images
This directory contains some Docker images with various versions of Pwntools pre-installed.
## Getting Images
You can either make them yourself, or pull from Docker Hub.
### Docker Hub
To pull an image from Docker hub, just run the command:
```sh
$ docker pull pwntools/pwntools:stable
```
Replace `stable` with `beta` or `dev` as desired.
### Building Locally
To build the images locally, just invoke the `Makefile` with the desired branch target.
```sh
$ make -C extra/docker dev
```
## Running Images
To run the `stable`, `beta`, or `dev` image, we recommend the following command line, in this example it is the `dev` image.
```sh
$ docker run -it \
--privileged \
--net=host \
--ulimit core=-1:-1 \
pwntools/pwntools:dev
```
The `--privileged` option is needed to perform any debugging with GDB.
The `--ulimit` option is needed for any corefiles to drop when a program crashes.
The `--net=host` allows you to easily connect to services hosted inside the container from outside the container.
## Development Dockerfile
In addition to `stable`, `beta`, and `dev` Dockerfiles, there is also a `develop` dockerfile which mounts your Pwntools installation inside the VM so you can develop seamlessly while editing on your host.
```sh
$ make -C extra/docker develop
```
You will be dropped into a shell, and any changes you make to your local Pwntools checkout will be immediately reflected inside the Docker container. This is useful for e.g. editing on a macOS host, but testing your changes on Ubuntu without needing to copy files around.
-1
View File
@@ -1 +0,0 @@
xenial
@@ -3,20 +3,35 @@
# Based on Ubuntu
############################################################
FROM ubuntu:precise
FROM ubuntu:bionic
MAINTAINER Maintainer Gallopsled et al.
env DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y \
build-essential \
git \
libssl-dev \
libffi-dev \
python2.7 \
python \
python-pip \
python-dev \
python3 \
python3-pip \
python3-dev \
qemu-user-static \
binutils-arm-linux-gnueabihf \
binutils-aarch64-linux-gnu \
binutils-mips-linux-gnu \
binutils-mipsel-linux-gnu \
binutils-powerpc-linux-gnu \
binutils-powerpc64-linux-gnu \
binutils-sparc64-linux-gnu \
&& pip install --upgrade pip \
&& python -m pip install --upgrade pwntools \
&& pip3 install --upgrade pip \
&& python3 -m pip install --upgrade pwntools \
&& PWNLIB_NOTERM=1 pwn update \
&& apt-get install -y sudo \
&& useradd -m pwntools \
+1
View File
@@ -2,5 +2,6 @@ FROM pwntools/pwntools:stable
USER root
RUN pip install --upgrade git+https://github.com/Gallopsled/pwntools@beta
RUN pip3 install --upgrade git+https://github.com/Gallopsled/pwntools@beta
RUN PWNLIB_NOTERM=1 pwn update
USER pwntools
+1
View File
@@ -2,5 +2,6 @@ FROM pwntools/pwntools:stable
USER root
RUN pip install --upgrade git+https://github.com/Gallopsled/pwntools@dev
RUN pip3 install --upgrade git+https://github.com/Gallopsled/pwntools@dev
RUN PWNLIB_NOTERM=1 pwn update
USER pwntools
+59
View File
@@ -0,0 +1,59 @@
FROM pwntools/pwntools:base
# Uninstall existing versions of pwntools
USER root
RUN python -m pip uninstall -q -y pwntools \
&& python3 -m pip uninstall -q -y pwntools
# Switch back to the pwntools user from here forward
USER pwntools
WORKDIR /home/pwntools
# Since we are not installing Pwntools systemwide, the "pwn" binaries
# etc will all end up in this path.
ENV PATH="/home/pwntools/.local/bin:${PATH}"
# Install Pwntools to the home directory, make it an editable install
RUN git clone https://github.com/Gallopsled/pwntools \
&& python -m pip install --upgrade --editable pwntools \
&& python3 -m pip install --upgrade --editable pwntools \
&& PWNLIB_NOTERM=1 pwn version
# Requirements for running the tests
RUN python -m pip install --upgrade --requirement pwntools/docs/requirements.txt \
&& python3 -m pip install --upgrade --requirement pwntools/docs/requirements.txt
# Dependencies from .travis.yml addons -> apt -> packages
RUN sudo apt-get install -y \
ash \
bash \
bash-static \
binutils-msp430 \
binutils-multiarch \
binutils-s390x-linux-gnu \
dash \
gcc \
gcc-multilib \
gdb \
ksh \
lib32stdc++6 \
libc6-dev-i386 \
mksh \
pandoc \
qemu-user-static \
socat \
sshpass \
zsh
# Misc useful things when developing
RUN sudo apt-get install -y \
curl \
ipython \
ipython3 \
lsb-release \
ssh \
unzip \
wget
# Do not require password for sudo
RUN echo "pwntools ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/travis
-26
View File
@@ -1,26 +0,0 @@
############################################################
# Dockerfile to build Pwntools container
# Based on Ubuntu
############################################################
FROM kalilinux/kali-linux-docker
MAINTAINER Maintainer Gallopsled et al.
RUN apt-get update \
&& apt-get install -y \
build-essential \
git \
libssl-dev \
libffi-dev \
python2.7 \
python-pip \
python-dev \
&& pip install --upgrade pip \
&& python -m pip install --upgrade pwntools \
&& PWNLIB_NOTERM=1 pwn update \
&& apt-get install -y sudo \
&& useradd -m pwntools \
&& passwd --delete --unlock pwntools \
&& echo "pwntools ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/pwntools
USER pwntools
WORKDIR /home/pwntools
-8
View File
@@ -1,8 +0,0 @@
all: Dockerfile
Dockerfile: ../xenial/Dockerfile FORCE
sed "s|ubuntu:xenial|kalilinux/kali-linux-docker|" < "$<" > "$@"
FORCE:
.PHONY: all
-8
View File
@@ -1,8 +0,0 @@
all: Dockerfile
Dockerfile: ../xenial/Dockerfile FORCE
sed "s|ubuntu:xenial|ubuntu:precise|" < "$<" > "$@"
FORCE:
.PHONY: all
+1
View File
@@ -2,5 +2,6 @@ FROM pwntools/pwntools:base
USER root
RUN pip install --upgrade git+https://github.com/Gallopsled/pwntools@stable
RUN pip3 install --upgrade git+https://github.com/Gallopsled/pwntools@stable
RUN PWNLIB_NOTERM=1 pwn update
USER pwntools
-26
View File
@@ -1,26 +0,0 @@
############################################################
# Dockerfile to build Pwntools container
# Based on Ubuntu
############################################################
FROM ubuntu:trusty
MAINTAINER Maintainer Gallopsled et al.
RUN apt-get update \
&& apt-get install -y \
build-essential \
git \
libssl-dev \
libffi-dev \
python2.7 \
python-pip \
python-dev \
&& pip install --upgrade pip \
&& python -m pip install --upgrade pwntools \
&& PWNLIB_NOTERM=1 pwn update \
&& apt-get install -y sudo \
&& useradd -m pwntools \
&& passwd --delete --unlock pwntools \
&& echo "pwntools ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/pwntools
USER pwntools
WORKDIR /home/pwntools
-8
View File
@@ -1,8 +0,0 @@
all: Dockerfile
Dockerfile: ../xenial/Dockerfile FORCE
sed "s|ubuntu:xenial|ubuntu:trusty|" < "$<" > "$@"
FORCE:
.PHONY: all
-26
View File
@@ -1,26 +0,0 @@
############################################################
# Dockerfile to build Pwntools container
# Based on Ubuntu
############################################################
FROM ubuntu:xenial
MAINTAINER Maintainer Gallopsled et al.
RUN apt-get update \
&& apt-get install -y \
build-essential \
git \
libssl-dev \
libffi-dev \
python2.7 \
python-pip \
python-dev \
&& pip install --upgrade pip \
&& python -m pip install --upgrade pwntools \
&& PWNLIB_NOTERM=1 pwn update \
&& apt-get install -y sudo \
&& useradd -m pwntools \
&& passwd --delete --unlock pwntools \
&& echo "pwntools ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/pwntools
USER pwntools
WORKDIR /home/pwntools
-1
View File
@@ -7,7 +7,6 @@ pwnlib.args.initialize()
pwnlib.log.install_default_handler()
pwnlib.config.initialize()
log = pwnlib.log.getLogger('pwnlib.exploit')
args = pwnlib.args.args
if not platform.architecture()[0].startswith('64'):
+11 -2
View File
@@ -4,7 +4,9 @@ import logging
import math
import operator
import os
import platform
import re
import requests
import socks
import signal
import string
@@ -15,6 +17,7 @@ import tempfile
import threading
import time
import colored_traceback
from pprint import pprint
import pwnlib
@@ -28,8 +31,9 @@ from pwnlib.elf.corefile import Core, Corefile, Coredump
from pwnlib.elf.elf import ELF, load
from pwnlib.encoders import *
from pwnlib.exception import PwnlibException
from pwnlib.gdb import attach, debug, debug_assembly, debug_shellcode
from pwnlib.gdb import attach, debug_assembly, debug_shellcode
from pwnlib.filepointer import *
from pwnlib.filesystem import *
from pwnlib.flag import *
from pwnlib.fmtstr import FmtStr, fmtstr_payload, fmtstr_split
from pwnlib.log import getLogger
@@ -37,6 +41,7 @@ from pwnlib.memleak import MemLeak, RelativeMemLeak
from pwnlib.regsort import *
from pwnlib.replacements import *
from pwnlib.rop import ROP
from pwnlib.rop.call import AppendedArgument
from pwnlib.rop.srop import SigreturnFrame
from pwnlib.rop.ret2dlresolve import Ret2dlresolvePayload
from pwnlib.runner import *
@@ -73,6 +78,7 @@ from pwnlib.util.web import *
from six.moves import cPickle as pickle, cStringIO as StringIO
from six import BytesIO
log = getLogger("pwnlib.exploit")
error = log.error
warning = log.warning
warn = log.warning
@@ -80,4 +86,7 @@ info = log.info
debug = log.debug
success = log.success
__all__ = [x for x in globals().keys() if x != '__name__']
colored_traceback.add_hook()
# Equivalence with the default behavior of "from import *"
# __all__ = [x for x in tuple(globals()) if not x.startswith('_')]
+4 -6
View File
@@ -1,12 +1,11 @@
from __future__ import absolute_import
import importlib
from pwnlib.version import __version__
from .version import __version__
version = __version__
__all__ = [
'adb',
'args',
'asm',
'atexception',
@@ -35,9 +34,8 @@ __all__ = [
'ui',
'useragents',
'util',
'adb',
'update',
'version',
]
for module in __all__:
importlib.import_module('.%s' % module, 'pwnlib')
from . import args
+104 -17
View File
@@ -68,6 +68,7 @@ from pwnlib.context import context
from pwnlib.device import Device
from pwnlib.log import getLogger
from pwnlib.protocols.adb import AdbClient
from pwnlib.util.packing import _decode
from pwnlib.util import misc
log = getLogger(__name__)
@@ -75,10 +76,13 @@ log = getLogger(__name__)
def adb(argv, *a, **kw):
r"""Returns the output of an ADB subcommand.
>>> adb.adb('get-serialno')
b'emulator-5554\n'
>>> adb.adb(['shell', 'uname']) # it is better to use adb.process
b'Linux\n'
.. doctest::
:skipif: skip_android
>>> adb.adb('get-serialno')
b'emulator-5554\n'
>>> adb.adb(['shell', 'uname']) # it is better to use adb.process
b'Linux\n'
"""
if isinstance(argv, (bytes, six.text_type)):
argv = [argv]
@@ -113,11 +117,12 @@ def current_device(any=False):
"""Returns an ``AdbDevice`` instance for the currently-selected device
(via ``context.device``).
Example:
.. doctest::
:skipif: skip_android
>>> device = adb.current_device(any=True)
>>> device
AdbDevice(serial='emulator-5554', type='device', port='emulator', product='sdk_google_phone_armv7', model='sdk google phone armv7', device='generic')
>>> device # doctest: +ELLIPSIS
AdbDevice(serial='emulator-5554', type='device', port='emulator', product='sdk_...phone_armv7', model='sdk ...phone armv7', device='generic')
>>> device.port
'emulator'
"""
@@ -144,7 +149,10 @@ def with_device(f):
def root():
"""Restarts adbd as root.
>>> adb.root()
.. doctest::
:skipif: skip_android
>>> adb.root()
"""
log.info("Enabling root on %s" % context.device)
@@ -202,6 +210,10 @@ def uptime():
Uptime of the device, in seconds
Example:
.. doctest::
:skipif: skip_android
>>> adb.uptime() > 3 # normally AVD takes ~7 seconds to boot
True
"""
@@ -217,6 +229,10 @@ def boot_time():
nearest second.
Example:
.. doctest::
:skipif: skip_android
>>> import time
>>> adb.boot_time() < time.time()
True
@@ -231,6 +247,9 @@ class AdbDevice(Device):
Example:
.. doctest::
:skipif: skip_android
>>> device = adb.wait_for_device()
>>> device.arch
'arm'
@@ -238,8 +257,8 @@ class AdbDevice(Device):
32
>>> device.os
'android'
>>> device.product
'sdk_google_phone_armv7'
>>> device.product # doctest: +ELLIPSIS
'sdk_...phone_armv7'
>>> device.serial
'emulator-5554'
"""
@@ -357,10 +376,13 @@ class AdbDevice(Device):
"""Provides scoped access to ``adb`` module propertise, in the context
of this device.
>>> property = 'ro.build.fingerprint'
>>> device = adb.wait_for_device()
>>> adb.getprop(property) == device.getprop(property)
True
.. doctest::
:skipif: skip_android
>>> property = 'ro.build.fingerprint'
>>> device = adb.wait_for_device()
>>> adb.getprop(property) == device.getprop(property)
True
"""
with context.local(device=self):
g = globals()
@@ -387,6 +409,9 @@ def wait_for_device(kick=False):
Examples:
.. doctest::
:skipif: skip_android
>>> device = adb.wait_for_device()
"""
with log.waitfor("Waiting for device to come online") as w:
@@ -496,6 +521,9 @@ def pull(remote_path, local_path=None):
Example:
.. doctest::
:skipif: skip_android
>>> _=adb.pull('/proc/version', './proc-version')
>>> print(read('./proc-version').decode('utf-8')) # doctest: +ELLIPSIS
Linux version ...
@@ -527,6 +555,9 @@ def push(local_path, remote_path):
Example:
.. doctest::
:skipif: skip_android
>>> write('./filename', 'contents')
>>> adb.push('./filename', '/data/local/tmp')
'/data/local/tmp/filename'
@@ -584,6 +615,9 @@ def read(path, target=None, callback=None):
Examples:
.. doctest::
:skipif: skip_android
>>> print(adb.read('/proc/version').decode('utf-8')) # doctest: +ELLIPSIS
Linux version ...
>>> adb.read('/does/not/exist')
@@ -613,6 +647,9 @@ def write(path, data=b''):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.write('/dev/null', b'data')
>>> adb.write('/data/local/tmp/')
"""
@@ -633,6 +670,9 @@ def mkdir(path):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.mkdir('/')
>>> path = '/data/local/tmp/mkdir_test'
@@ -673,6 +713,9 @@ def makedirs(path):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.makedirs('/data/local/tmp/this/is/a/directory/hierarchy')
>>> adb.listdir('/data/local/tmp/this/is/a/directory')
['hierarchy']
@@ -689,6 +732,9 @@ def exists(path):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.exists('/')
True
>>> adb.exists('/etc/hosts')
@@ -706,6 +752,9 @@ def isdir(path):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.isdir('/')
True
>>> adb.isdir('/init')
@@ -724,6 +773,9 @@ def unlink(path, recursive=False):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.unlink("/does/not/exist")
Traceback (most recent call last):
...
@@ -775,6 +827,9 @@ def process(argv, *a, **kw):
Examples:
.. doctest::
:skipif: skip_android
>>> adb.root()
>>> print(adb.process(['cat','/proc/version']).recvall().decode('utf-8')) # doctest: +ELLIPSIS
Linux version ...
@@ -815,6 +870,9 @@ def which(name, all = False, *a, **kw):
Example:
.. doctest::
:skipif: skip_android
>>> adb.which('sh')
'/system/bin/sh'
>>> adb.which('sh', all=True)
@@ -838,7 +896,7 @@ def which(name, all = False, *a, **kw):
which_cmd = which_cmd.strip()
data = process(['sh','-c', which_cmd], *a, **kw).recvall()
data = context._decode(data)
data = _decode(data)
result = []
for path in data.split('\x00'):
@@ -864,6 +922,10 @@ def whoami():
"""Returns current shell user
Example:
.. doctest::
:skipif: skip_android
>>> adb.whoami()
b'root'
"""
@@ -917,6 +979,10 @@ def proc_exe(pid):
"""Returns the full path of the executable for the provided PID.
Example:
.. doctest::
:skipif: skip_android
>>> adb.proc_exe(1)
b'/init'
"""
@@ -937,18 +1003,22 @@ def getprop(name=None):
Otherwise, a string is returned with the contents of the named property.
Example:
.. doctest::
:skipif: skip_android
>>> adb.getprop() # doctest: +ELLIPSIS
{...}
"""
with context.quiet:
if name:
result = process(['getprop', name]).recvall().strip()
result = context._decode(result)
result = _decode(result)
return result
result = process(['getprop']).recvall()
result = context._decode(result)
result = _decode(result)
expr = r'\[([^\]]+)\]: \[(.*)\]'
props = {}
@@ -1052,6 +1122,10 @@ class Kernel(object):
def address(self):
"""Returns kernel address
Example:
.. doctest::
:skipif: skip_android
>>> hex(adb.kernel.address) # doctest: +ELLIPSIS
'0x...000'
"""
@@ -1178,6 +1252,10 @@ class Property(object):
"""Allow simple comparison
Example:
.. doctest::
:skipif: skip_android
>>> adb.properties.ro.build.version.sdk == "24"
True
"""
@@ -1266,6 +1344,10 @@ def compile(source):
r"""Compile a source file or project with the Android NDK.
Example:
.. doctest::
:skipif: skip_android
>>> temp = tempfile.mktemp('.c')
>>> write(temp, '''
... #include <stdio.h>
@@ -1390,6 +1472,10 @@ class Partitions(object):
"""Enable access to partitions
Example:
.. doctest::
:skipif: skip_android
>>> hex(adb.partitions.vda.size) # doctest: +ELLIPSIS
'0x...000'
"""
@@ -1506,3 +1592,4 @@ def version():
"""Returns rthe platform version as a tuple."""
prop = getprop('ro.build.version.release')
return [int(v) for v in prop.split('.')]
+2 -1
View File
@@ -4,6 +4,7 @@ from __future__ import division
import ctypes
import io
import os
import six
import sys
from pwnlib.log import getLogger
@@ -64,7 +65,7 @@ class BootloaderImage(object):
Returns:
Contents of the image.
"""
if isinstance(index_or_name, int):
if isinstance(index_or_name, six.integer_types):
index = index_or_name
else:
for i in range(len(self.img_info)):
-2
View File
@@ -1,5 +1,3 @@
#!/usr/bin/env python2
"""
Pwntools exposes several magic command-line arguments and environment
variables when operating in `from pwn import *` mode.
+46 -23
View File
@@ -167,6 +167,9 @@ def which_binutils(util):
'i386': ['x86_64', 'amd64'],
'i686': ['x86_64', 'amd64'],
'amd64': ['x86_64', 'i386'],
'mips64': ['mips'],
'powerpc64': ['powerpc'],
'sparc64': ['sparc'],
}.get(arch, [])
# If one of the candidate architectures matches the native
@@ -190,16 +193,18 @@ def which_binutils(util):
for gutil in utils:
# e.g. objdump
if arch is None:
pattern = gutil
patterns = [gutil]
# e.g. aarch64-linux-gnu-objdump
# e.g. aarch64-linux-gnu-objdump, avr-objdump
else:
pattern = '%s*linux*-%s' % (arch,gutil)
patterns = ['%s*linux*-%s' % (arch, gutil),
'%s-%s' % (arch, gutil)]
for dir in environ['PATH'].split(':'):
res = sorted(glob(path.join(dir, pattern)))
if res:
return res[0]
for pattern in patterns:
for dir in environ['PATH'].split(':'):
res = sorted(glob(path.join(dir, pattern)))
if res:
return res[0]
# No dice!
print_binutils_instructions(util, context)
@@ -245,9 +250,9 @@ def _assembler():
stderr=subprocess.STDOUT, universal_newlines=True)
version = re.search(r' (\d\.\d+)', result).group(1)
if version < '2.19':
log.warn_once('Your binutils version is too old and may not work!\n' + \
'Try updating with: https://docs.pwntools.com/en/stable/install/binutils.html\n' + \
'Reported Version: %r' % result.strip())
log.warn_once('Your binutils version is too old and may not work!\n'
'Try updating with: https://docs.pwntools.com/en/stable/install/binutils.html\n'
'Reported Version: %r', result.strip())
return assembler
@@ -294,6 +299,7 @@ def _arch_header():
prefix = ['.section .shellcode,"awx"',
'.global _start',
'.global __start',
'.p2align 2',
'_start:',
'__start:']
headers = {
@@ -322,15 +328,18 @@ def _bfdname():
'amd64' : 'elf64-x86-64',
'arm' : 'elf32-%sarm' % E,
'thumb' : 'elf32-%sarm' % E,
'avr' : 'elf32-avr',
'mips' : 'elf32-trad%smips' % E,
'mips64' : 'elf64-trad%smips' % E,
'alpha' : 'elf64-alpha',
'cris' : 'elf32-cris',
'ia64' : 'elf64-ia64-%s' % E,
'm68k' : 'elf32-m68k',
'msp430' : 'elf32-msp430',
'powerpc' : 'elf32-powerpc',
'powerpc64' : 'elf64-powerpc',
'vax' : 'elf32-vax',
's390' : 'elf%d-s390' % context.bits,
'sparc' : 'elf32-sparc',
'sparc64' : 'elf64-sparc',
}
@@ -344,10 +353,13 @@ def _bfdname():
def _bfdarch():
arch = context.arch
convert = {
'i386': 'i386',
'amd64': 'i386:x86-64',
'thumb': 'arm',
'ia64': 'ia64-elf64'
'amd64': 'i386:x86-64',
'i386': 'i386',
'ia64': 'ia64-elf64',
'mips64': 'mips',
'powerpc64': 'powerpc',
'sparc64': 'sparc',
'thumb': 'arm',
}
if arch in convert:
@@ -356,7 +368,7 @@ def _bfdarch():
return arch
def _run(cmd, stdin = None):
log.debug(subprocess.list2cmdline(cmd))
log.debug('%s', subprocess.list2cmdline(cmd))
try:
proc = subprocess.Popen(
cmd,
@@ -369,17 +381,20 @@ def _run(cmd, stdin = None):
exitcode = proc.wait()
except OSError as e:
if e.errno == errno.ENOENT:
log.exception('Could not run %r the program' % cmd[0])
log.exception('Could not run %r the program', cmd[0])
else:
raise
if (exitcode, stderr) != (0, ''):
msg = 'There was an error running %s:\n' % repr(cmd)
msg = 'There was an error running %r:\n'
args = cmd,
if exitcode != 0:
msg += 'It had the exitcode %d.\n' % exitcode
msg += 'It had the exitcode %d.\n'
args += exitcode,
if stderr != '':
msg += 'It had this on stdout:\n%s\n' % stderr
log.error(msg)
msg += 'It had this on stdout:\n%s\n'
args += stderr,
log.error(msg, *args)
return stdout
@@ -481,9 +496,7 @@ def make_elf_from_assembly(assembly,
>>> file_b = make_elf_from_assembly('nop', extract=True)
>>> file_a[:4] == file_b[:4]
True
>>> len(file_a) < 0x200
True
>>> len(file_b) > 0x1000
>>> len(file_a) < len(file_b)
True
"""
if shared and vma:
@@ -637,6 +650,10 @@ def asm(shellcode, vma = 0, extract = True, shared = False):
b'H\xc7\xc0\x17\x00\x00\x00'
>>> asm("mov r0, #SYS_select", arch = 'arm', os = 'linux', bits=32)
b'R\x00\xa0\xe3'
>>> asm("mov #42, r0", arch = 'msp430')
b'0@*\x00'
>>> asm("la %r0, 42", arch = 's390', bits=64)
b'A\x00\x00*'
"""
result = ''
@@ -749,6 +766,12 @@ def disasm(data, vma = 0, byte = True, offset = True, instructions = True):
>>> print(disasm(unhex('656664676665400F18A4000000000051'), byte=0, arch='amd64'))
0: gs data16 fs data16 rex nop/reserved BYTE PTR gs:[eax+eax*1+0x0]
f: push rcx
>>> print(disasm(unhex('01000000'), arch='sparc64'))
0: 01 00 00 00 nop
>>> print(disasm(unhex('60000000'), arch='powerpc64'))
0: 60 00 00 00 nop
>>> print(disasm(unhex('00000000'), arch='mips64'))
0: 00000000 nop
"""
result = ''
+6 -1
View File
@@ -13,6 +13,7 @@ from __future__ import division
import sys
import threading
import traceback
import atexit as std_atexit
from pwnlib.context import context
@@ -95,4 +96,8 @@ def _run_handlers():
if hasattr(sys, "exitfunc"):
register(sys.exitfunc)
sys.exitfunc = _run_handlers
if sys.version_info[0] < 3:
sys.exitfunc = _run_handlers
else:
std_atexit.register(_run_handlers)
+2 -1
View File
@@ -18,5 +18,6 @@ __all__ = [
'scramble',
'shellcraft',
'unhex',
'update'
'update',
'version'
]
+3 -2
View File
@@ -5,7 +5,7 @@ from __future__ import division
import argparse
import sys
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -13,7 +13,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'asm',
help = 'Assemble shellcode into bytes'
help = 'Assemble shellcode into bytes',
description = 'Assemble shellcode into bytes',
)
parser.add_argument(
+2 -1
View File
@@ -10,7 +10,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'checksec',
help = 'Check binary security settings'
help = 'Check binary security settings',
description = 'Check binary security settings',
)
parser.add_argument(
'elf',
Regular → Executable
+14 -25
View File
@@ -4,10 +4,9 @@ from __future__ import division
import argparse
import functools
import os
import re
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -16,28 +15,26 @@ from pwnlib.commandline import common
p = common.parser_commands.add_parser(
'constgrep',
help = "Looking up constants from header files.\n\nExample: constgrep -c freebsd -m ^PROT_ '3 + 4'",
description = "Looking up constants from header files.\n\nExample: constgrep -c freebsd -m ^PROT_ '3 + 4'",
formatter_class = argparse.RawDescriptionHelpFormatter,
)
group = p.add_mutually_exclusive_group()
group.add_argument(
p.add_argument(
'-e', '--exact',
metavar = 'constant',
# nargs = 1,
default = None,
help = 'Do an exact match for a constant instead of searching for a regex',
action='store_true',
help='Do an exact match for a constant instead of searching for a regex',
)
group.add_argument(
p.add_argument(
'regex',
nargs = '?',
default = '',
help = 'The regex matching constant you want to find',
help='The regex matching constant you want to find',
)
p.add_argument(
'constant',
nargs = '?',
default = None,
type = safeeval.expr,
help = 'The constant to find',
)
@@ -65,7 +62,7 @@ p.add_argument(
def main(args):
if args.exact:
# This is the simple case
print(cpp(args.exact).strip())
print(cpp(args.regex).strip())
else:
# New we search in the right module.
# But first: We find the right module
@@ -80,20 +77,12 @@ def main(args):
else:
matcher = re.compile(args.regex)
# Evaluate the given constant
if args.constant:
try:
constant = safeeval.expr(args.constant)
except:
log.error("Could not evaluate constant %r" % args.constant)
else:
constant = None
# The found matching constants and the length of the longest string
out = []
maxlen = 0
constant = args.constant
for k in dir(mod):
# No python stuff
if k.endswith('__') and k.startswith('__'):
@@ -104,7 +93,7 @@ def main(args):
continue
# Check the constant
if constant != None:
if constant is not None:
val = getattr(mod, k)
if args.mask_mode:
if constant & val != val:
@@ -124,7 +113,7 @@ def main(args):
# If we are in match_mode, then try to find a combination of
# constants that yield the exact given value
# We do not want to find combinations using the value 0.
if not (constant == None or constant == 0) and args.mask_mode:
if constant and args.mask_mode:
mask = constant
good = []
out = [(v, k) for v, k in out if v != 0]
+5 -4
View File
@@ -7,7 +7,7 @@ import six
import string
import sys
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -15,14 +15,15 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'cyclic',
help = "Cyclic pattern creator/finder"
help = "Cyclic pattern creator/finder",
description = "Cyclic pattern creator/finder"
)
parser.add_argument(
'-a', '--alphabet',
metavar = 'alphabet',
default = string.ascii_lowercase.encode(),
type = six.ensure_binary,
type = packing._encode,
help = 'The alphabet to use in the cyclic pattern (defaults to all lower case letters)',
)
@@ -70,7 +71,7 @@ def main(args):
pat = int(pat, 0)
except ValueError:
pass
pat = flat(pat)
pat = flat(pat, bytes=args.length)
if len(pat) != subsize:
log.critical('Subpattern must be %d bytes' % subsize)
+2 -1
View File
@@ -10,7 +10,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'debug',
help = 'Debug a binary in GDB'
help = 'Debug a binary in GDB',
description = 'Debug a binary in GDB'
)
parser.add_argument(
'-x', metavar='GDBSCRIPT',
+2 -1
View File
@@ -8,7 +8,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'disablenx',
help = 'Disable NX for an ELF binary'
help = 'Disable NX for an ELF binary',
description = 'Disable NX for an ELF binary'
)
parser.add_argument(
'elf',
+3 -2
View File
@@ -7,7 +7,7 @@ import argparse
import string
import sys
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -15,7 +15,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'disasm',
help = 'Disassemble bytes into text format'
help = 'Disassemble bytes into text format',
description = 'Disassemble bytes into text format'
)
parser.add_argument(
+3 -2
View File
@@ -8,7 +8,7 @@ from subprocess import CalledProcessError
from subprocess import check_output
from tempfile import NamedTemporaryFile
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -29,7 +29,8 @@ def diff(a,b):
p = common.parser_commands.add_parser(
'elfdiff',
help = 'Compare two ELF files'
help = 'Compare two ELF files',
description = 'Compare two ELF files'
)
p.add_argument('a')
+3 -2
View File
@@ -4,7 +4,7 @@ from __future__ import division
import sys
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -12,7 +12,8 @@ from pwnlib.commandline import common
p = common.parser_commands.add_parser(
'elfpatch',
help = 'Patch an ELF file'
help = 'Patch an ELF file',
description = 'Patch an ELF file'
)
p.add_argument('elf',help="File to patch")
+2 -1
View File
@@ -8,7 +8,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'errno',
help = 'Prints out error messages'
help = 'Prints out error messages',
description = 'Prints out error messages'
)
parser.add_argument(
+3 -3
View File
@@ -10,9 +10,9 @@ from pwnlib.util.fiddling import enhex
parser = common.parser_commands.add_parser(
'hex',
help = '''
Hex-encodes data provided on the command line or stdin
''')
help = 'Hex-encodes data provided on the command line or stdin',
description = 'Hex-encodes data provided on the command line or stdin')
parser.add_argument('data', nargs='*',
help='Data to convert into hex')
+2
View File
@@ -21,6 +21,7 @@ from pwnlib.commandline import shellcraft
from pwnlib.commandline import template
from pwnlib.commandline import unhex
from pwnlib.commandline import update
from pwnlib.commandline import version
from pwnlib.commandline.common import parser
from pwnlib.context import context
@@ -43,6 +44,7 @@ commands = {
'template': template.main,
'unhex': unhex.main,
'update': update.main,
'version': version.main,
}
def main():
+3 -2
View File
@@ -7,7 +7,7 @@ import os
import sys
import io
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -15,7 +15,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'phd',
help = 'Pwnlib HexDump'
help = 'Pretty hex dump',
description = 'Pretty hex dump'
)
parser.add_argument(
+2 -1
View File
@@ -3,7 +3,7 @@ from __future__ import division
import argparse
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -12,6 +12,7 @@ from pwnlib.commandline import common
p = common.parser_commands.add_parser(
'pwnstrip',
help = 'Strip binaries for CTF usage',
description = 'Strip binaries for CTF usage'
)
g = p.add_argument_group("actions")
+3 -2
View File
@@ -4,7 +4,7 @@ from __future__ import division
import argparse
import sys
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -12,7 +12,8 @@ from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'scramble',
help = 'Shellcode encoder'
help = 'Shellcode encoder',
description = 'Shellcode encoder'
)
parser.add_argument(
+6 -5
View File
@@ -8,7 +8,7 @@ import six
import sys
import types
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -35,6 +35,7 @@ def _string(s):
p = common.parser_commands.add_parser(
'shellcraft',
help = 'Microwave shellcode -- Easy, fast and delicious',
description = 'Microwave shellcode -- Easy, fast and delicious',
)
@@ -198,11 +199,11 @@ def main(args):
common.parser.print_usage()
exit()
if args.shellcode not in shellcraft.templates:
try:
func = get_template(args.shellcode)
except AttributeError:
log.error("Unknown shellcraft template %r. Use --list to see available shellcodes." % args.shellcode)
func = get_template(args.shellcode)
if args.show:
# remove doctests
doc = []
@@ -295,7 +296,7 @@ def main(args):
vma = args.address
if vma:
vma = eval(vma)
vma = pwnlib.util.safeeval.expr(vma)
if args.format in ['e','elf']:
args.format = 'default'
Regular → Executable
+21 -11
View File
@@ -2,8 +2,6 @@
from __future__ import absolute_import
from __future__ import division
import re
from pwn import *
from pwnlib.commandline import common
@@ -11,26 +9,23 @@ from mako.lookup import TemplateLookup
parser = common.parser_commands.add_parser(
'template',
help = 'Generate an exploit template'
help = 'Generate an exploit template',
description = 'Generate an exploit template'
)
parser.add_argument('exe', nargs='?', help='Target binary')
parser.add_argument('--host', help='Remote host / SSH server')
parser.add_argument('--port', help='Remote port / SSH port', type=int)
parser.add_argument('--user', help='SSH Username')
parser.add_argument('--pass', help='SSH Password', dest='password')
parser.add_argument('--pass', '--password', help='SSH Password', dest='password')
parser.add_argument('--path', help='Remote path of file on SSH server')
parser.add_argument('--quiet', help='Less verbose template comments', action='store_true')
parser.add_argument('--color', help='Print the output in color', choices=['never', 'always', 'auto'], default='auto')
def main(args):
cache = None
if cache:
cache = os.path.join(context.cache_dir, 'mako')
lookup = TemplateLookup(
directories = [os.path.join(pwnlib.data.path, 'templates')],
module_directory = cache
module_directory = None
)
# For the SSH scenario, check that the binary is at the
@@ -40,7 +35,14 @@ def main(args):
log.error("Must specify --path or a exe")
s = ssh(args.user, args.host, args.port or 22, args.password or None)
s.download(args.path or args.exe)
try:
remote_file = args.path or args.exe
s.download(remote_file)
except Exception:
log.warning("Could not download file %r, opening a shell", remote_file)
s.interactive()
return
if not args.exe:
args.exe = os.path.basename(args.path)
@@ -57,8 +59,16 @@ def main(args):
# Fix Mako formatting bs
output = re.sub('\n\n\n', '\n\n', output)
# Colorize the output if it's a TTY
if args.color == 'always' or (args.color == 'auto' and sys.stdout.isatty()):
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers.python import PythonLexer
output = highlight(output, PythonLexer(), TerminalFormatter())
print(output)
# If redirected to a file, make the resulting script executable
if not sys.stdout.isatty():
try: os.fchmod(sys.stdout.fileno(), 0o700)
except OSError: pass
+3 -3
View File
@@ -11,9 +11,9 @@ from pwnlib.util.fiddling import unhex
parser = common.parser_commands.add_parser(
'unhex',
help = '''
Decodes hex-encoded data provided on the command line or via stdin.
''')
help = 'Decodes hex-encoded data provided on the command line or via stdin.',
description = 'Decodes hex-encoded data provided on the command line or via stdin.'
)
parser.add_argument('hex', nargs='*',
help='Hex bytes to decode')
+3 -2
View File
@@ -4,7 +4,7 @@ from __future__ import division
import subprocess
import pwnlib
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
@@ -12,7 +12,8 @@ from pwnlib.commandline import common
p = common.parser_commands.add_parser(
'update',
help = 'Check for pwntools updates'
help = 'Check for pwntools updates',
description = 'Check for pwntools updates'
)
p.add_argument('--install', action='store_true', help='''
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
import os
import subprocess
import pwnlib.args
pwnlib.args.free_form = False
from pwn import *
from pwnlib.commandline import common
parser = common.parser_commands.add_parser(
'version',
help = 'Pwntools version',
description = 'Pwntools version'
)
def main(a):
version = pwnlib.version
git_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if os.path.exists(os.path.join(git_root, '.git')):
gitver = subprocess.check_output(['git', '-C', git_root, 'log', '-1', '--format=%h (%cr)'])
branch = subprocess.check_output(['git', '-C', git_root, 'rev-parse', '--abbrev-ref', 'HEAD'])
version = '%s-%s-%s' % (version, branch.decode().strip(), gitver.decode())
log.info("Pwntools v%s" % version)
if __name__ == '__main__':
pwnlib.commandline.common.main(__file__)
+9 -2
View File
@@ -5,7 +5,9 @@ The list of configurable options includes all of the logging symbols
and colors, as well as all of the default values on the global context
object.
The configuration file is read from ``~/.pwn.conf`` and ``/etc/pwn.conf``.
The configuration file is read from ``~/.pwn.conf``, ``$XDG_CONFIG_HOME/pwn.conf``
(``$XDG_CONFIG_HOME`` defaults to ``~/.config``, per XDG Base Directory Specification),
and ``/etc/pwn.conf``.
The configuration file is only read in ``from pwn import *`` mode, and not
when used in library mode (``import pwnlib``). To read the configuration
@@ -53,8 +55,13 @@ def initialize():
from pwnlib.log import getLogger
log = getLogger(__name__)
xdg_config_home = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser("~/.config"))
c = configparser.ConfigParser()
c.read(['/etc/pwn.conf', os.path.expanduser('~/.pwn.conf')])
c.read(['/etc/pwn.conf',
os.path.join(xdg_config_home, 'pwn.conf'),
os.path.expanduser('~/.pwn.conf')])
for section in c.sections():
if section not in registered_configs:
+8 -2
View File
@@ -92,7 +92,7 @@ class ConstantsModule(ModuleType):
# Special case for __all__, we want to return the contextually
# relevant module.
if key == '__all__':
return self.guess().__dict__.keys()
return list(self.guess().__dict__.keys())
# Special case for all other special properties which aren't defined
if key.endswith('__'):
@@ -145,7 +145,13 @@ class ConstantsModule(ModuleType):
if key not in self._env_store:
self._env_store[key] = {key: getattr(self, key) for key in dir(self) if not key.endswith('__')}
return Constant('(%s)' % string, safeeval.values(string, self._env_store[key]))
val = safeeval.values(string, self._env_store[key])
# if the expression is not assembly-safe, it is not so vital to preserve it
if set(string) & (set(bytearray(range(32)).decode()) | set('"#$\',.;@[\\]`{}')):
string = val
return Constant('(%s)' % string, val)
# To prevent garbage collection
+110 -35
View File
@@ -1,4 +1,3 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Implements context management so that nested/scoped contexts and threaded
@@ -359,17 +358,18 @@ class ContextType(object):
'log_console': sys.stdout,
'randomize': False,
'rename_corefiles': True,
'newline': '\n',
'newline': b'\n',
'noptrace': False,
'os': 'linux',
'proxy': None,
'ssh_session': None,
'signed': False,
'terminal': tuple(),
'timeout': Timeout.maximum,
}
#: Valid values for :meth:`pwnlib.context.ContextType.os`
oses = sorted(('linux','freebsd','windows','cgc','android'))
oses = sorted(('linux','freebsd','windows','cgc','android','baremetal'))
big_32 = {'endian': 'big', 'bits': 32}
big_64 = {'endian': 'big', 'bits': 64}
@@ -549,14 +549,66 @@ class ContextType(object):
@property
def quiet(self, function=None):
"""Disables all non-error logging within the enclosed scope,
*unless* the debugging level is set to 'debug' or lower."""
*unless* the debugging level is set to 'debug' or lower.
Example:
Let's assume the normal situation, where log_level is INFO.
>>> context.clear(log_level='info')
Note that only the log levels below ERROR do not print anything.
>>> with context.quiet:
... log.debug("DEBUG")
... log.info("INFO")
... log.warn("WARN")
Next let's try with the debugging level set to 'debug' before we
enter the context handler:
>>> with context.local(log_level='debug'):
... with context.quiet:
... log.debug("DEBUG")
... log.info("INFO")
... log.warn("WARN")
[DEBUG] DEBUG
[*] INFO
[!] WARN
"""
level = 'error'
if context.log_level <= logging.DEBUG:
level = None
return self.local(function, log_level=level)
def quietfunc(self, function):
"""Similar to :attr:`quiet`, but wraps a whole function."""
"""Similar to :attr:`quiet`, but wraps a whole function.
Example:
Let's set up two functions, which are the same but one is
wrapped with :attr:`quietfunc`.
>>> def loud(): log.info("Loud")
>>> @context.quietfunc
... def quiet(): log.info("Quiet")
If we set the logging level to 'info', the loud function
prints its contents.
>>> with context.local(log_level='info'): loud()
[*] Loud
However, the quiet function does not, since :attr:`quietfunc`
silences all output unless the log level is DEBUG.
>>> with context.local(log_level='info'): quiet()
Now let's try again with debugging enabled.
>>> with context.local(log_level='debug'): quiet()
[*] Quiet
"""
@functools.wraps(function)
def wrapper(*a, **kw):
level = 'error'
@@ -570,6 +622,28 @@ class ContextType(object):
@property
def verbose(self):
"""Enable all logging within the enclosed scope.
This is the opposite of :attr:`.quiet` and functionally equivalent to:
.. code-block:: python
with context.local(log_level='debug'):
...
Example:
Note that the function does not emit any information by default
>>> context.clear()
>>> def func(): log.debug("Hello")
>>> func()
But if we put it inside a :attr:`.verbose` context manager, the
information is printed.
>>> with context.verbose: func()
[DEBUG] Hello
"""
return self.local(log_level='debug')
@@ -603,7 +677,7 @@ class ContextType(object):
@property
def native(self):
if context.os in ('android', 'cgc'):
if context.os in ('android', 'baremetal', 'cgc'):
return False
arch = context.arch
@@ -827,27 +901,6 @@ class ContextType(object):
return charset
def _encode(self, s):
if isinstance(s, (bytes, bytearray)):
return s # already bytes
if self.encoding == 'auto':
try:
return s.encode('latin1')
except UnicodeEncodeError:
return s.encode('utf-8', 'surrogateescape')
return s.encode(self.encoding)
def _decode(self, b):
if self.encoding == 'auto':
try:
return b.decode('utf-8')
except UnicodeDecodeError:
return b.decode('latin1')
except AttributeError:
return b
return b.decode(self.encoding)
@_validator
def endian(self, endianness):
"""
@@ -932,20 +985,22 @@ class ContextType(object):
Examples:
>>> context.log_file = 'foo.txt' #doctest: +ELLIPSIS
>>> log.debug('Hello!') #doctest: +ELLIPSIS
>>> foo_txt = tempfile.mktemp()
>>> bar_txt = tempfile.mktemp()
>>> context.log_file = foo_txt
>>> log.debug('Hello!')
>>> with context.local(log_level='ERROR'): #doctest: +ELLIPSIS
... log.info('Hello again!')
>>> with context.local(log_file='bar.txt'):
>>> with context.local(log_file=bar_txt):
... log.debug('Hello from bar!')
>>> log.info('Hello from foo!')
>>> open('foo.txt').readlines()[-3] #doctest: +ELLIPSIS
>>> open(foo_txt).readlines()[-3] #doctest: +ELLIPSIS
'...:DEBUG:...:Hello!\n'
>>> open('foo.txt').readlines()[-2] #doctest: +ELLIPSIS
>>> open(foo_txt).readlines()[-2] #doctest: +ELLIPSIS
'...:INFO:...:Hello again!\n'
>>> open('foo.txt').readlines()[-1] #doctest: +ELLIPSIS
>>> open(foo_txt).readlines()[-1] #doctest: +ELLIPSIS
'...:INFO:...:Hello from foo!\n'
>>> open('bar.txt').readlines()[-1] #doctest: +ELLIPSIS
>>> open(bar_txt).readlines()[-1] #doctest: +ELLIPSIS
'...:DEBUG:...:Hello from bar!\n'
"""
if isinstance(value, (bytes, six.text_type)):
@@ -1019,7 +1074,7 @@ class ContextType(object):
>>> context.os = 'foobar' #doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: os must be one of ['android', 'cgc', 'freebsd', 'linux', 'windows']
AttributeError: os must be one of ['android', 'baremetal', 'cgc', 'freebsd', 'linux', 'windows']
"""
os = os.lower()
@@ -1279,6 +1334,17 @@ class ContextType(object):
"""
return bool(v)
@_validator
def newline(self, v):
"""Line ending used for Tubes by default.
This configures the newline emitted by e.g. ``sendline`` or that is used
as a delimiter for e.g. ``recvline``.
"""
# circular imports
from pwnlib.util.packing import _need_bytes
return _need_bytes(v)
@_validator
def gdbinit(self, value):
@@ -1322,6 +1388,15 @@ class ContextType(object):
return size
@_validator
def ssh_session(self, shell):
from pwnlib.tubes.ssh import ssh
if not isinstance(shell, ssh):
raise AttributeError("context.ssh_session must be an ssh tube")
return shell
#*************************************************************************
# ALIASES
#*************************************************************************
+1
View File
@@ -1,6 +1,7 @@
from __future__ import absolute_import
from pwnlib.data.elf import fmtstr
from pwnlib.data.elf import relro
from pwnlib.data.elf import ret2dlresolve
import os
path = os.path.dirname(__file__)
+8
View File
@@ -0,0 +1,8 @@
all: i386 amd64
i386: vuln.c
gcc "$^" -fno-stack-protector -no-pie -m32 -o $@
amd64: vuln.c
gcc "$^" -fno-stack-protector -no-pie -o $@
@@ -0,0 +1,5 @@
import os
path = os.path.dirname(__file__)
def get(x):
return os.path.join(path, x)
Binary file not shown.
BIN
View File
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
#include <unistd.h>
void vuln(void){
char buf[64];
read(STDIN_FILENO, buf, 200);
}
int main(int argc, char** argv){
vuln();
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+11 -9
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python2
from __future__ import division
import argparse
import keyword
import os
from pwnlib import constants
@@ -62,7 +63,7 @@ CALL = """
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
@@ -75,8 +76,8 @@ CALL = """
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (bytes, six.text_type)):
if not isinstance(arg, bytes):
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
@@ -144,12 +145,11 @@ def can_be_array(arg):
def fix_bad_arg_names(func, arg):
if arg.name == 'str':
return 'str_'
if arg.name == 'len':
return 'length'
if arg.name == 'repr':
return 'repr_'
if arg.name in ('str', 'repr') or keyword.iskeyword(arg.name):
return arg.name + '_'
if func.name == 'open' and arg.name == 'vararg':
return 'mode'
@@ -277,8 +277,10 @@ def generate_one(target):
CALL.format(**template_variables)
]
with open(os.path.join(target, name + '.asm'), 'wt+') as f:
f.write('\n'.join(map(str.strip, lines)))
if keyword.iskeyword(name):
name += '_'
with open(os.path.join(target, name + '.asm'), 'wt') as f:
f.write('\n'.join(map(str.strip, lines)) + '\n')
if __name__ == '__main__':
p = argparse.ArgumentParser()
+5 -5
View File
@@ -32,7 +32,7 @@ remote_path = remote_path or exe
password = password or 'secret1234'
binary_repr = repr(binary)
%>\
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
%if not quiet:
# This exploit template was generated via:
@@ -84,14 +84,14 @@ if not args.LOCAL:
%endif
%if host:
def local(argv=[], *a, **kw):
def start_local(argv=[], *a, **kw):
'''Execute the target binary locally'''
if args.GDB:
return gdb.debug([${binary_repr}] + argv, gdbscript=gdbscript, *a, **kw)
else:
return process([${binary_repr}] + argv, *a, **kw)
def remote(argv=[], *a, **kw):
def start_remote(argv=[], *a, **kw):
%if ssh:
'''Execute the target binary on the remote host'''
if args.GDB:
@@ -111,9 +111,9 @@ def remote(argv=[], *a, **kw):
def start(argv=[], *a, **kw):
'''Start the exploit against the target.'''
if args.LOCAL:
return local(argv, *a, **kw)
return start_local(argv, *a, **kw)
else:
return remote(argv, *a, **kw)
return start_remote(argv, *a, **kw)
%else:
def start(argv=[], *a, **kw):
'''Start the exploit against the target.'''
+11 -8
View File
@@ -62,7 +62,7 @@ from pwnlib.elf import constants
from pwnlib.log import getLogger
from pwnlib.memleak import MemLeak
from pwnlib.util.fiddling import enhex
from pwnlib.util.packing import unpack
from pwnlib.util.packing import unpack, _encode
from pwnlib.util.web import wget
log = getLogger(__name__)
@@ -75,7 +75,7 @@ def sysv_hash(symbol):
"""
h = 0
g = 0
for c in bytearray(context._encode(symbol)):
for c in bytearray(_encode(symbol)):
h = (h << 4) + c
g = h & 0xf0000000
h ^= (g >> 24)
@@ -87,7 +87,7 @@ def gnu_hash(s):
Function used to generated GNU-style hashes for strings.
"""
s = bytearray(context._encode(s))
s = bytearray(_encode(s))
h = 5381
for c in s:
h = h * 33 + c
@@ -538,6 +538,9 @@ class DynELF(object):
if lib == 'libc':
lib = 'libc.so'
if symb:
symb = _encode(symb)
#
# Get a pretty name for the symbol to show the user
#
@@ -637,12 +640,14 @@ class DynELF(object):
while leak.field(cur, LinkMap.l_prev):
cur = leak.field(cur, LinkMap.l_prev)
libname = _encode(libname)
while cur:
self.status("link_map entry %#x" % cur)
p_name = leak.field(cur, LinkMap.l_name)
name = leak.s(p_name)
if libname.encode('utf-8') in name:
if libname in name:
break
if name:
@@ -741,7 +746,6 @@ class DynELF(object):
# Leak the name of the function from the symbol table
name = leak.s(strtab + leak.field(sym, Sym.st_name))
name = name.decode('utf-8')
# Make sure it matches the name of the symbol we were looking for.
if name == symb:
@@ -749,7 +753,7 @@ class DynELF(object):
addr = libbase + leak.field(sym, Sym.st_value)
return addr
self.status("%s (hash collision)" % name)
self.status("%r (hash collision)" % name)
# The name did not match what we were looking for, or we assume
# it did not since it was not a function.
@@ -825,7 +829,6 @@ class DynELF(object):
# Check for collision on hash values
sym = symtab + sizeof(Sym) * (ndx + i)
name = leak.s(strtab + leak.field(sym, Sym.st_name))
name = name.decode('utf-8')
if name == symb:
# No collision, get offset and calculate address
@@ -833,7 +836,7 @@ class DynELF(object):
addr = offset + libbase
return addr
self.status("%s (hash collision)" % name)
self.status("%r (hash collision)" % name)
# Collision or no match, continue to the next item
i += 1
+135 -70
View File
@@ -196,8 +196,8 @@ class Mapping(object):
self.start,
self.stop,
self.size,
self.page_offset,
self.flags)
self.flags,
self.page_offset)
def __int__(self):
return self.start
@@ -219,8 +219,8 @@ class Mapping(object):
stop += self.stop
if not (self.start <= start <= stop <= self.stop):
log.error("Byte range [%#x:%#x] not within range [%#x:%#x]" \
% (start, stop, self.start, self.stop))
log.error("Byte range [%#x:%#x] not within range [%#x:%#x]",
start, stop, self.start, self.stop)
data = self._core.read(start, stop-start)
@@ -264,13 +264,16 @@ class Mapping(object):
return result + self.address
class Corefile(ELF):
r"""Enhances the inforation available about a corefile (which is an extension
r"""Enhances the information available about a corefile (which is an extension
of the ELF format) by permitting extraction of information about the mapped
data segments, and register state.
Registers can be accessed directly, e.g. via ``core_obj.eax`` and enumerated
via :data:`Corefile.registers`.
Memory can be accessed directly via :meth:`.read` or :meth:`.write`, and also
via :meth:`.pack` or :meth:`.unpack` or even :meth:`.string`.
Arguments:
core: Path to the core file. Alternately, may be a :class:`.process` instance,
and the core file will be located automatically.
@@ -320,11 +323,7 @@ class Corefile(ELF):
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf7713000, stop=0xf7714000, size=0x1000, flags=0x6, page_offset=0x21),
Mapping('[stack]', start=0xfff3e000, stop=0xfff61000, size=0x23000, flags=0x6, page_offset=0x0)]
Example:
The Linux kernel may not overwrite an existing core-file.
>>> if os.path.exists('core'): os.unlink('core')
Examples:
Let's build an example binary which should eat ``R0=0xdeadbeef``
and ``PC=0xcafebabe``.
@@ -345,18 +344,24 @@ class Corefile(ELF):
You can specify a full path a la ``Corefile('/path/to/core')``,
but you can also just access the :attr:`.process.corefile` attribute.
There's a lot of behind-the-scenes logic to locate the corefile for
a given process, but it's all handled transparently by Pwntools.
>>> core = io.corefile
The core file has a :attr:`.Corefile.exe` property, which is a :class:`.Mapping`
The core file has a :attr:`exe` property, which is a :class:`.Mapping`
object. Each mapping can be accessed with virtual addresses via subscript, or
contents can be examined via the :attr:`.Mapping.data` attribute.
>>> core.exe.address == address
True
>>> core.exe # doctest: +ELLIPSIS
Mapping('/.../step3', start=..., stop=..., size=0x1000, flags=0x..., page_offset=...)
>>> hex(core.exe.address)
'0x41410000'
The core file also has registers which can be accessed direclty.
Pseudo-registers ``pc`` and ``sp`` are available on all architectures,
Pseudo-registers :attr:`pc` and :attr:`sp` are available on all architectures,
to make writing architecture-agnostic code more simple.
If this were an amd64 corefile, we could access e.g. ``core.rax``.
>>> core.pc == 0xcafebabe
True
@@ -367,7 +372,8 @@ class Corefile(ELF):
We may not always know which signal caused the core dump, or what address
caused a segmentation fault. Instead of accessing registers directly, we
can also extract this information from the core dump.
can also extract this information from the core dump via :attr:`fault_addr`
and :attr:`signal`.
On QEMU-generated core dumps, this information is unavailable, so we
substitute the value of PC. In our example, that's correct anyway.
@@ -378,60 +384,103 @@ class Corefile(ELF):
11
Core files can also be generated from running processes.
This requires GDB to be installed, and can only be done with native
processes. Getting a "complete" corefile requires GDB 7.11 or better.
This requires GDB to be installed, and can only be done with native processes.
Getting a "complete" corefile requires GDB 7.11 or better.
>>> elf = ELF('/bin/bash-static')
>>> elf = ELF(which('bash-static'))
>>> context.clear(binary=elf)
>>> io = process(elf.path, env={'HELLO': 'WORLD'})
>>> env = dict(os.environ)
>>> env['HELLO'] = 'WORLD'
>>> io = process(elf.path, env=env)
>>> io.sendline(b'echo hello')
>>> io.recvline()
b'hello\n'
The process is still running, but accessing its :attr:`.process.corefile` property
automatically invokes GDB to attach and dump a corefile.
>>> core = io.corefile
Data can also be extracted directly from the corefile.
The corefile can be inspected and read from, and even exposes various mappings
>>> elf.address > 0
True
>>> core.exe[elf.address:elf.address+4]
b'\x7fELF'
>>> core.exe.data[:4]
>>> core.exe # doctest: +ELLIPSIS
Mapping('.../bin/bash-static', start=..., stop=..., size=..., flags=..., page_offset=...)
>>> core.exe.data[0:4]
b'\x7fELF'
Various other mappings are available by name. On Linux, 32-bit Intel binaries
should have a VDSO section. Since our ELF is statically linked, there is
no libc which gets mapped.
It also supports all of the features of :class:`ELF`, so you can :meth:`.read`
or :meth:`.write` or even the helpers like :meth:`.pack` or :meth:`.unpack`.
Don't forget to call :meth:`.ELF.save` to save the changes to disk.
>>> core.read(elf.address, 4)
b'\x7fELF'
>>> core.pack(core.sp, 0xdeadbeef)
>>> core.save()
Let's re-load it as a new :attr:`Corefile` object and have a look!
>>> core2 = Corefile(core.path)
>>> hex(core2.unpack(core2.sp))
'0xdeadbeef'
Various other mappings are available by name, for the first segment of:
* :attr:`.exe` the executable
* :attr:`.libc` the loaded libc, if any
* :attr:`.stack` the stack mapping
* :attr:`.vvar`
* :attr:`.vdso`
* :attr:`.vsyscall`
On Linux, 32-bit Intel binaries should have a VDSO section via :attr:`vdso`.
Since our ELF is statically linked, there is no libc which gets mapped.
>>> core.vdso.data[:4]
b'\x7fELF'
>>> core.libc # doctest: +ELLIPSIS
Mapping('/lib/x86_64-linux-gnu/libc-...', ...)
>>> core.libc
The corefile also contains a :attr:`.Corefile.stack` property, which gives
But if we dump a corefile from a dynamically-linked binary, the :attr:`.libc`
will be loaded.
>>> process('bash').corefile.libc # doctest: +ELLIPSIS
Mapping('/.../libc-....so', start=0x..., stop=0x..., size=0x..., flags=..., page_offset=...)
The corefile also contains a :attr:`.stack` property, which gives
us direct access to the stack contents. On Linux, the very top of the stack
should contain two pointer-widths of NULL bytes, preceded by the NULL-
terminated path to the executable (as passed via the first arg to ``execve``).
>>> stack_end = core.exe.name.encode()
>>> stack_end += b'\x00' * (1+8)
>>> core.stack.data.endswith(stack_end)
True
>>> len(core.stack.data) == core.stack.size
True
>>> core.stack # doctest: +ELLIPSIS
Mapping('[stack]', start=0x..., stop=0x..., size=0x..., flags=0x6, page_offset=0x0)
We can also directly access the environment variables and arguments.
When creating a process, the kernel puts the absolute path of the binary and some
padding bytes at the end of the stack. We can look at those by looking at
``core.stack.data``.
>>> size = len('/bin/bash-static') + 8
>>> core.stack.data[-size:]
b'bin/bash-static\x00\x00\x00\x00\x00\x00\x00\x00\x00'
We can also directly access the environment variables and arguments, via
:attr:`.argc`, :attr:`.argv`, and :attr:`.env`.
>>> 'HELLO' in core.env
True
>>> core.string(core.env['HELLO'])
b'WORLD'
>>> core.getenv('HELLO')
b'WORLD'
>>> core.argc
1
>>> core.argv[0] in core.stack
True
>>> core.string(core.argv[0]) == core.exe.path.encode()
True
>>> core.string(core.argv[0]) # doctest: +ELLIPSIS
b'.../bin/bash-static'
Corefiles can also be pulled from remote machines via SSH!
>>> s = ssh(host='example.pwnme')
>>> s = ssh(user='travis', host='example.pwnme', password='demopass')
>>> _ = s.set_working_directory()
>>> elf = ELF.from_assembly(shellcraft.trap())
>>> path = s.upload(elf.path)
@@ -451,10 +500,6 @@ class Corefile(ELF):
>>> io.corefile.fault_addr
1234
Tests:
These are extra tests not meant to serve as examples.
Corefile.getenv() works correctly, even if the environment variable's
value contains embedded '='. Corefile is able to find the stack, even
if the stack pointer doesn't point at the stack.
@@ -505,20 +550,21 @@ class Corefile(ELF):
#: The NT_SIGINFO object
self.siginfo = None
#: :class:`dict`: Dictionary of memory mappings from ``address`` to ``name``
#: :class:`list`: A list of :class:`.Mapping` objects for each loaded memory region
self.mappings = []
#: :class:`int`: Address of the stack base
#: :class:`int`: A :class:`Mapping` corresponding to the stack
self.stack = None
#: :class:`dict`: Environment variables read from the stack. Keys are
#: the environment variable name, values are the memory address of the
#: variable.
#:
#: Note: Use with the :meth:`.ELF.string` method to extract them.
#:
#: Note: If FOO=BAR is in the environment, self.env['FOO'] is the
#: address of the string "BAR\x00".
"""
Environment variables read from the stack.
Keys are the environment variable name, values are the memory
address of the variable.
Use :meth:`.getenv` or :meth:`.string` to retrieve the textual value.
Note: If ``FOO=BAR`` is in the environment, ``self.env['FOO']`` is the address of the string ``"BAR\x00"``.
"""
self.env = {}
#: :class:`int`: Pointer to envp on the stack
@@ -551,15 +597,15 @@ class Corefile(ELF):
self.load_addr = 0
self._address = 0
if not self.elftype == 'CORE':
if self.elftype != 'CORE':
log.error("%s is not a valid corefile" % self.file.name)
if not self.arch in prstatus_types.keys():
if self.arch not in prstatus_types:
log.warn_once("%s does not use a supported corefile architecture, registers are unavailable" % self.file.name)
prstatus_type = prstatus_types.get(self.arch, None)
prpsinfo_type = prpsinfo_types.get(self.bits, None)
siginfo_type = siginfo_types.get(self.bits, None)
prstatus_type = prstatus_types.get(self.arch)
prpsinfo_type = prpsinfo_types.get(self.bits)
siginfo_type = siginfo_types.get(self.bits)
with log.waitfor("Parsing corefile...") as w:
self._load_mappings()
@@ -627,6 +673,13 @@ class Corefile(ELF):
# off the end of the stack.
pass
# Corefiles generated by QEMU do not have a name for the
# main module mapping.
# Fetching self.exe will cause this to be auto-populated,
# and is a no-op in other cases.
self.exe
# Print out the nice display for the user
self._describe_core()
def _parse_nt_file(self, note):
@@ -669,8 +722,8 @@ class Corefile(ELF):
continue
if mapping.start == self.at_sysinfo_ehdr \
or (not vdso and mapping.size in [0x1000, 0x2000] \
and mapping.flags == 5 \
or (not vdso and mapping.size in [0x1000, 0x2000]
and mapping.flags == 5
and self.read(mapping.start, 4) == b'\x7fELF'):
mapping.name = '[vdso]'
vdso = True
@@ -719,15 +772,30 @@ class Corefile(ELF):
@property
def exe(self):
""":class:`Mapping`: First mapping for the executable file."""
# Finding the executable mapping requires knowing the entry point
# from the auxv
if not self.at_entry:
return None
# The entry point may not be in the first segment of a given file,
# but we want to find the first segment of the file -- not the segment that
# contains the entrypoint.
first_segment_for_name = {}
for m in self.mappings:
if self.at_entry and m.start <= self.at_entry <= m.stop:
first_segment_for_name.setdefault(m.name, m)
# Find which segment conains the entry point
for m in self.mappings:
if m.start <= self.at_entry < m.stop:
if not m.name and self.at_execfn:
m.name = self.string(self.at_execfn)
if not isinstance(m.name, str):
m.name = m.name.decode('utf-8')
return m
return first_segment_for_name.get(m.name, m)
@property
def pid(self):
@@ -839,7 +907,7 @@ class Corefile(ELF):
@property
def sp(self):
""":class:`int`: The program counter for the Corefile
""":class:`int`: The stack pointer for the Corefile
This is a cross-platform way to get e.g. ``core.esp``, ``core.rsp``, etc.
"""
@@ -1109,11 +1177,8 @@ class Corefile(ELF):
return rv
def debug(self, *a, **kw):
def debug(self):
"""Open the corefile under a debugger."""
if a or kw:
log.error("Arguments are not supported for %s.debug()" % self.__class__.__name__)
import pwnlib.gdb
pwnlib.gdb.attach(self, exe=self.exe.path)
@@ -1504,7 +1569,7 @@ class CorefileFinder(object):
path = os.path.join(binfmt_misc, entry)
try:
data = self.read(path)
data = self.read(path).decode()
except Exception:
continue
+49 -17
View File
@@ -90,6 +90,12 @@ log = getLogger(__name__)
__all__ = ['load', 'ELF']
def _iter_symbols(sec):
# Cache result of iter_symbols.
if not hasattr(sec, '_symbols'):
sec._symbols = list(sec.iter_symbols())
return iter(sec._symbols)
class Function(object):
"""Encapsulates information about a function in an :class:`.ELF` binary.
@@ -269,6 +275,9 @@ class ELF(ELFFile):
self.arch = 'mips64'
self.bits = 64
self._sections = None
self._segments = None
#: IntervalTree which maps all of the loaded memory segments
self.memory = intervaltree.IntervalTree()
self._populate_memory()
@@ -455,9 +464,6 @@ class ELF(ELFFile):
self.checksec(*a, **kw)
)
def __repr__(self):
return "ELF(%r)" % self.path
def get_machine_arch(self):
return {
'EM_X86_64': 'amd64',
@@ -485,6 +491,13 @@ class ELF(ELFFile):
""":class:`str`: ELF type (``EXEC``, ``DYN``, etc)"""
return describe_e_type(self.header.e_type).split()[0]
def iter_segments(self):
# Yield and cache all the segments in the file
if self._segments is None:
self._segments = [self.get_segment(i) for i in range(self.num_segments())]
return iter(self._segments)
@property
def segments(self):
"""
@@ -537,6 +550,13 @@ class ELF(ELFFile):
return None
def iter_sections(self):
# Yield and cache all the sections in the file
if self._sections is None:
self._sections = [self.get_section(i) for i in range(self.num_sections())]
return iter(self._sections)
@property
def sections(self):
"""
@@ -725,7 +745,7 @@ class ELF(ELFFile):
self._libs[qemu_lib] = address
def _patch_elf_and_read_maps(self):
"""patch_elf_and_read_maps(self) -> dict
r"""patch_elf_and_read_maps(self) -> dict
Read ``/proc/self/maps`` as if the ELF were executing.
@@ -745,12 +765,13 @@ class ELF(ELFFile):
These tests are just to ensure that our shellcode is correct.
>>> for arch in CAT_PROC_MAPS_EXIT:
... context.clear()
... with context.local(arch=arch):
... sc = shellcraft.cat("/proc/self/maps")
... sc += shellcraft.exit()
... sc = asm(sc)
... sc = enhex(sc)
... assert sc == CAT_PROC_MAPS_EXIT[arch]
... assert sc == CAT_PROC_MAPS_EXIT[arch], (arch, sc)
"""
# Get our shellcode
@@ -795,7 +816,7 @@ class ELF(ELFFile):
try:
with context.silent:
io = process(path)
data = context._decode(io.recvall(timeout=2))
data = packing._decode(io.recvall(timeout=2))
except Exception:
log.warn_once("Injected /proc/self/maps code did not execute correctly")
return {}
@@ -842,7 +863,7 @@ class ELF(ELFFile):
if not isinstance(sec, SymbolTableSection):
continue
for sym in sec.iter_symbols():
for sym in _iter_symbols(sec):
# Avoid duplicates
if sym.name in self.functions:
continue
@@ -866,7 +887,7 @@ class ELF(ELFFile):
if not isinstance(section, SymbolTableSection):
continue
for symbol in section.iter_symbols():
for symbol in _iter_symbols(section):
value = symbol.entry.st_value
if not value:
continue
@@ -907,7 +928,7 @@ class ELF(ELFFile):
if self.statically_linked:
return
for section in self.iter_sections():
for section in self.sections:
# We are only interested in relocations
if not isinstance(section, RelocationSection):
continue
@@ -961,7 +982,7 @@ class ELF(ELFFile):
# Iterate over the dynamic symbol table
dynsym = self.get_section_by_name('.dynsym')
symbol_iter = dynsym.iter_symbols()
symbol_iter = _iter_symbols(dynsym)
# 'gotsym' is the index of the first GOT symbol
gotsym = self.dynamic_value_by_tag('DT_MIPS_GOTSYM')
@@ -1003,9 +1024,10 @@ class ELF(ELFFile):
# In particular, this is where EBX points when it points into the GOT.
dt_pltgot = self.dynamic_value_by_tag('DT_PLTGOT') or 0
# There are two PLTs we may need to search
# There are three PLTs we may need to search
plt = self.get_section_by_name('.plt') # <-- Functions only
plt_got = self.get_section_by_name('.plt.got') # <-- Functions used as data
plt_sec = self.get_section_by_name('.plt.sec')
plt_mips = self.get_section_by_name('.MIPS.stubs')
# Invert the GOT symbols we already have, so we can look up by address
@@ -1013,7 +1035,7 @@ class ELF(ELFFile):
inv_symbols.update({v:k for k,v in self.symbols.items()})
with context.local(arch=self.arch, bits=self.bits, endian=self.endian):
for section in (plt, plt_got, plt_mips):
for section in (plt, plt_got, plt_sec, plt_mips):
if not section:
continue
@@ -1026,8 +1048,8 @@ class ELF(ELFFile):
for address, target in sorted(res.items()):
self.plt[inv_symbols[target]] = address
for a,n in sorted({v:k for k,v in self.plt.items()}.items()):
log.debug('PLT %#x %s', a, n)
# for a,n in sorted({v:k for k,v in self.plt.items()}.items()):
# log.debug('PLT %#x %s', a, n)
def _populate_kernel_version(self):
if 'linux_banner' not in self.symbols:
@@ -1095,8 +1117,8 @@ class ELF(ELFFile):
return_from_main = int(return_from_main[ : return_from_main.index(':') ], 16)
return return_from_main
def search(self, needle, writable = False):
"""search(needle, writable = False) -> generator
def search(self, needle, writable = False, executable = False):
"""search(needle, writable = False, executable = False) -> generator
Search the ELF's virtual address space for the specified string.
@@ -1109,6 +1131,7 @@ class ELF(ELFFile):
Arguments:
needle(str): String to search for.
writable(bool): Search only writable sections.
executable(bool): Search only executable sections.
Yields:
An iterator for each virtual address that matches.
@@ -1126,11 +1149,20 @@ class ELF(ELFFile):
>>> len(list(bash.search(b'GNU bash'))) > 0
True
It is also possible to search for instructions in executable sections.
>>> binary = ELF.from_assembly('nop; mov eax, 0; jmp esp; ret')
>>> jmp_addr = next(binary.search(asm('jmp esp'), executable = True))
>>> binary.read(jmp_addr, 2) == asm('jmp esp')
True
"""
load_address_fixup = (self.address - self.load_addr)
if writable:
segments = self.writable_segments
elif executable:
segments = self.executable_segments
else:
segments = self.segments
@@ -1825,7 +1857,7 @@ class ELF(ELFFile):
# Check for Linux configuration, it must contain more than
# just the version.
if len(self.config) > 1:
config_opts = collections.defaultdict(lambda: [])
config_opts = collections.defaultdict(list)
for checker in kernel_configuration:
result, message = checker(self.config)
+1 -1
View File
@@ -17,7 +17,7 @@ CAT_PROC_MAPS_EXIT = {
'000020e00170a0e3000000ef',
'thumb':
'004f01e0617073ff4fea07274fea172780b4dff8047001e06c662f6d80b4dff8047001e0632f736580b4dff8047001e02f70726f80b4684681ea010182ea02024ff0050741df05464ff00100294682ea02026ff000434ff0bb0741df'
'80ea00004ff0010741df',
'80ea00004ff0010741df00bf',
'mips':
'726f093c2f702935f0ffa9af7365093c632f2935f4ffa9af2f6d093c6c662935f8ffa9af8cff193c9e8f393727482003fcffa9aff0ffbd272020a003ffff0528ffff0628a50f02340c010101feff192427202003fcffa2affcffa58fffff0628ff7f073cffffe7346f1002340c010101'
'ffff0428a10f02340c010101',
+25 -9
View File
@@ -36,13 +36,17 @@ def emulate_plt_instructions(elf, got, address, data, targets):
data = packing.unpack_many(data, bits=32, endian='little')
data = packing.flat(data, bits=32, endian='big')
uc, ctx = prepare_unicorn_and_context(elf, got, address, data)
# Brute force addresses, assume that PLT entry points are at 4-byte aligned
# Do not emulate more than a handful of instructions.
for i, pc in enumerate(range(address, address + len(data), 4)):
if log.isEnabledFor(logging.DEBUG):
log.debug('%s %#x', fiddling.enhex(data[i*4:(i+1) * 4]), pc)
log.debug(elf.disasm(pc, 4))
target = emulate_plt_instructions_inner(elf, got, pc, data[i*4:], targets)
uc.context_restore(ctx)
target = emulate_plt_instructions_inner(uc, elf, got, pc, data[i*4:], targets)
if target in targets:
log.debug("%#x -> %#x", pc, target)
@@ -50,8 +54,7 @@ def emulate_plt_instructions(elf, got, address, data, targets):
return rv
def emulate_plt_instructions_inner(elf, got, pc, data, targets):
# Deferred import to not affect load time
def prepare_unicorn_and_context(elf, got, address, data):
import unicorn as U
# Instantiate the emulator with the correct arguments for the current
@@ -88,15 +91,15 @@ def emulate_plt_instructions_inner(elf, got, pc, data, targets):
uc = U.Uc(arch, mode)
# Map the page of memory, and fill it with the contents
start = pc & (~0xfff)
stop = (pc + len(data) + 0xfff) & (~0xfff)
start = address & (~0xfff)
stop = (address + len(data) + 0xfff) & (~0xfff)
if not (0 <= start <= stop <= (1 << elf.bits)):
return None
uc.mem_map(start, stop-start)
uc.mem_write(pc, data)
assert uc.mem_read(pc, len(data)) == data
uc.mem_write(address, data)
assert uc.mem_read(address, len(data)) == data
# MIPS is unique in that it relies entirely on _DYNAMIC, at the beginning
# of the GOT. Each PLT stub loads an address stored here.
@@ -129,9 +132,17 @@ def emulate_plt_instructions_inner(elf, got, pc, data, targets):
trap = packing.p32(0x34000000, endian=elf.endian)
uc.mem_write(magic_addr, trap)
return uc, uc.context_save()
def emulate_plt_instructions_inner(uc, elf, got, pc, data, targets):
import unicorn as U
# Hook invalid addresses and any accesses out of the specified address range
stopped_addr = []
# For MIPS. Explanation at prepare_unicorn_and_context.
magic_addr = 0xdbdbdbdb
def hook_mem(uc, access, address, size, value, user_data):
# Special case to allow MIPS to dereference the _DYNAMIC pointer
# in the GOT.
@@ -142,8 +153,10 @@ def emulate_plt_instructions_inner(elf, got, pc, data, targets):
uc.emu_stop()
return False
uc.hook_add(U.UC_HOOK_MEM_READ, hook_mem, stopped_addr)
uc.hook_add(U.UC_HOOK_MEM_UNMAPPED, hook_mem, stopped_addr)
hooks = [
uc.hook_add(U.UC_HOOK_MEM_READ, hook_mem, stopped_addr),
uc.hook_add(U.UC_HOOK_MEM_UNMAPPED, hook_mem, stopped_addr)
]
# callback for tracing instructions
# def hook_code(uc, address, size, user_data):
@@ -178,4 +191,7 @@ def emulate_plt_instructions_inner(elf, got, pc, data, targets):
if stopped_addr:
retval = stopped_addr.pop()
for hook in hooks:
uc.hook_del(hook)
return retval
Loaded 100 of 640 files, more files were not shown because too many files have changed in this diff. Show more