markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
The optional parameter `do_not_encode` allows us to skip certain characters from encoding. This is useful when encoding grammar rules:
cgi_encode("<string>@<string>", "<>")
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
`cgi_encode()` is the exact counterpart of the `cgi_decode()` function defined in the [chapter on coverage](Coverage.ipynb):
from Coverage import cgi_decode # minor dependency cgi_decode(s)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
End of Excursion In the grammar, we make use of `cgi_encode()` to encode strings:
from Grammars import crange, is_valid_grammar, syntax_diagram, Grammar ORDER_GRAMMAR: Grammar = { "<start>": ["<order>"], "<order>": ["/order?item=<item>&name=<name>&email=<email>&city=<city>&zip=<zip>"], "<item>": ["tshirt", "drill", "lockset"], "<name>": [cgi_encode("Jane Doe"), cgi_encode("John Smith...
start
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Using [one of our grammar fuzzers](GrammarFuzzer.iynb), we can instantiate this grammar and generate URLs:
from GrammarFuzzer import GrammarFuzzer order_fuzzer = GrammarFuzzer(ORDER_GRAMMAR) [order_fuzzer.fuzz() for i in range(5)]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Sending these URLs to the server will have them processed correctly:
HTML(webbrowser(urljoin(httpd_url, order_fuzzer.fuzz()))) print(db.execute("SELECT * FROM orders").fetchall())
[('tshirt', 'Jane Doe', 'doe@example.com', 'Seattle', '98104'), ('lockset', 'Jane Doe', 'j_smith@example.com', 'Seattle', '16631')]
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Fuzzing with Unexpected Values We can now see that the server does a good job when faced with "standard" values. But what happens if we feed it non-standard values? To this end, we make use of a [mutation fuzzer](MutationFuzzer.ipynb) which inserts random changes into the URL. Our seed (i.e. the value to be mutated...
seed = order_fuzzer.fuzz() seed
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Mutating this string yields mutations not only in the field values, but also in field names as well as the URL structure.
from MutationFuzzer import MutationFuzzer # minor deoendency mutate_order_fuzzer = MutationFuzzer([seed], min_mutations=1, max_mutations=1) [mutate_order_fuzzer.fuzz() for i in range(5)]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Let us fuzz a little until we get an internal server error. We use the Python `requests` module to interact with the Web server such that we can directly access the HTTP status code.
while True: path = mutate_order_fuzzer.fuzz() url = urljoin(httpd_url, path) r = requests.get(url) if r.status_code == HTTPStatus.INTERNAL_SERVER_ERROR: break
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
That didn't take long. Here's the offending URL:
url clear_httpd_messages() HTML(webbrowser(url))
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
How does the URL cause this internal error? We make use of [delta debugging](Reducer.ipynb) to minimize the failure-inducing path, setting up a `WebRunner` class to define the failure condition:
failing_path = path failing_path from Fuzzer import Runner class WebRunner(Runner): """Runner for a Web server""" def __init__(self, base_url: str = None): self.base_url = base_url def run(self, url: str) -> Tuple[str, str]: if self.base_url is not None: url = urljoin(self.base...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
This is the minimized path:
from Reducer import DeltaDebuggingReducer # minor minimized_path = DeltaDebuggingReducer(web_runner).reduce(failing_path) minimized_path
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
It turns out that our server encounters an internal error if we do not supply the requested fields:
minimized_url = urljoin(httpd_url, minimized_path) minimized_url clear_httpd_messages() HTML(webbrowser(minimized_url))
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We see that we might have a lot to do to make our Web server more robust against unexpected inputs. The [exercises](Exercises) give some instructions on what to do. Extracting Grammars for Input FormsIn our previous examples, we have assumed that we have a grammar that produces valid (or less valid) order queries. H...
html_text = webbrowser(httpd_url) print(html_text[html_text.find("<form"):html_text.find("</form>") + len("</form>")])
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We see that there is a number of form elements that accept inputs, in particular ``, but also `` and ``. The idea now is to _parse_ the HTML of the Web page in question, to extract these individual input elements, and then to create a _grammar_ that produces a matching URL, effectively filling out the form. To parse t...
from html.parser import HTMLParser
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
During parsing, we search for `` tags and save the associated action (i.e., the URL to be invoked when the form is submitted) in the `action` attribute. While processing the form, we create a map `fields` that holds all input fields we have seen; it maps field names to the respective HTML input types (`"text"`, `"numb...
class FormHTMLParser(HTMLParser): """A parser for HTML forms""" def reset(self) -> None: super().reset() # Form action attribute (a URL) self.action = "" # Map of field name to type # (or selection name to [option_1, option_2, ...]) self.fields: Dict[str, List...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
While parsing, the parser calls `handle_starttag()` for every opening tag (such as ``) found; conversely, it invokes `handle_endtag()` for closing tags (such as ``). `attributes` gives us a map of associated attributes and values.Here is how we process the individual tags:* When we find a `` tag, we save the associate...
class FormHTMLParser(FormHTMLParser): def handle_starttag(self, tag, attrs): attributes = {attr_name: attr_value for attr_name, attr_value in attrs} # print(tag, attributes) if tag == "form": self.action = attributes.get("action", "") elif tag == "select" or tag == "dat...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Our implementation handles only one form per Web page; it also works on HTML only, ignoring all interaction coming from JavaScript. Also, it does not support all HTML input types. Let us put this parser to action. We create a class `HTMLGrammarMiner` that takes a HTML document to parse. It then returns the associate...
class HTMLGrammarMiner: """Mine a grammar from a HTML form""" def __init__(self, html_text: str) -> None: """Constructor. `html_text` is the HTML string to parse.""" html_parser = FormHTMLParser() html_parser.feed(html_text) self.fields = html_parser.fields self.action ...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Applied on our order form, this is what we get:
html_miner = HTMLGrammarMiner(html_text) html_miner.action html_miner.fields
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
From this structure, we can now generate a grammar that automatically produces valid form submission URLs. Mining Grammars for Web Pages To create a grammar from the fields extracted from HTML, we build on the `CGI_GRAMMAR` defined in the [chapter on grammars](Grammars.ipynb). The key idea is to define rules for ever...
from Grammars import crange, srange, new_symbol, unreachable_nonterminals, CGI_GRAMMAR, extend_grammar class HTMLGrammarMiner(HTMLGrammarMiner): QUERY_GRAMMAR: Grammar = extend_grammar(CGI_GRAMMAR, { "<start>": ["<action>?<query>"], "<text>": ["<string>"], "<number>": ["<digits>"], ...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Our grammar miner now takes the fields extracted from HTML, converting them into rules. Essentially, every input field encountered gets included in the resulting query URL; and it gets a rule expanding it into the appropriate type.
class HTMLGrammarMiner(HTMLGrammarMiner): def mine_grammar(self) -> Grammar: """Extract a grammar from the given HTML text""" grammar: Grammar = extend_grammar(self.QUERY_GRAMMAR) grammar["<action>"] = [self.action] query = "" for field in self.fields: field_sym...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Let us show `HTMLGrammarMiner` in action, again applied on our order form. Here is the full resulting grammar:
html_miner = HTMLGrammarMiner(html_text) grammar = html_miner.mine_grammar() grammar
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Let us take a look into the structure of the grammar. It produces URL paths of this form:
grammar["<start>"]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Here, the `` comes from the `action` attribute of the HTML form:
grammar["<action>"]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
The `` is composed from the individual field items:
grammar["<query>"]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Each of these fields has the form `=`, where `` is already defined in the grammar:
grammar["<zip>"] grammar["<terms>"]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
These are the query URLs produced from the grammar. We see that these are similar to the ones produced from our hand-crafted grammar, except that the string values for names, email addresses, and cities are now completely random:
order_fuzzer = GrammarFuzzer(grammar) [order_fuzzer.fuzz() for i in range(3)]
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We can again feed these directly into our Web browser:
HTML(webbrowser(urljoin(httpd_url, order_fuzzer.fuzz())))
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We see (one more time) that we can mine a grammar automatically from given data. A Fuzzer for Web FormsTo make things most convenient, let us define a `WebFormFuzzer` class that does everything in one place. Given a URL, it extracts its HTML content, mines the grammar and then produces inputs for it.
class WebFormFuzzer(GrammarFuzzer): """A Fuzzer for Web forms""" def __init__(self, url: str, *, grammar_miner_class: Optional[type] = None, **grammar_fuzzer_options): """Constructor. `url` - the URL of the Web form to fuzz. `grammar_miner_class` - the ...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
All it now takes to fuzz a Web form is to provide its URL:
web_form_fuzzer = WebFormFuzzer(httpd_url) web_form_fuzzer.fuzz()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We can combine the fuzzer with a `WebRunner` as defined above to run the resulting fuzz inputs directly on our Web server:
web_form_runner = WebRunner(httpd_url) web_form_fuzzer.runs(web_form_runner, 10)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
While convenient to use, this fuzzer is still very rudimentary:* It is limited to one form per page.* It only supports `GET` actions (i.e., inputs encoded into the URL). A full Web form fuzzer would have to at least support `POST` actions.* The fuzzer is build on HTML only. There is no Javascript handling for dynamic...
clear_httpd_messages()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Crawling User Interfaces So far, we have assumed there would be only one form to explore. A real Web server, of course, has several pages – and possibly several forms, too. We define a simple *crawler* that explores all the links that originate from one page. Our crawler is pretty straightforward. Its main componen...
class LinkHTMLParser(HTMLParser): """Parse all links found in a HTML page""" def reset(self): super().reset() self.links = [] def handle_starttag(self, tag, attrs): attributes = {attr_name: attr_value for attr_name, attr_value in attrs} if tag == "a" and "href" in attribut...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
The actual crawler comes as a _generator function_ `crawl()` which produces one URL after another. By default, it returns only URLs that reside on the same host; the parameter `max_pages` controls how many pages (default: 1) should be scanned. We also respect the `robots.txt` file on the remote site to check which pa...
from collections import deque import urllib.robotparser def crawl(url, max_pages: Union[int, float] = 1, same_host: bool = True): """Return the list of linked URLs from the given URL. `max_pages` - the maximum number of pages accessed. `same_host` - if True (default), stay on the same host""" pages = d...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
End of Excursion We can run the crawler on our own server, where it will quickly return the order page and the terms and conditions page.
for url in crawl(httpd_url): print_httpd_messages() print_url(url)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We can also crawl over other sites, such as the home page of this project.
for url in crawl("https://www.fuzzingbook.org/"): print_url(url)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Once we have crawled over all the links of a site, we can generate tests for all the forms we found:
for url in crawl(httpd_url, max_pages=float('inf')): web_form_fuzzer = WebFormFuzzer(url) web_form_runner = WebRunner(url) print(web_form_fuzzer.run(web_form_runner))
('http://127.0.0.1:8800/terms', 'PASS') ('http://127.0.0.1:8800/order?item=tshirt&name=+&email=b+%742%40+&city=%45%39&zip=54&terms=on&submit=', 'PASS') ('http://127.0.0.1:8800/order?item=drill&name=%52-&email=e%40%3f&city=+&zip=5&terms=on&submit=', 'PASS')
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
For even better effects, one could integrate crawling and fuzzing – and also analyze the order confirmation pages for further links. We leave this to the reader as an exercise. Let us get rid of any server messages accumulated above:
clear_httpd_messages()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Crafting Web AttacksBefore we close the chapter, let us take a look at a special class of "uncommon" inputs that not only yield generic failures, but actually allow _attackers_ to manipulate the server at their will. We will illustrate three common attacks using our server, which (surprise) actually turns out to be v...
from Grammars import extend_grammar ORDER_GRAMMAR_WITH_HTML_INJECTION: Grammar = extend_grammar(ORDER_GRAMMAR, { "<name>": [cgi_encode(''' Jane Doe<p> <strong><a href="www.lots.of.malware">Click here for cute cat pictures!</a></strong> </p> ''')], })
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
If we use this grammar to create inputs, the resulting URL will have all of the HTML encoded in:
html_injection_fuzzer = GrammarFuzzer(ORDER_GRAMMAR_WITH_HTML_INJECTION) order_with_injected_html = html_injection_fuzzer.fuzz() order_with_injected_html
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
What hapens if we send this string to our Web server? It turns out that the HTML is left in the confirmation page and shown as link. This also happens in the log:
HTML(webbrowser(urljoin(httpd_url, order_with_injected_html)))
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Since the link seemingly comes from a trusted origin, users are much more likely to follow it. The link is even persistent, as it is stored in the database:
print(db.execute("SELECT * FROM orders WHERE name LIKE '%<%'").fetchall())
[('drill', '\n Jane Doe<p>\n <strong><a href="www.lots.of.malware">Click here for cute cat pictures!</a></strong>\n </p>\n ', 'j_smith@example.com', 'Seattle', '02805')]
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
This means that anyone ever querying the database (for instance, operators processing the order) will also see the link, multiplying its impact. By carefully crafting the injected HTML, one can thus expose malicious content to a large number of users – until the injected HTML is finally deleted. Cross-Site Scripting ...
ORDER_GRAMMAR_WITH_XSS_INJECTION: Grammar = extend_grammar(ORDER_GRAMMAR, { "<name>": [cgi_encode('Jane Doe' + '<script>' + 'document.title = document.cookie.substring(0, 10);' + '</script>') ], }) xss_injection_fuzzer = Gr...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
The message looks as always – but if you have a look at your browser title, it should now show the first 10 characters of your "secret" notebook cookie. Instead of showing its prefix in the title, the script could also silently send the cookie to a remote server, allowing attackers to highjack your current notebook se...
HTML('<script>document.title = "Jupyter"</script>')
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
SQL Injection AttacksCross-site scripts have the same privileges as web pages – most notably, they cannot access or change data outside of your browser. So-called *SQL injection* targets _databases_, allowing to inject commands that can read or modify data in the database, or change the purpose of the original query....
values: Dict[str, str] = { "item": "tshirt", "name": "Jane Doe", "email": "j.doe@example.com", "city": "Seattle", "zip": "98104" }
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
and format the string as seen above:
sql_command = ("INSERT INTO orders " + "VALUES ('{item}', '{name}', '{email}', '{city}', '{zip}')".format(**values)) sql_command
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
All fine, right? But now, we define a very "special" name that can also be interpreted as a SQL command:
values["name"] = "Jane', 'x', 'x', 'x'); DELETE FROM orders; -- " sql_command = ("INSERT INTO orders " + "VALUES ('{item}', '{name}', '{email}', '{city}', '{zip}')".format(**values)) sql_command
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
What happens here is that we now get a command to insert values into the database (with a few "dummy" values `x`), followed by a SQL `DELETE` command that would _delete all entries_ of the orders table. The string `-- ` starts a SQL _comment_ such that the remainder of the original query would be easily ignored. By c...
from Grammars import extend_grammar ORDER_GRAMMAR_WITH_SQL_INJECTION = extend_grammar(ORDER_GRAMMAR, { "<name>": [cgi_encode("Jane', 'x', 'x', 'x'); DELETE FROM orders; --")], }) sql_injection_fuzzer = GrammarFuzzer(ORDER_GRAMMAR_WITH_SQL_INJECTION) order_with_injected_sql = sql_injection_fuzzer.fuzz() order_with_i...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
These are the current orders:
print(db.execute("SELECT * FROM orders").fetchall())
[('tshirt', 'Jane Doe', 'doe@example.com', 'Seattle', '98104'), ('lockset', 'Jane Doe', 'j_smith@example.com', 'Seattle', '16631'), ('drill', 'Jane Doe', 'j.doe@example.com', '', '45732'), ('drill', 'Jane Doe', 'j,doe@example.com', 'Seattle', '45732'), ('drill', ' ', '5F @p a ', 'cdb', '3230'), ('drill', ' m', '@@0',...
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Let us go and send our URL with SQL injection to the server. From the log, we see that the "malicious" SQL command is formed just as sketched above, and executed, too.
contents = webbrowser(urljoin(httpd_url, order_with_injected_sql))
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
All orders are now gone:
print(db.execute("SELECT * FROM orders").fetchall())
[]
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
This effect is also illustrated [in this very popular XKCD comic](https://xkcd.com/327/): ![https://xkcd.com/327/](PICS/xkcd_exploits_of_a_mom.png){width=100%} Even if we had not been able to execute arbitrary commands, being able to compromise an orders database offers several possibilities for mischief. For instance...
answer = webbrowser(urljoin(httpd_url, "/order"), mute=True) HTML(answer)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
The best way to avoid information leakage through failures is of course not to fail in the first place. But if you fail, _make it hard for the attacker to establish a link between the attack and the failure._ In particular,* Do not produce "internal error" messages (and certainly not ones with internal information).* ...
class SQLInjectionGrammarMiner(HTMLGrammarMiner): """Demonstration of an automatic SQL Injection attack grammar miner""" # Some common attack schemes ATTACKS: List[str] = [ "<string>' <sql-values>); <sql-payload>; <sql-comment>", "<string>' <sql-comment>", "' OR 1=1<sql-comment>'", ...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We see that several fields now are tested for vulnerabilities:
sql_fuzzer = GrammarFuzzer(grammar) sql_fuzzer.fuzz() print(db.execute("SELECT * FROM orders").fetchall()) contents = webbrowser(urljoin(httpd_url, "/order?item=tshirt&name=Jane+Doe&email=doe%40example.com&city=Seattle&zip=98104")) def orders_db_is_empty(): """Return True if the orders...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We create a `SQLInjectionFuzzer` that does it all automatically.
class SQLInjectionFuzzer(WebFormFuzzer): """Simple demonstrator of a SQL Injection Fuzzer""" def __init__(self, url: str, sql_payload : str ="", *, sql_injection_grammar_miner_class: Optional[type] = None, **kwargs): """Constructor. `url` - the Web page (with a...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Our attack was successful! After less than a second of testing, our database is empty:
orders_db_is_empty()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Again, note the level of possible automation: We can* Crawl the Web pages of a host for possible forms* Automatically identify form fields and possible values* Inject SQL (or HTML, or JavaScript) into any of these fieldsand all of this fully automatically, not needing anything but the URL of the site. The bad news is t...
web_form_fuzzer = WebFormFuzzer(httpd_url) web_form_fuzzer.grammar['<start>'] web_form_fuzzer.grammar['<action>'] web_form_fuzzer.grammar['<query>']
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Using it for fuzzing yields a path with all form values filled; accessing this path acts like filling out and submitting the form.
web_form_fuzzer.fuzz()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Repeated calls to `WebFormFuzzer.fuzz()` invoke the form again and again, each time with different (fuzzed) values. Internally, `WebFormFuzzer` builds on a helper class named `HTMLGrammarMiner`; you can extend its functionality to include more features. SQL Injection Attacks`SQLInjectionFuzzer` is an experimental exte...
sql_fuzzer = SQLInjectionFuzzer(httpd_url, "DELETE FROM orders") sql_fuzzer.fuzz()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
As you can see, the path to be retrieved contains the payload encoded into one of the form field values. Internally, `SQLInjectionFuzzer` builds on a helper class named `SQLInjectionGrammarMiner`; you can extend its functionality to include more features. `SQLInjectionFuzzer` is a proof-of-concept on how to build a mal...
# ignore from ClassDiagram import display_class_hierarchy from Fuzzer import Fuzzer, Runner from Grammars import Grammar, Expansion from GrammarFuzzer import GrammarFuzzer, DerivationTree # ignore display_class_hierarchy([WebFormFuzzer, SQLInjectionFuzzer, WebRunner, HTMLGrammarMiner, SQLInject...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Lessons Learned* User Interfaces (in the Web and elsewhere) should be tested with _expected_ and _unexpected_ values.* One can _mine grammars from user interfaces_, allowing for their widespread testing.* Consequent _sanitizing_ of inputs prevents common attacks such as code and SQL injection.* Do not attempt to write...
clear_httpd_messages() httpd_process.terminate()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Next StepsFrom here, the next step is [GUI Fuzzing](GUIFuzzer.ipynb), going from HTML- and Web-based user interfaces to generic user interfaces (including JavaScript and mobile user interfaces).If you are interested in security testing, do not miss our [chapter on information flow](InformationFlow.ipynb), showing how ...
BETTER_HTML_INTERNAL_SERVER_ERROR = \ HTML_INTERNAL_SERVER_ERROR.replace("<pre>{error_message}</pre>", "") HTML(BETTER_HTML_INTERNAL_SERVER_ERROR)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We have the `internal_server_error()` message return `HTTPStatus.OK` to make it harder for machines to find out something went wrong:
class BetterHTTPRequestHandler(SimpleHTTPRequestHandler): def internal_server_error(self): # Note: No INTERNAL_SERVER_ERROR status self.send_response(HTTPStatus.OK, "Internal Error") self.send_header("Content-type", "text/html") self.end_headers() exc = traceback.format_exc...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Part 2: Sanitized HTMLSet up the server such that it is not vulnerable against HTML and JavaScript injection attacks, notably by using methods such as `html.escape()` to escape special characters when showing them.
import html
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
**Solution.** We pass all values read through `html.escape()` before showing them on the screen; this will properly encode `` characters.
class BetterHTTPRequestHandler(BetterHTTPRequestHandler): def send_order_received(self, values): sanitized_values = {} for field in values: sanitized_values[field] = html.escape(values[field]) sanitized_values["item_name"] = html.escape( FUZZINGBOOK_SWAG[values["item"...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Part 3: Sanitized SQLSet up the server such that it is not vulnerable against SQL injection attacks, notably by using _SQL parameter substitution._ **Solution.** We use SQL parameter substitution to avoid interpretation of inputs as SQL commands. Also, we use `execute()` rather than `executescript()` to avoid process...
class BetterHTTPRequestHandler(BetterHTTPRequestHandler): def store_order(self, values): db = sqlite3.connect(ORDERS_DB) db.execute("INSERT INTO orders VALUES (?, ?, ?, ?, ?)", (values['item'], values['name'], values['email'], values['city'], values['zip'])) db.commit()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
One could also argue not to save "dangerous" characters in the first place. But then, there might always be names or addresses with special characters which all need to be handled. Part 4: A Robust ServerSet up the server such that it does not crash with invalid or missing fields. **Solution.** We set up a simple che...
class BetterHTTPRequestHandler(BetterHTTPRequestHandler): REQUIRED_FIELDS = ['item', 'name', 'email', 'city', 'zip'] def handle_order(self): values = self.get_field_values() for required_field in self.REQUIRED_FIELDS: if required_field not in values: self.send_order_...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
This could easily be extended to check for valid (at least non-empty) values. Also, the order form should be pre-filled with the originally submitted values, and come with a helpful error message. Part 5: Test it!Test your improved server whether your measures have been successful. **Solution.** Here we go:
httpd_process, httpd_url = start_httpd(BetterHTTPRequestHandler) print_url(httpd_url) print_httpd_messages()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We test standard behavior:
standard_order = "/order?item=tshirt&name=Jane+Doe&email=doe%40example.com&city=Seattle&zip=98104" contents = webbrowser(httpd_url + standard_order) HTML(contents) assert contents.find("Thank you") > 0
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We test for incomplete URLs:
bad_order = "/order?item=" contents = webbrowser(httpd_url + bad_order) HTML(contents) assert contents.find("Order Form") > 0
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We test for HTML (and JavaScript) injection:
injection_order = "/order?item=tshirt&name=Jane+Doe" + cgi_encode("<script></script>") + \ "&email=doe%40example.com&city=Seattle&zip=98104" contents = webbrowser(httpd_url + injection_order) HTML(contents) assert contents.find("Thank you") > 0 assert contents.find("<script>") < 0 assert contents.find("&lt;script&g...
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
We test for SQL injection:
sql_order = "/order?item=tshirt&name=" + \ cgi_encode("Robert', 'x', 'x', 'x'); DELETE FROM orders; --") + \ "&email=doe%40example.com&city=Seattle&zip=98104" contents = webbrowser(httpd_url + sql_order) HTML(contents)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
(Okay, so obviously we can now handle the weirdest of names; still, Robert should consider changing his name...)
assert contents.find("DELETE FROM") > 0 assert not orders_db_is_empty()
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
That's it – we're done!
httpd_process.terminate() if os.path.exists(ORDERS_DB): os.remove(ORDERS_DB)
_____no_output_____
MIT
docs/notebooks/WebFuzzer.ipynb
vrthra-forks/fuzzingbook
Ensembl to RefSeq Mapping The constraint table from gnomAD has duplicate gene ID's - in the example of TUBB3 one gene ID is missannotated. Given out analysis is by transcript, it is probably better to use the transcript table from gnomAD. Howver, gnomAD used ENSEMBL transcripts and we used RefSeq Transcripts. Can map ...
import org.apache.spark.sql.{Row, SparkSession} import org.apache.spark.sql.types._ import org.apache.spark.sql.functions._ import org.apache.spark.sql.expressions.Window val customSchema = new StructType(Array( StructField("GeneID",StringType,true), StructField("GeneIDVer",StringType,true), StructField("Transcri...
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Double check there are no duplicates
val df_ref2ens = df_ens2ref.filter($"RefSeq".isNotNull).select("TranscriptID","RefSeq").sort($"TranscriptID").distinct df_ref2ens.show df_ref2ens.count df_ref2ens.select($"RefSeq").distinct.count df_ref2ens.groupBy($"RefSeq").count.sort($"count".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
gnomAD lof metrics by transcript We want to link the data to gnomAD constraint metrics (LOEUF and pLI):Supplemental Table describing data fields:https://static-content.springer.com/esm/art%3A10.1038%2Fs41586-020-2308-7/MediaObjects/41586_2020_2308_MOESM1_ESM.pdfSelect the following columns from the main file:* **gene*...
val cols_constraint = Seq("gene","gene_id","transcript","obs_mis","exp_mis","oe_mis","obs_syn","exp_syn","oe_syn", "p","pLI","pRec","pNull","oe_lof_upper","oe_lof_upper_rank","oe_lof_upper_bin") val df_loft_import = (spark.read .format("csv") .option("header", "true") ....
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Lets check that TranscriptID is not duplicated
df_loft.select($"TranscriptID").distinct.count df_loft.count df_loft.filter($"p".isNotNull && $"pLI" < 0.9). select("gnomadGeneSymbol","p","pLI","oe_lof_upper","oe_lof_upper_rank","oe_lof_upper_bin").sort($"pLI".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Join gnomAD lof table to RefSeq to Ensembl table
val df_loft_ref = (df_loft.as("df_loft") .join(df_ref2ens.as("df_ref2ens"), $"df_loft.TranscriptID" === $"df_ref2ens.TranscriptID", "inner") .drop($"df_ref2ens.TranscriptID"))
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Note that the number of rows has now increased from 80,950 to 95,806 - this is becuase ensemble transcripts can map to multiple RefSeq transcripts and vice versa. We now need to make a table where the RefSeq field is not duplicated.
df_loft_ref.groupBy($"RefSeq").count.sort($"count".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
For duplicate RefSeq's we will choose the value with the highest pLI value (i.e. most contrained) and where pLI is the same lowest oef rank (i.e. most constrained).
df_loft_ref.filter($"RefSeq" === "NM_206955" || $"RefSeq" === "NM_145021").show val df_high_pLI = df_loft_ref.groupBy($"RefSeq").agg(max($"pLI"), min($"oe_lof_upper_rank")) df_high_pLI.filter($"RefSeq" === "NM_206955" || $"RefSeq" === "NM_145021").show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Finally, create a table with unique RefSeq by joining to high pLI table
val df_loft_ref_uniq = ( df_loft_ref.join(df_high_pLI.as("pli"), df_loft_ref("RefSeq") === df_high_pLI("RefSeq") && df_loft_ref("pLI") === df_high_pLI("max(pLI)") && df_loft_ref("oe_lof_upper_r...
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Constrained genes are those with a pLi > 0.9
df_loft_ref_uniq.filter($"pLi" >= 0.9).groupBy($"oe_lof_upper_bin").count.sort($"count".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Probability that transcript falls into distribution of unconstrained genes
df_loft_ref_uniq.filter($"pNull" <= 0.05).groupBy($"oe_lof_upper_bin").count.sort($"count".desc).show df_loft_ref_uniq.filter($"pNull" > 0.05).groupBy($"oe_lof_upper_bin").count.sort($"count".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Probability that transcript falls into distribution of recessive genes (~46% o/e pLoF ratio; computed from gnomAD data)
df_loft_ref_uniq.filter($"pRec" <= 0.05).groupBy($"oe_lof_upper_bin").count.sort($"count".desc).show df_loft_ref_uniq.filter($"pRec" > 0.05).groupBy($"oe_lof_upper_bin").count.sort($"count".desc).show
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
Write out gnomAD pLI with RefSeq Metrics
(df_loft_ref_uniq.write.mode("overwrite") .parquet("s3://nch-igm-research-projects/rna_stability/peter/gnomAD_pLI_RefSeq.parquet"))
_____no_output_____
BSD-3-Clause
notebook/rnaStability_10.5.1_Step05_gnomAD_pLI.ipynb
nch-igm/rna-stability
练习 1:求n个随机整数均值的平方根,整数范围在m与k之间。
import random, math def test(): i = 0 total = 0 average = 0 number = random.randint(m, k) while i < n: i += 1 total += number number = random.randint(m, k) print('随机数是:', number) average = int(total/n) return math.sqrt(average) #主程序 m=i...
请输入一个整数下限:3 请输入一个整数上限:7 随机整数的个数是:2 随机数是: 4 随机数是: 5
MIT
chapter2/homework/localization/4-5/201611680168.ipynb
hpishacker/python_tutorial
练习 2:写函数,共n个随机整数,整数范围在m与k之间,(n,m,k由用户输入)。求1:西格玛log(随机整数),2:西格玛1/log(随机整数)
import random, math def test1(): i = 0 total = 0 number = random.randint(m,k) result = math.log10(number) while i < n: i += 1 number = random.randint(m,k) print('执行1的随机整数是:', number) result += math.log10(number) return result def t...
随机整数的个数是:2 请输入一个整数下限:1 请输入一个整数上限:100 执行1的随机整数是: 18 执行1的随机整数是: 46 执行1的结果是: 4.810124939475361 执行2的随机整数是: 49 执行2的随机整数是: 49 执行2的结果是: 1.6962756445012634
MIT
chapter2/homework/localization/4-5/201611680168.ipynb
hpishacker/python_tutorial
练习 3:写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘输入。
import random def test(): a = random.randint(1,9) print('随机整数a是:', a) i = 0 s = 0 number = 0 total = 0 while i < n: s = 10**i number += a * s total += number i += 1 return total #主程序 n = int(input('需要相加的个数是:')) print('结果是:', test())
需要相加的个数是:4 随机整数a是: 3 结果是: 3702
MIT
chapter2/homework/localization/4-5/201611680168.ipynb
hpishacker/python_tutorial
挑战性练习:仿照task5,将猜数游戏改成由用户随便选择一个整数,让计算机来猜测的猜数游戏,要求和task5中人猜测的方法类似,但是人机角色对换,由人来判断猜测是大、小还是相等,请写出完整的猜数游戏。
import random, math def win(): print( ''' ======YOU WIN======= ."". ."", | | / / | | / / | | / / | |/ ;-._ } ` _/ / ; | /` ) / / | / ...
=====游戏菜单===== 1. 游戏说明 2. 开始游戏 3. 退出游戏 4. 制作团队 =====游戏菜单===== 请输入你的选择1 游戏说明 玩家选择一个任意整数,计算机来猜测该数。 若计算机在规定次数内猜中该数,则计算机获胜。 若规定次数内没有猜中,则玩家获胜。 =====游戏菜单===== 1. 游戏说明 2. 开始游戏 ...
MIT
chapter2/homework/localization/4-5/201611680168.ipynb
hpishacker/python_tutorial
import tensorflow as tf import os import numpy as np from matplotlib import pyplot as plt %matplotlib inline if not os.path.isdir('models'): os.mkdir('models') print('Tensorflow Version:', tf.__version__) print('is using GPU?', tf.test.is_gpu_available()) def get_three_classess(x,y): indices_0, _ = np.where(y...
_____no_output_____
MIT
CNN_Keras_imageClassfier.ipynb
parthsaxena1909/Image-Classifer-using-CIFRA10
Locality Sensitive Hashing
import numpy as np import pandas as pd from scipy.sparse import csr_matrix from sklearn.metrics.pairwise import pairwise_distances import time from copy import copy import matplotlib.pyplot as plt %matplotlib inline '''compute norm of a sparse vector Thanks to: Jaiyam Sharma''' def norm(x): sum_sq=x.dot(x.T) ...
_____no_output_____
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Load in the Wikipedia dataset
wiki = pd.read_csv('people_wiki.csv') wiki.head()
_____no_output_____
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Extract TF-IDF matrix
def load_sparse_csr(filename): loader = np.load(filename) data = loader['data'] indices = loader['indices'] indptr = loader['indptr'] shape = loader['shape'] return csr_matrix((data, indices, indptr), shape) corpus = load_sparse_csr('people_wiki_tf_idf.npz') assert corpus.shape == (59071, 54797...
Check passed correctly!
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Train an LSH model
def generate_random_vectors(num_vector, dim): return np.random.randn(dim, num_vector) # Generate 3 random vectors of dimension 5, arranged into a single 5 x 3 matrix. np.random.seed(0) # set seed=0 for consistent results generate_random_vectors(num_vector=3, dim=5) # Generate 16 random vectors of dimension 547979 n...
Passed!
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Inspect bins
wiki[wiki['name'] == 'Barack Obama'] print(model['bin_indices'][35817]) wiki[wiki['name'] == 'Joe Biden'] print(np.array(model['bin_index_bits'][24478], dtype=int)) # list of 0/1's print(model['bin_indices'][24478]) # integer format sum(model['bin_index_bits'][24478] == model['bin_index_bits'][35817]) wiki[wiki['name']...
================= Cosine distance from Barack Obama Barack Obama - Joe Biden : 0.703139 Barack Obama - Mark Boulware : 0.950867 Barack Obama - John Wells (politician) : 0.975966 Barack Obama - Francis Longstaff : 0.978256 Barack Obama - Madurai T. Srinivasan : 0.993092
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Query the LSH model
from itertools import combinations num_vector = 16 search_radius = 3 for diff in combinations(range(num_vector), search_radius): print(diff) def search_nearby_bins(query_bin_bits, table, search_radius=2, initial_candidates=set()): """ For a given query vector and trained LSH model, return all candidate neig...
_____no_output_____
MIT
Machine_Learning_WashingTon/Clustering & Retrieval/week2 nearest neighbors & LSH implementation/Nearest Neighbors LSH Implementation.ipynb
PerpetualSmile/-Coursera
Read Data
path = '' dataTraining = pd.read_csv(os.path.join(path, 'data', 'dataTraining.csv'), encoding='UTF-8', index_col=0) dataTesting = pd.read_csv(os.path.join(path, 'data', 'dataTesting.csv'), encoding='UTF-8', index_col=0) dataTesting.head() dataTesting.head()
_____no_output_____
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass
Create count vectorizer with ngrams
vect = CountVectorizer(ngram_range=(1, 2), max_features=1000) X_dtm = vect.fit_transform(dataTraining['plot']) X_dtm.shape print(vect.get_feature_names()[:50])
['able', 'able to', 'about', 'about the', 'about to', 'accident', 'across', 'act', 'action', 'actually', 'affair', 'after', 'after the', 'again', 'against', 'against the', 'age', 'agent', 'ago', 'alex', 'alive', 'all', 'all of', 'all the', 'alone', 'along', 'along the', 'along with', 'already', 'also', 'although', 'alw...
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass
Create y
dataTraining['genres'] = dataTraining['genres'].map(lambda x: eval(x)) le = MultiLabelBinarizer() y_genres = le.fit_transform(dataTraining['genres'])
_____no_output_____
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass
Split train and test
X_train, X_test, y_train_genres, y_test_genres = train_test_split(X_dtm, y_genres, test_size=0.33, random_state=42)
_____no_output_____
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass