Giter Site home page Giter Site logo

build-an-efficient-pwn-environment's Introduction

Build an efficient pwn development environment in 2020

It has been years that, every time I determined to start learning pwn, I found that I can't write the exploits or debug the executable efficiently.

I finally decided to do something to change this situation.

So I spent some time on the usage of related tools. I even developed some scripts and tools to help me with a better experience.

Now you could have a more efficient pwn development environment in the year of 2020.

You can have a glimpse of the final environment in the GIF above.

In this article, I will show you how to build this environment.

Arch Linux

If you want to pwn an ELF, firstly you need a Linux distribution.

I use Arch Linux, which owns a powerful AUR to install different kinds of softwares, and all the following parts are based on it.

If you use other Linux distribution or even macOS, you may need to find ways to install some packages on your computer. But configurations below should still be useful for you.

Or you can just switch to Arch Linux, or Manjaro if you don't want to install a Linux distribution by command line.

You may find many articles still teach you to use yaourt to install packages in AUR, but it has discontinued and is not suggested to use.

It's better to choose another AUR helper, and my suggestion is Yay. You can install it by ways listed here.

glibc

glibc is the most important library in Linux, and when debugging we usually need to refer to some symbols in glibc, such as main_arena.

Arch Linux doesn't provide us with glibc symbols. If we need to add symbols to glibc, we must edit its PKGBUILD and add debug to options and package it by ourselves:

yay -G glibc
cd glibc
sed -i 's/options=(!strip staticlibs)/options=(!strip debug staticlibs)/' PKGBUILD
makepkg -si

Notice: this step could not be necessary if you want to use the glibc same as which used on the server. In this situation, you may need to check the virtual environment section to solve it.

GDB

The most important tool when debugging is GDB. (Certainly, you can use LLDB if you like)

You can install it by

pacman -S gdb

and if you need to debug ELF in other architectures rather than i386/x86_64, you need to install gdb-multiarch from AUR:

yay -S gdb-multiarch

But GDB itself is hard to use, you need some plugins to enhance GDB.

You may have heard of peda, but today we have better choices like GEF and pwndbg, which are more powerful and in active development.

You can install them by

yay -S gef-git

or

yay -S pwndbg-git

and add source /usr/share/gef/gef.py or source /usr/share/pwndbg/gdbinit.py in ~/.gdbinit to use them.

hyperpwn

Although GEF and pwndbg can help us a lot when debugging, they simply print all the context outputs to terminal and don't organize them in a layout like what have done in ollydbg and x64dbg.

You may have heard of Voltron or gdb-dashboard to help this, and they can be used together with GEF or pwndbg. But that means you must disable the context function in GEF or pwndbg, which may lose some features provided by them, and although we can use some ways to automate the layout creation, it still needs manual intervention.

One major drawback of tools above is that we can't easily check for previous states, which is very useful when debugging. We need to scroll the terminal again and again and lost in huge amounts of outputs, or previous outputs may have been cleared.

Certainly, we can use reverse debugging in GDB or rr to help us, but most time we only need to have a peek of the previous state.

Some people tried to solve this problem before like this, but it was only a prototype.

I have developed a new tool named hyperpwn to solve all the problems mentioned before.

hyperpwn bases on Hyper terminal, you can install it by

pacman -S hyper

or you can install the git version of Hyper by

yay -S hyper-git

then follow the steps here to install hyperpwn.

After hyperpwn is installed correctly, if you run gdb in Hyper terminal and GEF or pwndbg is loaded, a layout will be created automatically.

pwntools

The most widely used library to facilitate creating pwn script is pwntools.

pwntools depended on Python 2 before, which has reached its end-of-life now.

Now pwntools also supports Python 3. It's time for you to write exploits in Python 3!

You can install it by:

pacman -S python-pwntools

VS Code

We need a handy editor to help us write pwn scripts. I suggest using Visual Studio Code, which is lightweight, out-of-the-box and powerful.

You can install the open source build version of VS Code by

pacman -S code

or install the official binary version by

yay -S visual-studio-code-bin

Then you just need to install the python plugin, and you can start to write pwn scripts.

Settings

There are some settings needed to tweak to improve the experience. You can find config file including all the settings below in settings.json.

Code completion

VS Code uses Jedi to do code completions. But you may find that the following code can't be completed:

Because Jedi can't detect the type of sh correctly.

We can add a type hinting to help Jedi with this:

It seems that Microsoft Python Language Server can't recognize this kind of type hinting, so if you want to have completions in such situation, make sure python.jediEnabled is set to true.

Integrated terminal

VS Code provides us with an integrated terminal. So when you finish your script, you don't need to leave VS Code to run it.

You can just right click in the pwn script and select Run Python File in Terminal, and the file will be executed in VS Code's integrated terminal.

You can also select Run Selection/Line in Python Terminal to send parts of your script to REPL, which will help you a lot when writing script.

As most pwn scripts are written in a single file, and may use a relative path like gdb.debug('./a.out'), it's better to let the script run in file's directory by setting python.terminal.executeInFileDir to true. (However, this option currently doesn't affect Run Selection/Line in Python Terminal)

You can replace the default Python REPL with IPython to get a more powerful interactive REPL, by setting python.terminal.launchArgs to ["-m", "IPython", "--no-autoindent"].

In order to use Ctrl+P in terminal to select commands executed previously, you need to set terminal.integrated.commandsToSkipShell with ["-workbench.action.quickOpen"].

Code runner

It's a pity that Run Python File in Terminal and Run Selection/Line in Python Terminal can't be used consecutively. As Run Selection/Line in Python Terminal can't be replaced easily, we can replace the Run Python File in Terminal function with the Code Runner plugin.

Like what has been mentioned before, we need to set code-runner.fileDirectoryAsCwd to true, so the relative path to executable can be parsed correctly.

Many pwn scripts use the interactive function to interact with the shell, so we need to set code-runner.runInTerminal to true.

macros

When we debug pwn script, we may need to run the whole script file in REPL again and again.

Instead of boring Select all, Run Selection in Python Terminal and Cancel Selection, we can combine these steps with one shortcut.

To achive this, we need to install the macros plugin, then add this into settings.json:

    "macros.list": {
        "pythonExecFile": [
            "workbench.action.files.save",
            "editor.action.selectAll",
            "python.execSelectionInTerminal",
            "cancelSelection",
        ],
    },

And set the shortcut in keybindings.json:

[
    {
        "key": "shift+alt+enter",
        "command": "macros.pythonExecFile"
    }
]

Shortcuts

There are some shortcuts which are very useful when we write pwn scripts:

Command Keybinding
Toggle Line comment Ctrl + /
Focus into Python Script Ctrl + 1
Toggle / Focus into Integrated Terminal Ctrl + `
Run Selection/Line in Python Terminal Shift + Enter

Full keyboard shortcuts of VS Code can be found here or just press Ctrl+K Ctrl+S in VS Code.

You can also install the Vim plugin if you are familar with vim key bindings.

Cooperation

Now we have all parts needed to build a pwn environment. How can we combine them together so we can get an efficient pwn environment?

The key part is the cooperation of pwntools and hyperpwn. We need pwntools when we write pwn scripts and hyperpwn to debug the executable.

pwntools provides gdb.debug function to create a debug session by a script file. It will start gdbserver with the executable to be debugged in the background and run gdb in a new terminal to connect the gdbserver.

We can control which terminal will be chosen by setting context.terminal, e.g., ['konsole', '-e']. However, Hyper terminal, which hyperpwn replies on, doesn't provide similar arguments.

And even Hyper provides this, it mostly means that we need to start a new Hyper terminal every time we run gdb.debug, we can't specify to run gdb in an existed terminal.

To solve this problem, I created two simple scripts, one acts as a server and the other one acts as a client. They communicate with named pipe.

Server side script hyperpwn-server.sh which should be used in Hyper terminal:

#!/bin/bash
pipe=/tmp/hyperpwn-pipe; if [[ ! -p $pipe ]]; then mkfifo $pipe; fi; while read line < $pipe; do sh -c "$line"; echo "Waiting for new session..."; done

Client side script hyperpwn-client.sh which should be set as context.terminal:

#!/bin/bash
echo "cd $PWD; $1" > /tmp/hyperpwn-pipe

After gdb connected to gdbserver, we may find that even if we use sh.close() to shutdown gdbserver, gdb will remain there, which prevents the next session:

I created a gdb python script autoquit.py to quit gdb when the connection is closed:

import gdb
def exec_quit(prompt):
    gdb.execute("quit")

def exit_handler(event):
    gdb.prompt_hook = exec_quit

gdb.events.exited.connect(exit_handler)

That's what it looks like after source this script in ~/.gdbinit:

If you only have one monitor, you may want to put the VS Code window and the Hyper window side by side.

I created a vertical layout of hyperpwn, so you can maximize the use of your monitor. you can overwrite configs in ~/.hyperinator with them to enable it.

If you use GEF, you can replace ~/.hyperinator/hyperpwn-gef.yml with hyperpwn-gef.yml:

session_name: gef
global_options:
  default-shell: /bin/sleep
  default-shell-args: 100000000
windows:
- layout: 34da,70x51,0,0[70x25,0,0{28x25,0,0,1,41x25,29,0[41x14,29,0,2,41x7,29,15,3,41x2,29,23,4]},70x14,0,26,5,70x10,0,41,6]
  panes:
  - shell_command:
    - hyperpwn trace
  - shell_command:
    - hyperpwn stack
  - shell_command:
    -
    reuse: True
    focus: True
  - shell_command:
    - hyperpwn thread
  - shell_command:
    - hyperpwn code
  - shell_command:
    - hyperpwn reg

If you use pwndbg, you can replace ~/.hyperinator/hyperpwn-pwndbg.yml with hyperpwn-pwndbg.yml:

session_name: pwndbg
global_options:
  default-shell: /bin/sleep
  default-shell-args: 100000000
windows:
- layout: 5d07,70x52,0,0[70x24,0,0{32x24,0,0,1,37x24,33,0[37x15,33,0,2,37x5,33,16,3,37x2,33,22,4]},70x15,0,25,5,70x11,0,41,6]
  panes:
  - shell_command:
    - hyperpwn TRACE
  - shell_command:
    - hyperpwn STACK
  - shell_command:
    -
    reuse: True
    focus: True
  - shell_command:
    - hyperpwn LEGEND
  - shell_command:
    - hyperpwn DISASM
  - shell_command:
    - hyperpwn REG

I have created a python snippet, so you can create a pwn script template with some tips mentioned before by just typing pwn.

You can use it by select File - Perference - User Snippets - Python and paste this python.json file there, and you can change it as you like:

{
	"pwn": {
		"prefix": "pwn",
		"body": [
			"from pwn import *",
			"",
			"try:",
			"\tsh.close()",
			"except:",
			"\tpass",
			"",
			"context.clear(arch='amd64')",
			"context.log_level = 'debug'",
			"context.terminal = ['/path/to/hyperpwn-client.sh']",
			"",
			"filename = './${1:a.out}'",
			"",
			"elf = ELF(filename)",
			"libc = elf.libc",
			"",
			"sh = gdb.debug(filename) # type: pwnlib.tubes.process.process",
			"# sh = process(filename)",
			"# sh = remote('127.0.0.1', 7777)",
			""
		],
		"description": "pwn script template"
	}
}

Virtual environment

One big drawback of our environment is that most pwn executables are running on Ubuntu, and the version of glibc is different from our environment.

Virtual environment can help us with this situation. It can provide us a Ubuntu environment with a low cost.

we can create a virtual environment by debootstrap, Docker or Vagrant.

I prefer to use debootstrap to build a chroot environment, and use schroot to enter it, which is very lightweight. You only need less than 2GB for a specify Ubuntu version.

You can install them by

pacman -S debootstrap schroot

For example, if you need an Ubuntu 16.04 environment, you can download it by

debootstrap --arch amd64 --variant=buildd xenial /srv/chroot/xenial http://archive.ubuntu.com/ubuntu/

Copy this xenial.conf into /etc/schroot/chroot.d/:

[xenial]
description=Ubuntu 16.04
type=directory
directory=/srv/chroot/xenial
shell=/bin/bash
users=user
root-users=user
groups=sudo
profile=desktop
personality=linux
preserve-environment=true

Then enter this environment by

schroot -c xenial

If you need other version of Ubuntu, just change xenial with corresponding name.

We can enter the virtual environment's Pyhon REPL manually in VS Code's integrated terminal, the Run Selection/Line in Python Terminal function should also work well.

You may need to install pwntools in this virtual environment again, but other tools installed on the host can just be used as before.

Embedded environment

Sometimes we may need to pwn a real-life program on an embedded device.

But some embedded devices use a minimal Linux environment, which could not provide gdb or gdbserver for us, and it could be not easy to cross compile them as the source code of gdb is so huge.

Certainly, we can use prebuilt statically linked gdbserver compiled by others likes this, but if it can't work in your environment it's hard to fix it.

To solve this problem, I developed a tiny gdbserver from scratch, you can find it here.

It's very easy to compile it, all you need is a gcc that can generate ELF for the target environment.

You can connect this tiny gdbserver with a normal gdb client, and most common commands needed when debugging should work.

You can even load GEF or pwndbg in gdb client, and use hyperpwn on it, likes what have been described before.

Conclusion

In this article, I share some ways I used to build my pwn development environment.

Hope it's useful for you when you build your own environment.

And if you find some other ways and want to share it to others, feel free to send a pull request!

Happy hacking~

build-an-efficient-pwn-environment's People

Contributors

bet4it avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

build-an-efficient-pwn-environment's Issues

Update requirement to use unicorn-engine 1.0.3 or unicorn2

When install pwntools via pip with command: pip install pwntools , it requires unicorn-engine >1.0.2rc1 - 1.0.2rc4.
But some other lib use pwntools >=1.0.3 and unicorn-engine will be bump up to unicorn2. I think we nees to update :D

Hyperpwn-client.sh do not work

`from pwn import *

context.binary = './combo-chain'
context.log_level = 'debug'
context.terminal=['~/hyperpwn/hyperpwn-client.sh']

conn = gdb.debug('./combo-chain')`

Result:
Starting local process '/usr/bin/gdbserver' argv=[b'/usr/bin/gdbserver', b'--multi', b'--no-disable-randomization', b'localhost:0', b'./combo-chain'] : pid 21153 [DEBUG] Received 0x43 bytes: b'Process ./combo-chain created; pid = 21157\n' b'Listening on port 45131\n' [DEBUG] Wrote gdb script to '/tmp/pwn24bii4nz.gdb' target remote 127.0.0.1:45131 [*] running in new terminal: /usr/bin/gdb -q "./combo-chain" -x /tmp/pwn24bii4nz.gdb [DEBUG] Launching a new terminal: ['~/hyperpwn/hyperpwn-client.sh', '/usr/bin/gdb -q "./combo-chain" -x /tmp/pwn24bii4nz.gdb']

I set context.terminal , but the terminal where hyperpwn-server.sh work show nothing.
Help me ...

Hyperpwn-client & hyperpwn-server

Great work on the debugger build. The one that I was curious was when do you automatically load up hyperpwn-client and hyperpwn-server? I wanted to make sense of this and figure out when you could actually run both? Ideally I would just like to hit gdb on Hyper and both scripts will run off the bat. It seems arbitrary when/where you would start it.

How can I start everything with one click

How can I start everything with one click?
Now I have to start hyper and type ./hyper-server.sh
the terminal should be set to ./hyper.client.sh
Can I find a way to start it quickly?

Explain in detail the virtual environment setup?

Hi there, thank you for sharing this great setup. It’s so useful. However, could you explain the virtual environment setup in detail?

Or can you post your own setup in this repo, so others can refer to them.

Awesome Work

If you document how to get all this to work on Kali/Debian I bet you will get a big uptick in usage.

hyperpwn_client.sh can't function normally when combined with pwntools

This question is simliar to issue 5.

environment

kali 2020.4

problem

python script

I have the following python script:

from pwn import *
context.clear(arch='amd64')
context.log_level = 'debug'
context.terminal = ['~/hyperpwn-client.sh']
filename = "ls"
sh = gdb.debug(filename) # type: pwnlib.tubes.process.process

run result

then i run it in terminal with an opening hyper terminal which runs the server, but the ~/hyperpwn-client.sh doesn't take effect

[DEBUG] Received 0x38 bytes:
    'Process ls created; pid = 16673\n'
    'Listening on port 44169\n'
[DEBUG] Wrote gdb script to '/tmp/pwnkaSrGb.gdb'
    target remote 127.0.0.1:44169
[*] running in new terminal: /usr/bin/gdb -q  "/usr/bin/ls" -x /tmp/pwnkaSrGb.gdb
[DEBUG] Launching a new terminal: ['~/hyperpwn-client.sh', '/usr/bin/gdb -q  "/usr/bin/ls" -x /tmp/pwnkaSrGb.gdb']
[*] Stopped process '/usr/bin/ls' (pid 16673)

but if i run~/hyperpwn-client.sh '/usr/bin/gdb -q "/usr/bin/ls" -x /tmp/pwnkaSrGb.gdb' on terminal, it can function normally

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.