├── win32.png ├── TCPdump_Filters.pdf ├── Google_CheatSheet.pdf ├── Linux_CheatSheet.pdf ├── Netcat_CheatSheet.pdf ├── vi_vim_CheatSheet.gif ├── Nmap_CheatSheet_v1.1.pdf ├── Python2_CheatSheet.pdf ├── Python3_CheatSheet.pdf ├── Scapy_CheatSheet_v0.2.pdf ├── hping3_CheatSheet_v1.0.pdf ├── MISC_Tools_CheatSheet_v1.pdf ├── Metasploit_CheatSheet_2.0.pdf ├── PowerShell_CheatSheet_v41.pdf ├── SQLmap_CheatSheet-1.0-SDB.pdf ├── Wireshark_Display_Filters.pdf ├── Windows_Command_Line_CheatSheet_v1.pdf ├── X86_Win32_Reverse_Engineering_CheatSheet.pdf ├── PythonSnippets.md ├── Exploitation_CheatSheet.md ├── Privilege_Escalation.md ├── HTTP_Strict_Transport_Security_CheatSheet.md ├── AJAX_Security_CheatSheet.md ├── Regexp.md ├── Securing_Cascading_Style_Sheets_CheatSheet.md ├── PHP_Configuration_CheatSheet.md ├── Reverse-Engineering_Malware_CheatSheet.md ├── LDAP_Injection_Prevention_CheatSheet.md ├── Analyzing_Malicious_Documents.md ├── OS_Command_Injection_Defense_CheatSheet.md ├── TLS_Cipher_String_CheatSheet.md ├── Clickjacking_Defense_CheatSheet.md ├── Injection_Prevention_CheatSheet_in_Java.md ├── Injection_Prevention_CheatSheet.md ├── Mobile_App_Pen_Test.md ├── XML_External_Entity_Prevention_CheatSheet.md └── DotNet_Security_CheatSheet.md /win32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/win32.png -------------------------------------------------------------------------------- /TCPdump_Filters.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/TCPdump_Filters.pdf -------------------------------------------------------------------------------- /Google_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Google_CheatSheet.pdf -------------------------------------------------------------------------------- /Linux_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Linux_CheatSheet.pdf -------------------------------------------------------------------------------- /Netcat_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Netcat_CheatSheet.pdf -------------------------------------------------------------------------------- /vi_vim_CheatSheet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/vi_vim_CheatSheet.gif -------------------------------------------------------------------------------- /Nmap_CheatSheet_v1.1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Nmap_CheatSheet_v1.1.pdf -------------------------------------------------------------------------------- /Python2_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Python2_CheatSheet.pdf -------------------------------------------------------------------------------- /Python3_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Python3_CheatSheet.pdf -------------------------------------------------------------------------------- /Scapy_CheatSheet_v0.2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Scapy_CheatSheet_v0.2.pdf -------------------------------------------------------------------------------- /hping3_CheatSheet_v1.0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/hping3_CheatSheet_v1.0.pdf -------------------------------------------------------------------------------- /MISC_Tools_CheatSheet_v1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/MISC_Tools_CheatSheet_v1.pdf -------------------------------------------------------------------------------- /Metasploit_CheatSheet_2.0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Metasploit_CheatSheet_2.0.pdf -------------------------------------------------------------------------------- /PowerShell_CheatSheet_v41.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/PowerShell_CheatSheet_v41.pdf -------------------------------------------------------------------------------- /SQLmap_CheatSheet-1.0-SDB.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/SQLmap_CheatSheet-1.0-SDB.pdf -------------------------------------------------------------------------------- /Wireshark_Display_Filters.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Wireshark_Display_Filters.pdf -------------------------------------------------------------------------------- /Windows_Command_Line_CheatSheet_v1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/Windows_Command_Line_CheatSheet_v1.pdf -------------------------------------------------------------------------------- /X86_Win32_Reverse_Engineering_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberguideme/CheatSheets/HEAD/X86_Win32_Reverse_Engineering_CheatSheet.pdf -------------------------------------------------------------------------------- /PythonSnippets.md: -------------------------------------------------------------------------------- 1 | # Python Snippets 2 | 3 | ## File Operations 4 | 5 | * read a file line by line into a list 6 | 7 | * If you want the \n included: 8 | 9 | ```python 10 | with open(fname) as f: 11 | content = f.readlines() 12 | ``` 13 | 14 | * If you do not want \n included: 15 | 16 | ```python 17 | with open(fname) as f: 18 | content = f.read().splitlines() 19 | ``` 20 | 21 | * move file to the dist_dir folder 22 | 23 | os.rename(, dist_dir + os.path.sep + ) 24 | 25 | * get working directory 26 | 27 | PWD = os.getcwd() 28 | 29 | * write file 30 | 31 | RESOURCE = "filename.txt" 32 | fd = open(RESOURCE, 'w') 33 | fd.write("first line\n") 34 | fd.close() 35 | 36 | 37 | ## Parsing Arguments 38 | 39 | ```python 40 | parser = argparse.ArgumentParser() 41 | 42 | parser.add_argument("-p", dest="payload", help=payloads, required=True) 43 | parser.add_argument("-i", dest="interface", help="use interface - default: eth0", default="eth0") 44 | args = parser.parse_args() 45 | 46 | payload_type = args.payload 47 | ``` 48 | -------------------------------------------------------------------------------- /Exploitation_CheatSheet.md: -------------------------------------------------------------------------------- 1 | ## Exploitation 2 | * [Empire Cheat Sheet](https://github.com/HarmJ0y/CheatSheets/blob/master/Empire.pdf) - [Empire](http://www.powershellempire.com) is a PowerShell and Python post-exploitation framework 3 | * [Exploit Development Cheat Sheet](docs/pentest-exploit-dev-cheatsheet.jpg) - [@ovid](https://twitter.com/ovid)'s exploit development in one picture 4 | * [Java Deserialization Cheat Sheet](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet) - A cheat sheet for pentesters about Java Native Binary Deserialization vulnerabilities 5 | * [Local File Inclution (LFI) Cheat Sheet #1](https://highon.coffee/blog/lfi-cheat-sheet/) - Arr0way's LFI Cheat Sheet 6 | * [Local File Inclution (LFI) Cheat Sheet #2](https://www.aptive.co.uk/blog/local-file-inclusion-lfi-testing/) - Aptive's LFI Cheat Sheet 7 | * [Metasploit Unleashed](https://www.offensive-security.com/metasploit-unleashed/) - The ultimate guide to the Metasploit Framework 8 | * [Metasploit Cheat Sheet](https://www.tunnelsup.com/metasploit-cheat-sheet/) - A quick reference guide [(PNG version)](docs/Metasploit-CheatSheet.png)[(PDF version)](docs/Metasploit-CheatSheet.pdf) 9 | * [PowerSploit Cheat Sheet](https://github.com/HarmJ0y/CheatSheets/blob/master/PowerSploit.pdf) - [PowerSploit](https://github.com/PowerShellMafia/PowerSploit) is a powershell post-exploitation framework 10 | * [PowerView 2.0 Tricks](https://gist.github.com/HarmJ0y/3328d954607d71362e3c) 11 | * [PowerView 3.0 Tricks](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993) 12 | * [PHP htaccess Injection Cheat Sheet](https://github.com/sektioneins/pcc/wiki/PHP-htaccess-injection-cheat-sheet) - htaccess Injection Cheat Sheet by PHP Secure Configuration Checker 13 | * [Reverse Shell Cheat Sheet #1](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) - Pentestmonkey Reverse Shell Cheat Sheet 14 | * [Reverse Shell Cheat Sheet #2](https://highon.coffee/blog/reverse-shell-cheat-sheet) - Arr0way's Reverse Shell Cheat Sheet 15 | * [SQL Injection Cheat Sheet](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet) - Netsparker's SQL Injection Cheat Sheet 16 | * [SQLite3 Injection Cheat Sheet](http://atta.cked.me/home/sqlite3injectioncheatsheet) 17 | -------------------------------------------------------------------------------- /Privilege_Escalation.md: -------------------------------------------------------------------------------- 1 | # Privilege Escalation 2 | 3 | ### Learn Privilege Escalation 4 | 5 | * [Windows / Linux Local Privilege Escalation Workshop](https://github.com/sagishahar/lpeworkshop) - The Privilege Escalation Workshop covers all known (at the time) attack vectors of local user privilege escalation on both Linux and Windows operating systems and includes slides, videos, test VMs. 6 | 7 | 8 | ### Linux Privilege Escalation 9 | 10 | * [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) - Linux Privilege Escalation by [@g0tmi1k](https://twitter.com/g0tmi1k) 11 | * [linux-exploit-suggester.sh](https://github.com/mzet-/linux-exploit-suggester) - Linux privilege escalation auditing tool written in bash (updated) 12 | * [Linux_Exploit_Suggester.pl](https://github.com/PenturaLabs/Linux_Exploit_Suggester) - Linux Exploit Suggester written in Perl (last update 3 years ago) 13 | * [Linux_Exploit_Suggester.pl v2](https://github.com/jondonas/linux-exploit-suggester-2) - Next-generation exploit suggester based on Linux_Exploit_Suggester (updated) 14 | * [Linux Soft Exploit Suggester](https://github.com/belane/linux-soft-exploit-suggester) - linux-soft-exploit-suggester finds exploits for all vulnerable software in a system helping with the privilege escalation. It focuses on software packages instead of Kernel vulnerabilities 15 | * [checksec.sh](https://github.com/slimm609/checksec.sh) - bash script to check the properties of executables (like PIE, RELRO, PaX, Canaries, ASLR, Fortify Source) 16 | * [linuxprivchecker.py](http://www.securitysift.com/download/linuxprivchecker.py) - This script is intended to be executed locally on a Linux box to enumerate basic system info and search for common privilege escalation vectors such as world writable files, misconfigurations, clear-text passwords and applicable exploits (@SecuritySift) 17 | * [LinEnum](https://github.com/rebootuser/LinEnum) - This tool is great at running through a heap of things you should check on a Linux system in the post exploit process. This include file permissions, cron jobs if visible, weak credentials etc.(@Rebootuser) 18 | 19 | 20 | ### Windows Privilege Escalation 21 | 22 | * [PowerUp](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc) - Excellent powershell script for checking of common Windows privilege escalation vectors. Written by [harmj0y](https://twitter.com/harmj0y) [(direct link)](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1) 23 | * [PowerUp Cheat Sheet](https://github.com/HarmJ0y/CheatSheets/blob/master/PowerUp.pdf) 24 | * [Windows Exploit Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester) - Tool for detection of missing security patches on the windows operating system and mapping with the public available exploits 25 | * [Sherlock](https://github.com/rasta-mouse/Sherlock) - PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities 26 | * [Precompiled Windows Exploits](https://github.com/abatchy17/WindowsExploits) - Collection of precompiled Windows exploits 27 | * [Metasploit Modules](https://github.com/rapid7/metasploit-framework) 28 | * post/multi/recon/local_exploit_suggester - suggests local meterpreter exploits that can be used 29 | * post/windows/gather/enum_patches - helps to identify any missing patches 30 | -------------------------------------------------------------------------------- /HTTP_Strict_Transport_Security_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | HTTP [Strict Transport Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) (also named **HSTS**) is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS. It also prevents HTTPS click through prompts on browsers. 4 | 5 | The specification has been released and published end of 2012 as [RFC 6797](http://tools.ietf.org/html/rfc6797) (HTTP Strict Transport Security (HSTS)) by the IETF. 6 | 7 | # Threats 8 | 9 | HSTS addresses the following threats: 10 | 11 | - User bookmarks or manually types `http://example.com` and is subject to a man-in-the-middle attacker 12 | - HSTS automatically redirects HTTP requests to HTTPS for the target domain 13 | - Web application that is intended to be purely HTTPS inadvertently contains HTTP links or serves content over HTTP 14 | - HSTS automatically redirects HTTP requests to HTTPS for the target domain 15 | - A man-in-the-middle attacker attempts to intercept traffic from a victim user using an invalid certificate and hopes the user will accept the bad certificate 16 | - HSTS does not allow a user to override the invalid certificate message 17 | 18 | # Examples 19 | 20 | Simple example, using a long (1 year = 31536000 seconds) max-age. This example is dangerous since it lacks `includeSubDomains`: 21 | 22 | `Strict-Transport-Security: max-age=31536000` 23 | 24 | This example is useful if all present and future subdomains will be HTTPS. This is a more secure option but will block access to certain pages that can only be served over HTTP: 25 | 26 | `Strict-Transport-Security: max-age=31536000; includeSubDomains` 27 | 28 | This example is useful if all present and future subdomains will be HTTPS. In this example we set a very short max-age in case of mistakes during initial rollout: 29 | 30 | `Strict-Transport-Security: max-age=86400; includeSubDomains` 31 | 32 | **Recommended:** 33 | - If the site owner would like their domain to be included in the [HSTS preload list](https://hstspreload.appspot.com/) maintained by Chrome (and used by Firefox and Safari), then use the header below. 34 | - Sending the `preload` directive from your site can have **PERMANENT CONSEQUENCES** and prevent users from accessing your site and any of its subdomains if you find you need to switch back to HTTP. Please read the details at [preload removal](https://hstspreload.org/#removal) before sending the header with `preload`. 35 | 36 | `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` 37 | 38 | The `preload` flag indicates the site owner's consent to have their domain preloaded. The site owner still needs to then go and submit the domain to the list. 39 | 40 | # Problems 41 | 42 | Site owners can use HSTS to identify users without cookies. This can lead to a significant privacy leak. Take a look [here](http://www.leviathansecurity.com/blog/the-double-edged-sword-of-hsts-persistence-and-privacy) for more details. 43 | 44 | Cookies can be manipulated from sub-domains, so omitting the `includeSubDomains` option permits a broad range of cookie-related attacks that HSTS would otherwise prevent by requiring a valid certificate for a subdomain. Ensuring the `secure` flag is set on all cookies will also prevent, some, but not all, of the same attacks. 45 | 46 | # Browser Support 47 | 48 | See the browsers support matrix [here](https://caniuse.com/#feat=stricttransportsecurity). 49 | 50 | There is also a [TLS Browser Test Page](https://badssl.com/) to check whether your current browser supports HSTS. 51 | 52 | # References 53 | 54 | - [Chromium Projects/HSTS](http://dev.chromium.org/sts) 55 | - [OWASP TLS Protection Cheat Sheet](Transport_Layer_Protection_Cheat_Sheet.md) 56 | - [Moxie Marlinspike's Black Hat 2009 talk on sslstrip, that demonstrates why you need HSTS](https://moxie.org/software/sslstrip/) 57 | - [AppSecTutorial Series - Episode 4](https://www.youtube.com/watch?v=zEV3HOuM_Vw) 58 | - [Nmap NSE script to detect HSTS configuration](https://github.com/icarot/NSE_scripts/blob/master/http-hsts-verify.nse) 59 | 60 | # Authors and Primary Editors 61 | 62 | Til Maas 63 | 64 | Jim Manico 65 | 66 | Pawel Krawczyk 67 | 68 | Daniel Black 69 | 70 | Michael Coates 71 | -------------------------------------------------------------------------------- /AJAX_Security_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This document will provide a starting point for AJAX security and will hopefully be updated and expanded reasonably often to provide more detailed information about specific frameworks and technologies. 4 | 5 | ## Client Side (Javascript) 6 | 7 | ### Use .innerText instead of .innerHtml 8 | 9 | The use of `.innerText` will prevent most XSS problems as it will automatically encode the text. 10 | 11 | ### Don't use eval 12 | 13 | `eval()` function is evil, never use it. Needing to use eval usually indicates a problem in your design. 14 | 15 | ### Canonicalize data to consumer (read: encode before use) 16 | 17 | When using data to build HTML, script, CSS, XML, JSON, etc. make sure you take into account how that data must be presented in a literal sense to keep it's logical meaning. 18 | 19 | Data should be properly encoded before used in this manner to prevent injection style issues, and to make sure the logical meaning is preserved. 20 | 21 | [Check out the OWASP Java Encoder Project.](https://www.owasp.org/index.php/OWASP_Java_Encoder_Project) 22 | 23 | ### Don't rely on client logic for security 24 | 25 | Least ye have forgotten the user controls the client side logic. I can use a number of browser plugging to set breakpoints, skip code, change values, etc. Never rely on client logic. 26 | 27 | ### Don't rely on client business logic 28 | 29 | Just like the security one, make sure any interesting business rules/logic is duplicated on the server side less a user bypass needed logic and do something silly, or worse, costly. 30 | 31 | ### Avoid writing serialization code 32 | 33 | This is hard and even a small mistake can cause large security issues. There are already a lot of frameworks to provide this functionality. 34 | 35 | Take a look at the [JSON page](http://www.json.org/) for links. 36 | 37 | ### Avoid building XML or JSON dynamically 38 | 39 | Just like building HTML or SQL you will cause XML injection bugs, so stay way from this or at least use an encoding library or safe JSON or XML library to make attributes and element data safe. 40 | 41 | - [XSS (Cross Site Scripting) Prevention](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) 42 | - [SQL Injection Prevention](SQL_Injection_Prevention_Cheat_Sheet.md) 43 | 44 | ### Never transmit secrets to the client 45 | 46 | Anything the client knows the user will also know, so keep all that secret stuff on the server please. 47 | 48 | ### Don't perform encryption in client side code 49 | 50 | Use TLS/SSL and encrypt on the server! 51 | 52 | ### Don't perform security impacting logic on client side 53 | 54 | This is the overall one that gets me out of trouble in case I missed something :) 55 | 56 | ## Server Side 57 | 58 | ### Use CSRF Protection 59 | 60 | Take a look at the [Cross-Site Request Forgery (CSRF) Prevention](Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md) cheat sheet. 61 | 62 | ### Protect against JSON Hijacking for Older Browsers 63 | 64 | #### Review AngularJS JSON Hijacking Defense Mechanism 65 | 66 | See the [JSON Vulnerability Protection](https://docs.angularjs.org/api/ng/service/$http) section of the AngularJS documentation. 67 | 68 | #### Always return JSON with an Object on the outside 69 | 70 | Always have the outside primitive be an object for JSON strings: 71 | 72 | **Exploitable:** 73 | 74 | ```json 75 | [{"object": "inside an array"}] 76 | ``` 77 | 78 | **Not exploitable:** 79 | 80 | ```json 81 | {"object": "not inside an array"} 82 | ``` 83 | 84 | **Also not exploitable:** 85 | 86 | ```json 87 | {"result": [{"object": "inside an array"}]} 88 | ``` 89 | 90 | ### Avoid writing serialization code. Remember ref vs. value types! 91 | 92 | Look for an existing library that has been reviewed. 93 | 94 | ### Services can be called by users directly 95 | 96 | Even though you only expect your AJAX client side code to call those services the users can too. 97 | 98 | Make sure you validate inputs and treat them like they are under user control (because they are!). 99 | 100 | ### Avoid building XML or JSON by hand, use the framework 101 | 102 | Use the framework and be safe, do it by hand and have security issues. 103 | 104 | ### Use JSON And XML Schema for Webservices 105 | 106 | You need to use a 3rd party library to validate web services. 107 | 108 | # Authors and Primary Editors 109 | 110 | Til Mas 111 | 112 | Michael Eddington 113 | -------------------------------------------------------------------------------- /Regexp.md: -------------------------------------------------------------------------------- 1 | # Regexp Security Cheatsheet 2 | 3 | Research was done to find "weak places" in regular expressions of Web Application Firewalls (WAFs). 4 | Repository contains SAST, which can help you to find security vulnerabilities in custom regular expressions in own projects. 5 | Contribution is highly welcomed. 6 | 7 | ### High severity issues: 8 | |#| Requirement | Vulnerable regex example | Bypass example | 9 | |---|---|---|---| 10 | |1| Regexp should avoid using `^` (alternative: `\A`) and `$` (alternative: `\Z`) symbols, which are metacharacters for start and end of a string. It is possible to bypass regex by inserting any symbol in front or after regexp. | `(^a\|a$)` | `%20a%20` 11 | |2| Regexp should be case-insensitive: `(?i:` or `/regex/i`. It is possible to bypass regex using upper or lower cases in words. [Modsecurity transformation commands](https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#cmdLine) (which are applied on string before regex pattern is applied) can also be included in tests to cover more regexps. | `http` | `hTtP` 12 | |3| In case modifier `/m` is not (globally) specified, regexp should avoid using dot `.` symbol, which means every symbol except newline (`\n`). It is possible to bypass regex using [newline injection](https://www.htbridge.com/blog/bypassing-bitrix-web-application-firewall-via-tiny-regexp-error.html). | `a.*b` | `a%0Ab` 13 | |4| Regexp should not be vulnerable to ReDoS. [OWASP ReDoS article](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) 1. Find various evil patterns. 2. Generate evil string using e.g. “SDL Regex Fuzzer” | `(a+)+` | `aaaaaaaaaaaaaaaaaaaa!` 14 | |5| Number of repetitions of set or group `{}` should be carefully used, as one can bypass such limitation by lowering or increasing specified numbers. | `a{1,5}` | `aaaaaa (6 times)` 15 | |6| Nonstandard ranges (almost everything except a-z, 0-9, a-f, etc) | ``[A-z] = [a-zA-Z] + [\]^_` `` | ``aaa[\]^_`aaa`` 16 | |7| Regexp should only use plus “`+`” metacharacter in places where it is necessary, as it means “one or more”. Alternative metacharacter star “`*`”, which means “zero or more” is generally preferred. | `a'\s+\d` | `a'5` 17 | |8| Usage of newline wildcards should be reasonable. `\r\n` characters can often be bypassed by either substitution, or by using newline alternative `\v`, `\f` and others. Wildcard `\b` has different meanings while using it in square brackets (“backspace”) and in plain regex (“word boundary”) - [RegexLib](http://regexlib.com/CheatSheet.aspx) | `a[^\n]*$` | `a\n`? `a\r`? 18 | |9| Regexp should be applied to right scope of inputs: `Cookies names and values`, `Argument names and values`, `Header names and values`, `Files argument names and content`. Modsecurity: `grep -oP 'SecRule(.*?)"' -n` Other WAFs: manual observation. | Argument values | Cookie names and values 19 | |10| Regular expression writers should be careful while using only whitespace character (`%20`) as separators. Rule can be bypassed e.g. with newline character, tabulation, by skipping whitespace, or alternatives. | `a\s(not[whitespace]\|and)\sb` | `a not b` 20 | |11| Nonstandard combinations of operators | `a\|\|b` | `any_string` 21 | |12| Special cases: whitespaces before operators | `(a \|b)c` | `ac` 22 | |13| Usage of wrong syntax in POSIX character classes | `a[digit]b` | `aab` 23 | |14| Opposite usage of brackets [], () and {} | `[SYSTEM\|PUBLIC]` or `(a-z123)` | `SYSTEM` or `abcdef` 24 | 25 | ### Medium severity issues (non-expected behaviour: manual observation needed): 26 | |#| Requirement | Vulnerable regex example | Bypass example | 27 | |---|---|---|---| 28 | |15| Check backlinks, and bear in mind that [`\11` can be backlink -OR- 0x09](http://php.net/manual/en/regexp.reference.escape.php) | `(\d{1})=\1` | `1!=2` 29 | |16| Unsafe usage of comments | `a(?#some comment about wildcards:\)(\w*)b` | `afffb` 30 | |17| Excessive usage of metacharacters in [] | `[\w+]` | ` ` 31 | |18| Rarely used [wildcards](http://php.net/manual/en/regexp.reference.escape.php). All wildcards except popular: A,Z,b,r,n,t,wW,sS,dD,u,x | `\a = 0x07; \e = 0x1B; \R = \r\|\n\|\r\n; \xXX = 0xXX; \ddd = 0oddd; \cX, \x{XXXX}, \H, \V, \G` | ` ` 32 | |19| Excessive escaping, e.g. escaping symbol which is not a wildcard | `\q` | ` ` 33 | |20| Unsafe usage of [recursion](http://php.net/manual/ru/regexp.reference.recursive.php), IF statements, etc | `(?R`, `(?(id)true\|false)`, ... | ` ` 34 | |21| Unsafe usage of ranges | `[\0-9]` = `\0\1\2\3...$%&'...789` | ` ` 35 | 36 | ##### Experimental rules (probably to be removed): 37 | |#| Requirement | Vulnerable regex example | Bypass example | 38 | |---|---|---|---| 39 | |X| Greediness of regular expressions should be considered. Highlight of this topic is well done in [Chapter 9 of Jan Goyvaert’s tutorial](https://www.princeton.edu/~mlovett/reference/Regular-Expressions.pdf). While greediness itself does not create bypasses, bad implementation of regexp Greediness can raise False Positive rate. This can cause excessive log-file flooding, forcing vulnerable rule or even whole WAF to be switched off. | | 40 | |X| Best Practice from [slides of Ivan Novikov](http://www.slideshare.net/d0znpp/lie-tomephd2013): Modsecurity should avoid using t:base64Decode function (t:base64DecodeExt instead). | `t:base64Decode` | `detected=bypassed` 41 | 42 | Vladimir Ivanov 43 | @httpsonly 44 | -------------------------------------------------------------------------------- /Securing_Cascading_Style_Sheets_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | The goal of this `CSS` (Not [XSS](Cross_Site_Scripting_Prevention_Cheat_Sheet.md), but [Cascading Style Sheet](https://www.w3schools.com/css/css_intro.asp)) Cheat Sheet is to inform Programmers, Testers, Security Analysts, Front-End Developers and anyone who is interested in Web Application Security to use these recommendations or requirements in order to achieve better security when authoring `Cascading Style Sheets`. 4 | 5 | Let's demonstrate this risk with an example: 6 | 7 | Santhosh is a programmer who works for a company called **X** and authors a Cascading Style Sheet to implement styling of the web application. The application for which he is writing CSS Code has various roles like **Student**, **Teacher**, **Super User** & **Administrator** and these roles have different permissions (PBAC - [Permission Based Access Control](Access_Control_Cheat_Sheet.md)) and Roles (RBAC - [Role Based Access Control](Access_Control_Cheat_Sheet.md)). Not only do these roles have different access controls, but these roles could also have different styling for webpages that might be specific to an individual or group of roles. 8 | 9 | Santhosh thinks that it would a great optimized idea to create a “global styling” css file which has all the CSS styling/selectors for all of the roles. According to their role, a specific feature or user interface element will be rendered. For instance, Administrator will have different features compared to **Student** or **Teacher** or **SuperUser**. However, some permissions or features maybe common to some roles. 10 | 11 | Example: Profile Settings will be applicable to all the users here while *Adding Users* or *Deleting Users* is only applicable for **Administrator**. 12 | 13 | Example: 14 | 15 | - `.login` 16 | - `.profileStudent` 17 | - `.changePassword` 18 | - `.addUsers` 19 | - `.deleteUsers` 20 | - `.addNewAdmin` 21 | - `.deleteAdmin` 22 | - `.exportUserData` 23 | - `.exportProfileData` 24 | - ... 25 | 26 | Now, let’s examine what are the risks associated with this style of coding. 27 | 28 | ## Risk \#1 29 | 30 | Motivated Attackers always take a look at `*.CSS` files to learn the features of the application even without being logged in. 31 | 32 | For instance: Jim is a motivated attacker and always tries to look into CSS files from the View-Source even before other attacks. When Jim looks into the CSS file, he sees that there are different features and different roles based on the CSS selectors like `.profileSettings,` `.editUser,` `.addUser,` `.deleteUser` and so on. Jim can use the CSS for intel gathering to help gain access to sensitive roles.This isa form of attacker due diligence even before trying to perform dangerous attacks to gain access to the web application. 33 | 34 | In a nutshell, having global styling could reveal sensitive information that could be beneficial to the attacker. 35 | 36 | ## Risk \#2 37 | 38 | Let’s say, Santhosh has this habit of writing the descriptive selector names like `.profileSettings,` `exportUserData,` `.changePassword,` `.oldPassword,` `.newPassword,` `.confirmNewPassword` etc. Good programmers like to keep code readable and usable by other Code Reviewers of the team. The risk is that attackers could map these selectors to actual features of a web application. 39 | 40 | # Defensive Mechanisms to Mitigate Attacker’s Motivation 41 | 42 | ## Defense Mechanism 43 | 44 | As a CSS Coder / Programmer, always keep the CSS isolated by access control level. By this, it means **Student** will have a different CSS file called as `StudentStyling.CSS` while **Administrator** has `AdministratorStyling.CSS` and so on. Make sure these `*.CSS` files are accessed only for a user with the proper access control level. Only users with the proper access control level should be able to access their `*.CSS` file. 45 | 46 | If an authenticated user with the **Student** Role tries to access `AdministratorStyling.CSS` through forced browsing, an alert that an intrusion is occurring should be recorded. 47 | 48 | ## Defense Mechanism \#2 49 | 50 | Being a programmer or a tester, take care of the naming conventions of your CSS (Cascading Style Sheet) Selectors. Obfuscate the selector names in such a fashion that attackers are not informed what a specific selector is linking to. 51 | 52 | Example: CSS Selectors for `addUser,` `addAdmin,` `profileSettings,` `changePassword` could be named `aHj879JK,` `bHjsU,` `ahkrrE,` `lOiksn` respectively. These names could be randomly generated per user as well. 53 | 54 | This [NPM package](https://www.npmjs.com/package/rename-css-selectors) can be used to perform the renaming of the CSS selector. 55 | 56 | ## Defense Mechanism \#3 57 | 58 | Web applications that allow users to author content via HTML input could be vulnerable to malicious use of CSS. Uploaded HTML could use styles that are allowed by the web application but could be used for purposes other than intended which could lead to security risks. 59 | 60 | Example: You can read about how [LinkedIn](https://www.scmagazineuk.com/style-sheet-vulnerability-allowed-attacker-hijack-linkedin-pages/article/1479529) had a vulnerability which allowed malicious use of CSS that lead to the authoring of a page where the entire page was clickable including overwriting LinkedIn's standard navigation elements. 61 | 62 | # Authors and Primary Editors 63 | 64 | [Santhosh Tuppad](https://twitter.com/santhoshst) 65 | -------------------------------------------------------------------------------- /PHP_Configuration_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This page is meant to help those configuring PHP and the web server it is running on to be very secure. 4 | 5 | Below you will find information on the proper settings for the `php.ini` file and instructions on configuring Apache, Nginx, and Caddy web servers. 6 | 7 | For general PHP codebase security please refer to the two following great guides: 8 | - [Paragonie's 2018 PHP Security Guide](https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software) 9 | - [Awesome PHP Security](https://github.com/guardrailsio/awesome-php-security) 10 | 11 | # Web Server Configuration 12 | 13 | ## Apache 14 | 15 | [suPHP](http://suphp.org/) makes every php script run as its file owner. This way you are allowed to upload and modify files in your folders without needing to `chmod 777` any folder, which is very bad security practice and will let to your files be compromised easily. Install and configure it on your web server. 16 | 17 | ## NGINX 18 | 19 | TODO 20 | 21 | ## CADDY 22 | 23 | TODO 24 | 25 | # PHP Configuration and Deployment 26 | 27 | ## Suhosin 28 | 29 | Consider using [Suhosin](http://www.hardened-php.net/suhosin/index.html) if you want to patch many custom security flaws in various parts of PHP. 30 | 31 | ## php.ini 32 | 33 | Some of following settings need to be adapted to your system, in particular `session.save_path`, `session.cookie_path` (e.g. `/var/www/mysite`), and `session.cookie_domain` (e.g. `ExampleSite.com`). 34 | 35 | You should also be runninng PHP 7.2 or later. If running PHP 7.0 and 7.1, you will use slightly different values in a couple of places below (see inline comments). Finally look through the [PHP Manual](http://www.php.net/manual/ini.core.php) for a complete reference on every value in the php.ini configuration file. 36 | 37 | You can find a copy of the following values in a ready-to-go php.ini file [here](https://github.com/danehrlich1/very-secure-php-ini). 38 | 39 | #### PHP error handling 40 | 41 | ```text 42 | expose_php = Off 43 | error_reporting = E_ALL 44 | display_errors = Off 45 | display_startup_errors = Off 46 | log_errors = On 47 | error_log = /valid_path/PHP-logs/php_error.log 48 | ignore_repeated_errors = Off 49 | ``` 50 | 51 | Keep in mind that you need to have `display_errors` to `Off` on a production server and it's a good idea to frequently notice the logs. 52 | 53 | #### PHP general settings 54 | 55 | ```text 56 | doc_root = /path/DocumentRoot/PHP-scripts/ 57 | open_basedir = /path/DocumentRoot/PHP-scripts/ 58 | include_path = /path/PHP-pear/ 59 | extension_dir = /path/PHP-extensions/ 60 | mime_magic.magicfile = /path/PHP-magic.mime 61 | allow_url_fopen = Off 62 | allow_url_include = Off 63 | variables_order = "GPCS" 64 | allow_webdav_methods = Off 65 | session.gc_maxlifetime = 600 66 | ``` 67 | 68 | `allow_url_*` prevents [LFI](https://www.acunetix.com/blog/articles/local-file-inclusion-lfi/)s to be easily escalated to [RFI](https://www.acunetix.com/blog/articles/remote-file-inclusion-rfi/)s. 69 | 70 | #### PHP file upload handling 71 | 72 | ```text 73 | file_uploads = On 74 | upload_tmp_dir = /path/PHP-uploads/ 75 | upload_max_filesize = 2M 76 | max_file_uploads = 2 77 | ``` 78 | 79 | If your application is not using file uploads, and say the only data the user will enter / upload is forms that do not require any document attachments, `file_uploads` should be turned `Off`. 80 | 81 | #### PHP executable handling 82 | 83 | ```text 84 | enable_dl = Off 85 | disable_functions = system, exec, shell_exec, passthru, phpinfo, show_source, popen, proc_open 86 | disable_functions = fopen_with_path, dbmopen, dbase_open, putenv, move_uploaded_file 87 | disable_functions = chdir, mkdir, rmdir, chmod, rename 88 | disable_functions = filepro, filepro_rowcount, filepro_retrieve, posix_mkfifo 89 | # see also: http://ir.php.net/features.safe-mode 90 | disable_classes = 91 | ``` 92 | 93 | These are dangerous PHP functions. You should disable all that you don't use. 94 | 95 | #### PHP session handling 96 | 97 | Session settings are some of the MOST important values to concentrate on in configuring. It is a good practice to change `session.name` to something new. 98 | 99 | ```text 100 | session.save_path = /path/PHP-session/ 101 | session.name = myPHPSESSID 102 | session.auto_start = Off 103 | session.use_trans_sid = 0 104 | session.cookie_domain = full.qualified.domain.name 105 | #session.cookie_path = /application/path/ 106 | session.use_strict_mode = 1 107 | session.use_cookies = 1 108 | session.use_only_cookies = 1 109 | session.cookie_lifetime = 864000 # 4 hours 110 | session.cookie_secure = 1 111 | session.cookie_httponly = 1 112 | session.cookie_samesite = Strict 113 | session.cache_expire = 30 114 | session.sid_length = 256 115 | session.sid_bits_per_character = 6 # PHP 7.2+ 116 | session.hash_function = 1 # PHP 7.0-7.1 117 | session.hash_bits_per_character = 6 # PHP 7.0-7.1 118 | ``` 119 | 120 | #### Some more security paranoid checks 121 | 122 | ```text 123 | session.referer_check = /application/path 124 | memory_limit = 50M 125 | post_max_size = 20M 126 | max_execution_time = 60 127 | report_memleaks = On 128 | track_errors = Off 129 | html_errors = Off 130 | ``` 131 | 132 | # Authors and Primary Editors 133 | 134 | Achim Hoffmann - Achim@owasp.org 135 | 136 | Tony Hsu HsiangChih 137 | 138 | Abbas Naderi - abbas.naderi@owasp.org 139 | 140 | Dan Ehrlich - dan.ehrlich@owasp.org 141 | -------------------------------------------------------------------------------- /Reverse-Engineering_Malware_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Reverse-Engineering Malware Cheat Sheet 2 | 3 | This is a cheat sheet of shortcuts and tips for reverse-engineering malware. It covers the general malware analysis process, as well as useful tips for OllyDbg, IDA Pro, and other tools. Feel free to customize it to your own needs. My [reverse-engineering malware course](http://zeltser.com/reverse-malware/) explores these, and other useful techniques. 4 | 5 | ## General Approach 6 | 7 | 1. Set up a controlled, isolated laboratory in which to examine the malware specimen. 8 | 2. Perform behavioral analysis to examine the specimen’s interactions with its environment. 9 | 3. Perform static code analysis to further understand the specimen’s inner-workings. 10 | 4. Perform dynamic code analysis to understand the more difficult aspects of the code. 11 | 5. If necessary, unpack the specimen. 12 | 6. Repeat steps 2, 3, and 4 (order may vary) until sufficient analysis objectives are met. 13 | 7. Document findings and clean-up the laboratory for future analysis. 14 | 15 | ## Behavioral Analysis 16 | 17 | Be ready to revert to good state via [dd](http://en.wikipedia.org/wiki/Dd_(Unix)), [VMware](http://www.vmware.com/) snapshots, [CoreRestore](http://www.corerestore.com/), [Ghost](http://www.symantec.com/norton/ghost), [SteadyState](http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx), etc. 18 | 19 | Monitor local ([Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx)) and network ([Wireshark](http://www.wireshark.org/), [tcpdump](http://www.tcpdump.org/)) interactions. 20 | 21 | Detect major local changes ([RegShot](https://sourceforge.net/projects/regshot), [Autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902.aspx)). 22 | 23 | Redirect network traffic (hosts file, DNS, [Honeyd](http://www.honeyd.org/)). 24 | 25 | Activate services (IRC, HTTP, SMTP, etc.) as needed to evoke new behavior from the specimen. 26 | 27 | ## [IDA Pro](http://www.hex-rays.com/idapro/) for Static Code Analysis 28 | 29 | Text search; "Alt+T" 30 | 31 | Show strings window; "Shift+F12" 32 | 33 | Show operand as hex value; "Q" 34 | 35 | Insert comment; ":" 36 | 37 | Follow jump or call in view; "Enter" 38 | 39 | Return to previous view; "Esc" 40 | 41 | Go to next view; "Ctrl+Enter" 42 | 43 | Show names window; "Shift+F4" 44 | 45 | Display function's flow chart; "F12" 46 | 47 | Display graph of function calls; "Ctrl+F12" 48 | 49 | Go to program's entry point; "Ctrl+E" 50 | 51 | Go to specific address; "G" 52 | 53 | Rename a variable or function; "N" 54 | 55 | Show listing of names; "Ctrl+L" 56 | 57 | Display listing of segments; "Ctrl+S" 58 | 59 | Show cross-references to selected function; "Select function name » Ctrl+X" 60 | 61 | Show stack of current function; "Ctrl+K" 62 | 63 | ## [OllyDbg](http://www.ollydbg.de/) for Dynamic Code Analysis 64 | 65 | Step into instruction; "F7" 66 | 67 | Step over instruction; "F8" 68 | 69 | Execute till next breakpoint; "F9" 70 | 71 | Execute till next return; "Ctrl+F9" 72 | 73 | Show previous executed instruction; "-" 74 | 75 | Show next executed instruction; "+" 76 | 77 | Return to previous view; "*" 78 | 79 | Show memory map; "Alt+M" 80 | 81 | Follow expression in view; "Ctrl+G" 82 | 83 | Insert comment; ";" 84 | 85 | Follow jump or call in view; "Enter" 86 | 87 | Show listing of names; "Ctrl+N" 88 | 89 | New binary search; "Ctrl+B" 90 | 91 | Next binary search result; "Ctrl+L" 92 | 93 | Show listing of software breakpoints; "Alt+B" 94 | 95 | Assemble instruction in place of selected one; "Select instruction » Spacebar" 96 | 97 | Edit data in memory or instruction opcode; "Select data or instruction » Ctrl+E" 98 | 99 | Show SEH chain; "View » SEH chain" 100 | 101 | Show patches; "Ctrl+P" 102 | 103 | ## Bypassing Malware Defenses 104 | 105 | To try unpacking quickly, infect the system and dump from memory via LordPE or OllyDump. 106 | 107 | For more surgical unpacking, locate the Original Entry Point (OEP) after the unpacker executes. 108 | 109 | If cannot unpack cleanly, examine the packed specimen via dynamic code analysis while it runs. 110 | 111 | When unpacking in OllyDbg, try SFX (bytewise) and OllyDump's "Find OEP by Section Hop". 112 | 113 | Conceal OllyDbg via HideOD and OllyAdvanced. 114 | 115 | A JMP or CALL to EAX may indicate the OEP, possibly preceded by POPA or POPAD. 116 | 117 | Look out for tricky jumps via SEH, RET, CALL, etc. 118 | 119 | If the packer uses SEH, anticipate OEP by tracking stack areas used to store the packers' handlers. 120 | 121 | Decode protected data by examining results of the decoding function via dynamic code analysis. 122 | 123 | Correct PE header problems with XPELister, LordPE, [ImpREC](http://www.woodmann.com/collaborative/tools/index.php/ImpREC), [PEiD](http://peid.has.it/), etc. 124 | 125 | To get closer to OEP, try breaking on unpacker’s calls to LoadLibraryA or GetProcAddress. 126 | 127 | ## Common x86 Registers and Uses 128 | 129 | EAX; Addition, multiplication, function results 130 | 131 | ECX; Counter 132 | 133 | EBP; Base for referencing function arguments (EBP+value) and local variables (EBP-value) 134 | 135 | ESP; Points to the current "top" of the stack; changes via PUSH, POP, and others 136 | 137 | EIP; Points to the next instruction 138 | 139 | EFLAGS; Contains flags that store outcomes of computations (e.g., Zero and Carry flags) 140 | 141 | ## Post-Scriptum 142 | 143 | If you have suggestions for improving this cheat sheet, please [let me know](http://zeltser.com/about/contact.html). 144 | 145 | [Creative Commons v3 "Attribution" License](http://creativecommons.org/licenses/by/3.0/) for this Cheat Sheet v.1.6. 146 | 147 | Take a look at my [other security cheat sheets](http://zeltser.com/cheat-sheets/). 148 | -------------------------------------------------------------------------------- /LDAP_Injection_Prevention_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This cheatsheet is focused on providing clear, simple, actionable guidance for preventing LDAP Injection flaws in your applications. 4 | 5 | LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements through techniques similar to [SQL Injection](https://www.owasp.org/index.php/SQL_Injection). 6 | 7 | LDAP injection attacks could result in the granting of permissions to unauthorized queries, and content modification inside the LDAP tree. 8 | 9 | For more information on LDAP Injection attacks, visit [LDAP injection](https://www.owasp.org/index.php/LDAP_injection). 10 | 11 | [LDAP injection](https://www.owasp.org/index.php/LDAP_injection) attacks are common due to two factors: 12 | 13 | 1. The lack of safer, parameterized LDAP query interfaces 14 | 2. The widespread use of LDAP to authenticate users to systems. 15 | 16 | Primary Defenses: 17 | 18 | - Escape all variables using the right LDAP encoding function 19 | 20 | Additional Defenses: 21 | 22 | - Use a framework (like [LINQtoAD](https://archive.codeplex.com/?p=linqtoad)) that escapes automatically. 23 | 24 | # Primary Defenses 25 | 26 | ## Defense Option 1: Escape all variables using the right LDAP encoding function 27 | 28 | The main way LDAP stores names is based on DN (distinguished name). You can think of this like a unique identifier. These are sometimes used to access resources, like a username. 29 | 30 | A DN might look like this 31 | 32 | `cn=Richard Feynman, ou=Physics Department, dc=Caltech, dc=edu` 33 | 34 | or 35 | 36 | `uid=inewton, ou=Mathematics Department, dc=Cambridge, dc=com` 37 | 38 | There are certain characters that are considered special characters in a DN. 39 | 40 | The [exhaustive list](https://ldapwiki.com/wiki/DN%20Escape%20Values) is the following: `\ # + < > , ; " =` and leading or trailing spaces. 41 | 42 | Some "special" characters that are allowed in Distinguished Names and do not need to be escaped include: 43 | 44 | ```text 45 | * ( ) . & - _ [ ] ` ~ | @ $ % ^ ? : { } ! ' 46 | ``` 47 | 48 | Each DN points to exactly 1 entry, which can be thought of sort of like a row in a RDBMS. For each entry, there will be 1 or more attributes which are analogous to RDBMS columns. If you are interested in searching through LDAP for users will certain attributes, you may do so with search filters. 49 | 50 | In a search filter, you can use standard boolean logic to get a list of users matching an arbitrary constraint. Search filters are written in Polish notation AKA prefix notation. 51 | 52 | Example: 53 | 54 | ```text 55 | (&(ou=Physics)(| 56 | (manager=cn=Freeman Dyson,ou=Physics,dc=Caltech,dc=edu) 57 | (manager=cn=Albert Einstein,ou=Physics,dc=Princeton,dc=edu) 58 | )) 59 | ``` 60 | 61 | When building LDAP queries in application code, you MUST escape any untrusted data that is added to any LDAP query. There are two forms of LDAP escaping. Encoding for LDAP Search and Encoding for LDAP DN (distinguished name). The proper escaping depends on whether you are sanitizing input for a search filter, or you are using a DN as a username-like credential for accessing some resource. 62 | 63 | ### Safe Java Escaping Example 64 | 65 | - [Prevent LDAP injection](https://wiki.sei.cmu.edu/confluence/spaces/flyingpdf/pdfpageexport.action?pageId=88487534). 66 | - [Legacy OWASP ESAPI for Java DefaultEncoder which includes encodeForLDAP(String) and encodeForDN(String)](https://github.com/ESAPI/esapi-java-legacy/blob/develop/src/main/java/org/owasp/esapi/reference/DefaultEncoder.java). 67 | 68 | ### Safe C Sharp .NET TBA Example 69 | 70 | [.NET AntiXSS](https://blogs.msdn.microsoft.com/securitytools/2010/09/30/antixss-4-0-released/) (now the Encoder class) has LDAP encoding functions including `Encoder.LdapFilterEncode(string)`, `Encoder.LdapDistinguishedNameEncode(string)` and `Encoder.LdapDistinguishedNameEncode(string, bool, bool)`. 71 | 72 | `Encoder.LdapFilterEncode` encodes input according to [RFC4515](https://tools.ietf.org/search/rfc4515) where unsafe values are converted to `\XX` where `XX` is the representation of the unsafe character. 73 | 74 | `Encoder.LdapDistinguishedNameEncode` encodes input according to [RFC2253](https://tools.ietf.org/html/rfc2253) where unsafe characters are converted to `#XX` where `XX` is the representation of the unsafe character and the comma, plus, quote, slash, less than and great than signs are escaped using slash notation (`\X`). In addition to this a space or octothorpe (`#`) at the beginning of the input string is `\` escaped as is a space at the end of a string. 75 | 76 | `LdapDistinguishedNameEncode(string, bool, bool)` is also provided so you may turn off the initial or final character escaping rules, for example if you are concatenating the escaped distinguished name fragment into the midst of a complete distinguished name. 77 | 78 | ## Defense Option 2: Use Frameworks that Automatically Protect from LDAP Injection 79 | 80 | Safe NET Example 81 | 82 | [LINQ to Active Directory](https://linqtoad.codeplex.com) provides automatic LDAP encoding when building LDAP queries. 83 | 84 | ## Defense Option 3: Additional Defenses 85 | 86 | Beyond adopting one of the two primary defenses, we also recommend adopting all of these additional defenses in order to provide defense in depth. These additional defenses are: 87 | 88 | - **Least Privilege** 89 | - **White List Input Validation** 90 | 91 | ### Least Privilege 92 | 93 | To minimize the potential damage of a successful LDAP injection attack, you should minimize the privileges assigned to the LDAP binding account in your environment. 94 | 95 | ### White List Input Validation 96 | 97 | Input validation can be used to detect unauthorized input before it is passed to the LDAP query. For more information please see the [Input Validation Cheat Sheet](Input_Validation_Cheat_Sheet.md). 98 | 99 | # Related Articles 100 | 101 | - OWASP article on [LDAP Injection](https://www.owasp.org/index.php/LDAP_injection) Vulnerabilities. 102 | - OWASP article on [Preventing LDAP Injection in Java](https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java). 103 | - [OWASP Testing Guide](https://www.owasp.org/index.php/OWASP_Testing_Project) article on how to [Test for LDAP Injection](https://www.owasp.org/index.php/Testing_for_LDAP_Injection_(OTG-INPVAL-006)) Vulnerabilities. 104 | 105 | # Authors and Primary Editors 106 | 107 | Ben Weintraub - Ben@bluetalon.com 108 | 109 | Jim Manico - jim@owasp.org 110 | -------------------------------------------------------------------------------- /Analyzing_Malicious_Documents.md: -------------------------------------------------------------------------------- 1 | # Analyzing Malicious Documents Cheat Sheet 2 | 3 | This cheat sheet outlines tips and tools for reverse-engineering malicious documents, such as Microsoft Office (DOC, XLS, PPT) and Adobe Acrobat (PDF) files. 4 | 5 | ## General Approach 6 | 7 | 1. Locate potentially malicious embedded code, such as shellcode, VBA macros, or JavaScript. 8 | 2. Extract suspicious code segments from the file. 9 | 3. If relevant, disassemble and/or debug shellcode. 10 | 4. If relevant, deobfuscate and examine JavaScript, ActionScript, or VB macro code. 11 | 5. Understand next steps in the infection chain. 12 | 13 | ## Microsoft Office Binary File Format Notes 14 | 15 | Structured Storage (OLE SS) defines a file system inside the binary Microsoft Office file. 16 | 17 | Data can be “storage” (folder) and “stream” (file). 18 | 19 | Excel stores data inside the “workbook” stream. 20 | 21 | PowerPoint stores data inside the “PowerPoint Document” stream. 22 | 23 | Word stores data inside various streams. 24 | 25 | ## Tools for Analyzing Microsoft Office Files 26 | 27 | [OfficeMalScanner](http://www.reconstructer.org/code/OfficeMalScanner.zip) locates shellcode and VBA macros from MS Office (DOC, XLS, and PPT) files. 28 | 29 | MalHost-Setup extracts shellcode from a given offset in an MS Office file and embeds it an EXE file for further analysis. (Part of [OfficeMalScanner](http://www.reconstructer.org/code/OfficeMalScanner.zip)) 30 | 31 | [Offvis](http://go.microsoft.com/fwlink/?LinkId=158791) shows raw contents and structure of an MS Office file, and identifies some common exploits. 32 | 33 | [Hachoir-urwid](https://bitbucket.org/haypo/hachoir/wiki/hachoir-urwid) can navigate through the structure of binary Office files and view stream contents. 34 | 35 | [Office Binary Translator](http://b2xtranslator.sourceforge.net/) converts DOC, PPT, and XLS files into Open XML files (includes [BiffView](http://b2xtranslator.sourceforge.net/snapshots/BiffView.zip) tool). 36 | 37 | pyOLEScanner.py can examine and decode some aspects of malicious binary Office files. 38 | 39 | [FileHex](http://www.heaventools.com/) (not free) and [FileInsight](http://vil.nai.com/vil/averttools.aspx) hex editors can parse and edit OLE structures. 40 | 41 | ## Useful MS Office Analysis Commands 42 | 43 | OfficeMalScanner _file.doc_ scan brute 44 | 45 | Locate shellcode, OLE data, PE files in _file.doc_ 46 | 47 | OfficeMalScanner _file.doc_ info 48 | 49 | Locate VB macro code in _file.doc_ (no XML files) 50 | 51 | OfficeMalScanner _file.docx_ inflate 52 | 53 | Decompress _file.docx_ to locate VB code (XML files) 54 | 55 | MalHost-Setup _file.doc_ _out.exe_ 0x4500 56 | 57 | Extract shellcode from _file.doc_’s offset 0x4500 and create it as _out.exe_ 58 | 59 | ## Adobe PDF File Format Notes 60 | 61 | A PDF File is comprised of header, objects, cross-reference table (to locate objects), and trailer. 62 | 63 | “/OpenAction” and “/AA” (Additional Action) specifies the script or action to run automatically. 64 | 65 | “/Names”, “/AcroForm”, “/Action” can also specify and launch scripts or actions. 66 | 67 | “/JavaScript” specifies JavaScript to run. 68 | 69 | “/GoTo*” changes the view to a specified destination within the PDF or in another PDF file. 70 | 71 | “/Launch” launches a program or opens a document. 72 | 73 | “/URI” accesses a resource by its URL. 74 | 75 | “/SubmitForm” and “/GoToR” can send data to URL. 76 | 77 | “/RichMedia” can be used to embed Flash in PDF. 78 | 79 | “/ObjStm” can hide objects inside an Object Stream. 80 | 81 | Be mindful of obfuscation with hex codes, such as “/JavaScript” vs. “/J#61vaScript”. ([See examples](http://blog.didierstevens.com/2008/04/29/pdf-let-me-count-the-ways/)) 82 | 83 | ## Tools for Analyzing Adobe PDF Files 84 | 85 | [PDFiD](http://blog.didierstevens.com/programs/pdf-tools/) identifies PDFs that contain strings associated with scripts and actions. 86 | 87 | [PDF-parser](http://blog.didierstevens.com/programs/pdf-tools/) and [Origami’s](http://security-labs.org/origami/) pdfwalker examines the structure of PDF files. 88 | 89 | [Origami’s](http://security-labs.org/origami/) pdfextract and [Jsunpack-n’s](http://jsunpack.blogspot.com/2009/06/jsunpack-n-updates-for-pdf-decoding.html) pdf.py extract JavaScript from PDF files. 90 | 91 | [PDF Stream Dumper](http://blog.zeltser.com/post/3235995383/pdf-stream-dumper-malicious-file-analysis) combines many PDF analysis tools under a single graphical user interface. 92 | 93 | [Peepdf](http://blog.zeltser.com/post/6780160077/peepdf-malicious-pdf-analysis) and [Origami’s](http://esec-lab.sogeti.com/pages/Origami) pdfsh offer an interactive command-line shell for examining PDF files. 94 | 95 | [PDF X-RAY Lite](https://github.com/9b/pdfxray_lite) creates an HTML report containing decoded PDF file structure and contents. 96 | 97 | [SWF mastah](http://blog.zeltser.com/post/12615013257/extracting-swf-from-pdf-using-swf-mastah) extracts SWF objects from PDF files. 98 | 99 | [Pyew](http://code.google.com/p/pyew/wiki/PDFAnalysis) includes commands for examining and decoding structure and content of PDF files. 100 | 101 | ## Useful PDF Analysis Commands 102 | 103 | pdfid.py _file.pdf_ 104 | 105 | Locate script and action-related strings in _file.pdf_ 106 | 107 | pdf-parser.py _file.pdf_ 108 | 109 | Show _file.pdf_’s structure to identify suspect elements 110 | 111 | pdf-parser.py --object _id_ _file.pdf_ 112 | 113 | Display contents of object _id_ in _file.pdf_. Add “--filter --raw” to decode the object’s stream. 114 | 115 | pdfextract _file.pdf_ 116 | 117 | Extract JavaScript embedded in _file.pdf_ and save it to _file.dump_. 118 | 119 | pdf.py _file.pdf_ 120 | 121 | Extract JavaScript embedded in _file.pdf_ and save it to _file.pdf.out_. 122 | 123 | swf_mastah.py –f _file.pdf_ 124 | –o _out_ 125 | 126 | Extract PDF objects from _file.pdf_ into the _out_ directory. 127 | 128 | ## Additional PDF Analysis Tools 129 | 130 | [Malzilla](http://www.malzilla.org/) and [SpiderMonkey](http://isc.sans.edu/diary.html?storyid=12157) can help deobfuscate JavaScript embedded in malicious PDF files. 131 | 132 | [Wepawet](http://wepawet.cs.ucsb.edu/), [Jsunpack](http://jsunpack.jeek.org/dec/go), [VirusTotal](http://www.virustotal.com/) and [sandbox tools](http://zeltser.com/reverse-malware/automated-malware-analysis.html) can analyze some aspects of malicious PDF files. 133 | 134 | [ExeFilter](http://www.decalage.info/exefilter) can filter scripts from Office and PDF files. 135 | 136 | ## References 137 | 138 | [Adobe Portable Document Format (PDF) Reference](http://www.adobe.com/devnet/pdf/pdf_reference.html) 139 | 140 | [Physical and Logical Structure of PDF Files](http://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/) 141 | 142 | [Methods for Understanding and Analyzing Targeted Attacks with Office Documents](http://recon.cx/2008/a/bruce_dang/recon08_final.zip) ([video](http://bork.informatik.uni-erlangen.de/pub/ccc/25c3/video_h264_720x576/25c3-2938-en-methods_for_understanding_targeted_attacks_with_office_documents.mp4)) 143 | 144 | [Analyzing MSOffice Malware with OfficeMalScanner](http://www.reconstructer.org/papers/Analyzing%20MSOffice%20malware%20with%20OfficeMalScanner.zip) ([follow-up presentation](http://2009.hack.lu/archive/2009/New%20advances%20in%20Ms%20Office%20malware%20analysis.pdf)) 145 | 146 | [PDF Security Analysis and Malware Threats](http://www.blackhat.com/presentations/bh-europe-08/Filiol/Presentation/bh-eu-08-filiol.pdf) 147 | 148 | [Reverse-Engineering Malware cheat sheet](http://zeltser.com/reverse-malware/reverse-malware-cheat-sheet.html) 149 | 150 | [REMnux Linux distribution for malware analysis.](http://remnux.org/) 151 | -------------------------------------------------------------------------------- /OS_Command_Injection_Defense_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Command injection (or OS Command Injection) is a type of injection where the software, that constructs a system command using externally influenced input, does not correctly neutralizes the input from special elements that can modify the initially intended command. 4 | 5 | For example, if the supplied value is: 6 | 7 | ``` shell 8 | calc 9 | ``` 10 | 11 | when typed in a Windows command prompt, the application *Calculator* is displayed. 12 | 13 | However, if the supplied value has been tempered with, and now it is: 14 | 15 | ``` shell 16 | calc & echo “test” 17 | ``` 18 | 19 | When execute, it changes the meaning of the initial intended value. 20 | 21 | Now, both the *Calculator* application and the value *test* are displayed: 22 | 23 | 24 | 25 | The problem is exacerbated if the compromised process does not follow the principle of least privilege principle and attacker-controlled commands end up running with special system privileges that increases the amount of damage. 26 | 27 | # Primary Defenses 28 | 29 | ## Defense Option 1: Avoid calling OS commands directly 30 | 31 | The primary defense is to avoid calling OS commands directly. Built-in library functions are a very good alternative to OS Commands, and they cannot be manipulated to perform tasks other than those it is intended to do. 32 | 33 | For example use `mkdir()` instead of `system(“mkdir /dir_name”)`. 34 | 35 | If there are available libraries or APIs for the language you used, this is the preferred method. 36 | 37 | ## Defense option 2: Escape values added to OS commands specific to each OS 38 | 39 | **TODO: To enhance.** 40 | 41 | For examples, see [escapeshellarg()](http://php.net/manual/en/function.escapeshellarg.php) or [escapeshellcmd()](http://php.net/manual/en/function.escapeshellcmd.php) in PHP. 42 | 43 | ## Defense option 3: Parametrization in conjunction with Input Validation 44 | 45 | If it is considered unavoidable the call to a system command incorporated with user-supplied, the following two layers of defense should be used within software in order to prevent attacks 46 | 47 | ### Layer 1 48 | 49 | **Parametrization:** If available, use structured mechanisms that automatically enforce the separation between data and command. These mechanisms can help to provide the relevant quoting, encoding. 50 | 51 | ### Layer 2 52 | 53 | **Input validation:** The values for commands and the relevant arguments should be both validated. There are different degrees of validation for the actual command and its arguments: 54 | - When it comes to the **commands** used, these must be validated against a whitelist of allowed commands. 55 | - In regards to the **arguments** used for these commands, they should be validated using the following options: 56 | - **Positive or whitelist input validation**: Where are the arguments allowed explicitly defined. 57 | - **White list Regular Expression**: Where is explicitly defined a whitelist of good characters allowed and the maximum length of the string. Ensure that metacharacters like ones specified in `Note A` and white-spaces are not part of the Regular Expression. For example, the following regular expression only allows lowercase letters and numbers, and does not contain metacharacters. The length is also being limited to 3-10 characters: `^[a-z0-9]{3,10}$` 58 | 59 | **Note A:** 60 | 61 | ```text 62 | & | ; $ > < ` \ ! 63 | ``` 64 | 65 | # Additional Defenses 66 | 67 | On top of primary defences, parameterizations and input validation, we also recommend adopting all of these additional defenses in order to provide defense in depth. 68 | 69 | These additional defenses are: 70 | 71 | - Applications should run using the lowest privileges that are required to accomplish the necessary tasks. 72 | - If possible, create isolated accounts with limited privileges that are only used for a single task. 73 | 74 | # Code examples 75 | 76 | ## Java 77 | 78 | In Java, use [ProcessBuilder](https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html) and the command must be separated from its arguments. 79 | 80 | *Note about the Java's `Runtime.exec` method behavior:* 81 | 82 | There are many sites that will tell you that Java's `Runtime.exec` is exactly the same as `C`'s system function. This is not true. Both allow you to invoke a new program/process. 83 | 84 | However, `C`'s system function passes its arguments to the shell (`/bin/sh`) to be parsed, whereas `Runtime.exec` tries to split the string into an array of words, then executes the first word in the array with the rest of the words as parameters. 85 | 86 | **`Runtime.exec` does NOT try to invoke the shell at any point and do not support shell metacharacters**. 87 | 88 | The key difference is that much of the functionality provided by the shell that could be used for mischief (chaining commands using `&`, `&&`, `|`, `||`, etc, redirecting input and output) would simply end up as a parameter being passed to the first command, and likely causing a syntax error, or being thrown out as an invalid parameter. 89 | 90 | *Code to test the note above:* 91 | 92 | ``` java 93 | String[] specialChars = new String[]{"&", "&&", "|", "||"}; 94 | String payload = "cmd /c whoami"; 95 | String cmdTemplate = "java -version %s " + payload; 96 | String cmd; 97 | Process p; 98 | int returnCode; 99 | for (String specialChar : specialChars) { 100 | cmd = String.format(cmdTemplate, specialChar); 101 | System.out.printf("#### TEST CMD: %s\n", cmd); 102 | p = Runtime.getRuntime().exec(cmd); 103 | returnCode = p.waitFor(); 104 | System.out.printf("RC : %s\n", returnCode); 105 | System.out.printf("OUT :\n%s\n", IOUtils.toString(p.getInputStream(), 106 | "utf-8")); 107 | System.out.printf("ERROR :\n%s\n", IOUtils.toString(p.getErrorStream(), 108 | "utf-8")); 109 | } 110 | System.out.printf("#### TEST PAYLOAD ONLY: %s\n", payload); 111 | p = Runtime.getRuntime().exec(payload); 112 | returnCode = p.waitFor(); 113 | System.out.printf("RC : %s\n", returnCode); 114 | System.out.printf("OUT :\n%s\n", IOUtils.toString(p.getInputStream(), 115 | "utf-8")); 116 | System.out.printf("ERROR :\n%s\n", IOUtils.toString(p.getErrorStream(), 117 | "utf-8")); 118 | ``` 119 | 120 | *Result of the test:* 121 | 122 | ```text 123 | #### TEST CMD: java -version & cmd /c whoami 124 | RC : 0 125 | OUT : 126 | 127 | ERROR : 128 | java version "1.8.0_31" 129 | 130 | #### TEST CMD: java -version && cmd /c whoami 131 | RC : 0 132 | OUT : 133 | 134 | ERROR : 135 | java version "1.8.0_31" 136 | 137 | #### TEST CMD: java -version | cmd /c whoami 138 | RC : 0 139 | OUT : 140 | 141 | ERROR : 142 | java version "1.8.0_31" 143 | 144 | #### TEST CMD: java -version || cmd /c whoami 145 | RC : 0 146 | OUT : 147 | 148 | ERROR : 149 | java version "1.8.0_31" 150 | 151 | #### TEST PAYLOAD ONLY: cmd /c whoami 152 | RC : 0 153 | OUT : 154 | mydomain\simpleuser 155 | 156 | ERROR : 157 | ``` 158 | 159 | *Incorrect usage:* 160 | 161 | ```java 162 | ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2"); 163 | ``` 164 | 165 | In this example, the command together with the arguments are passed as a one string, making easy to manipulate that expression and inject malicious strings. 166 | 167 | *Correct Usage:* 168 | 169 | Here is an example that starts a process with a modified working directory. The command and each of the arguments are passed separately. This make it easy to validated each term and reduces the risk to insert malicious strings. 170 | 171 | ``` java 172 | ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "TrustedArg1", "TrustedArg2"); 173 | 174 | Map env = pb.environment(); 175 | 176 | pb.directory(new File("TrustedDir")); 177 | 178 | Process p = pb.start(); 179 | ``` 180 | 181 | ## .Net 182 | 183 | In .Net use [System.Diagnostics.Process.Start](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start?view=netframework-4.7.2) to call underlying OS functions. 184 | 185 | ``` csharp 186 | System.Diagnostics.Process process = new System.Diagnostics.Process(); 187 | 188 | System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 189 | 190 | startInfo.FileName = "validatedCommand"; 191 | 192 | startInfo.Arguments = "validatedArg1 validatedArg2 validatedArg3"; 193 | 194 | process.StartInfo = startInfo; 195 | 196 | process.Start(); 197 | ``` 198 | 199 | ## PHP 200 | 201 | In PHP use [escapeshellarg()](http://php.net/manual/en/function.escapeshellarg.php) or [escapeshellcmd()](http://php.net/manual/en/function.escapeshellcmd.php) rather than [exec()](http://php.net/manual/en/function.exec.php), [system()](http://php.net/manual/en/function.system.php), [passthru()](http://php.net/manual/en/function.passthru.php). 202 | 203 | # Related articles 204 | 205 | ## Description of Command Injection Vulnerability 206 | 207 | - OWASP [Command Injection](https://www.owasp.org/index.php/Command_Injection). 208 | 209 | ## How to Avoid Vulnerabilities 210 | 211 | - C Coding: [Do not call system()](https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177). 212 | 213 | ## How to Review Code 214 | 215 | - OWASP [Reviewing Code for OS Injection](https://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection). 216 | 217 | ## How to Test 218 | 219 | - [OWASP Testing Guide](https://www.owasp.org/index.php/OWASP_Testing_Project) article on [Testing for Command Injection](https://www.owasp.org/index.php/Testing_for_Command_Injection_(OTG-INPVAL-013)). 220 | 221 | ## External References 222 | 223 | - [CWE Entry 77 on Command Injection](https://cwe.mitre.org/data/definitions/77.html). 224 | 225 | # Authors and Primary Editors 226 | 227 | Katy Anton - katy.anton@owasp.org 228 | 229 | Jim Manico - jim.manico@owasp.org 230 | -------------------------------------------------------------------------------- /TLS_Cipher_String_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This article is focused on providing clear and simple examples for the cipher string. They are based on different scenarios where you use the Transport Layer Security (TLS) protocol. 4 | 5 | # Recommendations for a cipher string 6 | 7 | ## Scenarios 8 | 9 | The cipher strings are based on the recommendation to setup your policy to get a whitelist for your ciphers as described in the *[Transport Layer Protection Cheat Sheet (Rule - Only Support Strong Cryptographic Ciphers)](Transport_Layer_Protection_Cheat_Sheet.md)*. The latest and strongest ciphers are solely available with TLSv1.2, older protocols don't support them. Please find enclosed all supported protocols by the scenario. 10 | 11 | We have not included any `ChaCha20-Poly1305` ciphers, yet. One reason is that we haven't found various assessments yet, the other is that implementations of new ciphers may be more buggy. 12 | 13 | Finally we have compiled the oldest versions of different client agents that are still compatible with a cipher string. We provide this information according to the ciphers and protocols supported by browsers, libraries, bots on the basis of *[ssllabs's list of user agent capabilities](https://www.ssllabs.com/ssltest/clients.html)* and tests on our own. 14 | 15 | We have checked this thoroughly, but please accept that all data is provided without any warranty of any kind (Please contact the authors if you find any errors or if you can provide additional data). 16 | 17 | The recommended cipher strings are based on different scenarios: 18 | 19 | **OWASP Cipher String 'A+'** (Advanced+, limited compatibility, e.g. to more recent browser versions): 20 | 21 | * Recommended if you control the server and the clients (e.g. by approvement) and if you check the compatibility before using it 22 | * Includes solely the strongest [Perfect Forward Secrecy (PFS)](https://scotthelme.co.uk/perfect-forward-secrecy/) ciphers. 23 | * Protocols: `TLSv1.2` (and newer or better). 24 | * Oldest known clients that are compatible: Android 4.4.2, BingPreview Jan 2015, Chrome 32/Win 7, Chrome 34/OS X, Edge 12/Win 10, Firefox 27/Win 8, Googlebot Feb 2015, IE11/Win 7 + MS14-066, Java8b132, OpenSSL 1.0.1e, Safari 9/iOS 9, Yahoo Slurp Jun 2014, YandexBot Sep 2014. 25 | 26 | **OWASP Cipher String 'A'** (Advanced, wider compatibility, e.g. to most newer browser versions): 27 | 28 | * Recommended if you control the server and the clients (e.g. by approvement) if the 'A+' string does not work, make sure to check the compatibility before using it 29 | * Includes solely the strongest and stronger [PFS](https://scotthelme.co.uk/perfect-forward-secrecy/) ciphers 30 | * Protocols: `TLSv1.2` (and newer or better). 31 | * Oldest known clients that are compatible: Android 4.4.2, BingPreview Jan 2015, Chrome 30/Win 7, Chrome 34/OS X, Edge 12/Win 10, Firefox 27/Win 8, Googlebot Feb 2015, IE11/Win 7, IE 11/WinPhone 8.1, Java8b132, OpenSSL 1.0.1e, Opera 17/Win 7, Safari 5/iOS 5.1.1, Safari 7/OS X 10.9, Yahoo Slurp Jun 2014, YandexBot Sep 2014 32 | 33 | **OWASP Cipher String 'B'** (Broad compatibility to browsers, check the compatibility to other protocols before using it, e.g. IMAPS): 34 | 35 | * Recommended if you solely control the server, the clients use their browsers and if you check the compatibility before using it for other protocols than https. 36 | * Includes solely [PFS](https://scotthelme.co.uk/perfect-forward-secrecy/) ciphers. 37 | * Be aware of additional risks and of new vulnerabilities that may appear are more likely than above. 38 | * Plan to phase out SHA-1 and TLSv1, TLSv1.1 for https in middle-term. 39 | * Protocols: `TLSv1.2`, `TLSv1.1`, `TLSv1` (and newer or better). 40 | * Oldest known clients that are compatible: Android 2.3.7/4.0.4, Baidu Jan 2015, BingPreview Dec 2013, Chrome 27/Win 7, Chrome 34/OS X, Edge 12/Win 10, Firefox 10.0.12 ESR/Win 7, Firefox 21/Win 7+Fedora 19, Googlebot Oct 2013, IE 7/Vista, IE 10/WinPhone 8.0, Java 7u25, OpenSSL 0.9.8y, Opera 12.15/Win 7, Safari 5/iOS 5.1.1, Safari 5.1.9/OS X 10.6.8, Yahoo Slurp Oct 2013, YandexBot May 2014 41 | 42 | **OWASP Cipher String 'C'** (Widest Compatibility, compatibility to most legacy browsers, legacy libraries (still patched) and other application protocols besides https, e.g. IMAPS): 43 | 44 | * You may use this if you solely control the server, your clients use elder browsers and other elder libraries or if you use other protocols than https. 45 | * Be aware of the existing risks and of new vulnerabilities that may appear more likely. 46 | * [PFS](https://scotthelme.co.uk/perfect-forward-secrecy/) ciphers are preferred, except all [DHE](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) ciphers that use SHA-1 (to prevent possible incompatibility issues caused by the length of the [DHparameter](https://wiki.openssl.org/index.php/Diffie-Hellman_parameters)). 47 | * Plan to move to 'A' for https or at least 'B' otherwise in middle-term. 48 | * Protocols: `TLSv1.2`, `TLSv1.1`, `TLSv1` (and newer or better). 49 | 50 | **OWASP Cipher String 'C-'** (Legacy, widest compatibility to real old browsers and legacy libraries and other application protocols like SMTP): 51 | 52 | * Take care, use this cipher string only if you are forced to support `3DES` (`TLS_RSA_WITH_3DES_EDE_CBC_SHA`, `DES-CBC3-SHA`) for real old clients with very old libraries or old libraries for other protocols besides https 53 | * Be aware of the existing risks (e.g. ciphers without PFS, ciphers with 3DES) and of new vulnerabilities that may appear the most likely 54 | * **Never use** even more INSECURE or elder ciphers based on `RC2`, `RC4`, `DES`, `MD4`, `MD5`, `EXP`, `EXP1024`, `AH`, `ADH`, `aNULL`, `eNULL`, `SEED` nor `IDEA`. 55 | * [PFS](https://scotthelme.co.uk/perfect-forward-secrecy/) ciphers are preferred, except all [DHE](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) ciphers that use SHA-1 (to prevent possible incompatibility issues caused by the length of the [DHparameter](https://wiki.openssl.org/index.php/Diffie-Hellman_parameters)) 56 | * Plan to move at least to 'C' in a short-term 57 | * Protocols: `TLSv1.2`, `TLSv1.1`, `TLSv1` (and newer or better) 58 | 59 | ## Table of the ciphers (and their priority from high (1) to low (e.g. 19)) 60 | 61 | IANA, OpenSSL and other crypto libraries use slightly different names for the same ciphers. 62 | 63 | This table lists the names used by IANA and by openssl in brackets `[]`. Additional you can find the unambiguously hex values defined by IANA. Mozilla offers a larger *[cipher names correspondence table](https://wiki.mozilla.org/Security/Server_Side_TLS#Cipher_names_correspondence_table)*. 64 | 65 | 66 | | Cipher name:
IANA, [OpenSSL] | Cipher HEX value | Advanced+
(A+) | Advanced
(A) | Broad Compatibility
(B) | Widest Compatibility
(C) | Legacy
(C-) | 67 | | --- | :---: | :---: | :---: | :---: | :---: | :---: | 68 | | `TLS_DHE_RSA_WITH_AES_256_GCM_SHA384`,
[`DHE-RSA-AES256-GCM-SHA384`] | 0x009f | 1 | 1 | 1 | 1 | 1 | 69 | | `TLS_DHE_RSA_WITH_AES_128_GCM_SHA256`,
[`DHE-RSA-AES128-GCM-SHA256`] | 0x009e | 2 | 2 | 2 | 2 | 2 | 70 | | `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,
[`ECDHE-RSA-AES256-GCM-SHA384`] | 0xc030 | 3 | 3 | 3 | 3 | 3 | 71 | | `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,
[`ECDHE-RSA-AES128-GCM-SHA256`] | 0xc02f | 4 | 4 | 4 | 4 | 4 | 72 | | `TLS_DHE_RSA_WITH_AES_256_CBC_SHA256`,
[`DHE-RSA-AES256-SHA256`] | 0x006b | | 5 | 5 | 5 | 5 | 73 | | `TLS_DHE_RSA_WITH_AES_128_CBC_SHA256`,
[`DHE-RSA-AES128-SHA256`] | 0x0067 | | 6 | 6 | 6 | 6 | 74 | | `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384`,
[`ECDHE-RSA-AES256-SHA384`] | 0xc028 | | 7 | 7 | 7 | 7 | 75 | | `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`,
[`ECDHE-RSA-AES128-SHA256`] | 0xc027 | | 8 | 8 | 8 | 8 | 76 | | `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`,
[`ECDHE-RSA-AES256-SHA`] | 0xc014 | | | 9 | 9 | 9 | 77 | | `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`,
[`ECDHE-RSA-AES128-SHA`] | 0xc013 | | | 10 | 10 | 10 | 78 | | `TLS_RSA_WITH_AES_256_GCM_SHA384`,
[`AES256-GCM-SHA384`] | 0x009d | | | | 11 | 11 | 79 | | `TLS_RSA_WITH_AES_128_GCM_SHA256`,
[`AES128-GCM-SHA256`] | 0x009c | | | | 12 | 12 | 80 | | `TLS_RSA_WITH_AES_256_CBC_SHA256`,
[`AES256-SHA256`] | 0x003d | | | | 13 | 13 | 81 | | `TLS_RSA_WITH_AES_128_CBC_SHA256`,
[`AES128-SHA256`] | 0x003c | | | | 14 | 14 | 82 | | `TLS_RSA_WITH_AES_256_CBC_SHA`,
[`AES256-SHA`] | 0x0035 | | | | 15 | 15 | 83 | | `TLS_RSA_WITH_AES_128_CBC_SHA`,
[`AES128-SHA`] | 0x002f | | | | 16 | 16 | 84 | | `TLS_RSA_WITH_3DES_EDE_CBC_SHA`,
[`DES-CBC3-SHA`] | 0x000a | | | | | 17 | 85 | | `TLS_DHE_RSA_WITH_AES_256_CBC_SHA`,
[`DHE-RSA-AES256-SHA`] | 0x0039 | | | 11 | 17 | 18 | 86 | | `TLS_DHE_RSA_WITH_AES_128_CBC_SHA`,
[`DHE-RSA-AES128-SHA`] | 0x0033 | | | 12 | 18 | 19 | 87 | 88 | 89 | **Remarks:** 90 | 91 | Elder versions of Internet-Explorer and Java do **NOT** support Diffie-Hellman parameters superior to 1024 bit. So the ciphers `TLS_DHE_RSA_WITH_AES_256_CBC_SHA` and `TLS_DHE_RSA_WITH_AES_128_CBC_SHA` were moved to the end to prevent possible incompatibility issues. 92 | 93 | Other option: *Delete this two ciphers from your list*. 94 | 95 | ## Examples for cipher strings 96 | 97 | ### OpenSSL 98 | 99 | 100 | | Cipher-String | OpenSSL syntax | 101 | | --- | --- | 102 | | Advanced+
(A+) | `DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256` | 103 | | Advanced
(A) | `DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256` | 104 | | Broad Compatibility
(B) | `DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA` | 105 | | Widest Compatibility
(C) | `DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA` | 106 | | Legacy
(C-) | `DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA` | 107 | 108 | 109 | # How to use this Cipher Strings? 110 | 111 | Inform yourself how to securely configure the settings for the services or hardware that you do use, e.g. *[BetterCrypto.org: Applied Crypto Hardening (DRAFT)](https://bettercrypto.org)*, *[Mozilla: Security/Server Side TLS](https://wiki.mozilla.org/Security/Server_Side_TLS)*. 112 | 113 | We recommend to use one of the cipher strings described above. 114 | 115 | # Example configs 116 | 117 | ## Apache 118 | 119 | **Cipher String 'A':** 120 | 121 | ```text 122 | SSLProtocol +TLSv1.2 # for Cipher-String 'A+', 'A' 123 | #SSLProtocol +TLSv1.2 +TLSv1.1 +TLSv1 # for Cipher-String 'B', 'C', 'C-' 124 | SSLCompression off 125 | SSLHonorCipherOrder on 126 | SSLCipherSuite 'DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384 127 | :ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256 128 | :ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256' 129 | #add optionally ':!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:!ADH:!IDEA:!3DES' 130 | ``` 131 | 132 | **Remarks:** 133 | 134 | - The cipher string is compiled as a whitelist of individual ciphers to get a better compatibility even with old versions of OpenSSL. 135 | - Monitor the performance of your server, e.g. the TLS handshake with DHE hinders the CPU about 2.4 times more than ECDHE, cf. *[Vincent Bernat, 2011](http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html#some-benchmarks)*, *[nmav's Blog, 2011](http://nmav.gnutls.org/2011/12/price-to-pay-for-perfect-forward.html)*. 136 | - Verify your cipher string using your crypto library, e.g. openssl using cipher string 'A': 137 | 138 | ```text 139 | openssl ciphers -V "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384 140 | :ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384 141 | :ECDHE-RSA-AES128-SHA256" 142 | #add optionally ':!aNULL:!eNULL:!LOW:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:!ADH:!IDEA' to protect 143 | #older Versions of OpenSSL 144 | #use openssl ciphers -v "..." for openssl < 1.0.1: 145 | 146 | 0x00,0x9F - DHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(256) Mac=AEAD 147 | 0x00,0x9E - DHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(128) Mac=AEAD 148 | 0xC0,0x30 - ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD 149 | 0xC0,0x2F - ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD 150 | 0x00,0x6B - DHE-RSA-AES256-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AES(256) Mac=SHA256 151 | 0x00,0x67 - DHE-RSA-AES128-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AES(128) Mac=SHA256 152 | 0xC0,0x28 - ECDHE-RSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 153 | 0xC0,0x27 - ECDHE-RSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 154 | ``` 155 | 156 | **CAUTION:** You need a newer version of OpenSSL to use this cipher string! 157 | 158 | # Related Articles 159 | 160 | - [OWASP: Transport Layer Protection Cheat Sheet](Transport_Layer_Protection_Cheat_Sheet.md). 161 | - [BetterCrypto.org: Applied Crypto Hardening (DRAFT)](https://bettercrypto.org). 162 | - [Mozilla: Security/Server Side TLS](https://wiki.mozilla.org/Security/Server_Side_TLS). 163 | 164 | # Authors and Primary Editors 165 | 166 | Torsten Gigler - torsten.gigler@owasp.org 167 | 168 | Achim Hoffmann - achim@owasp.org 169 | -------------------------------------------------------------------------------- /Clickjacking_Defense_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This cheat sheet is focused on providing developer guidance on [Clickjack/UI Redress](https://www.owasp.org/index.php/Clickjacking) attack prevention. 4 | 5 | The most popular way to defend against Clickjacking is to include some sort of "frame-breaking" functionality which prevents other web pages from framing the site you wish to defend. This cheat sheet will discuss two methods of implementing frame-breaking: first is X-Frame-Options headers (used if the browser supports the functionality); and second is javascript frame-breaking code. 6 | 7 | # Defending with Content Security Policy (CSP) frame-ancestors directive 8 | 9 | The `frame-ancestors` directive can be used in a Content-Security-Policy HTTP response header to indicate whether or not a browser should be allowed to render a page in a `` or ` 246 | ``` 247 | 248 | **Safari 4.0.4** 249 | 250 | We observed that although location is kept immutable in most circumstances, when a custom location setter is defined via `defineSetter` (through window) the object location becomes undefined. 251 | 252 | The framing page simply does: 253 | 254 | ```html 255 | 258 | ``` 259 | 260 | Now any attempt to read or navigate the top frame's location will fail. 261 | 262 | ## Restricted zones 263 | 264 | Most frame busting relies on JavaScript in the framed page to detect framing and bust itself out. If JavaScript is disabled in the context of the subframe, the frame busting code will not run. There are unfortunately several ways of restricting JavaScript in a subframe: 265 | 266 | **In IE 8:** 267 | 268 | ```html 269 | 270 | ``` 271 | 272 | **In Chrome:** 273 | 274 | ```html 275 | 276 | ``` 277 | 278 | **Firefox and IE:** 279 | 280 | Activate [designMode](https://developer.mozilla.org/en-US/docs/Web/API/Document/designMode) in parent page. 281 | 282 | ```javascript 283 | document.designMode = "on"; 284 | ``` 285 | 286 | # Authors and Primary Editors 287 | 288 | Jim Manico - jim@owasp.org 289 | 290 | Santhosh Tuppad - santhosh.tuppad@gmail.com 291 | 292 | Jeffrey Walton 293 | 294 | Till Maas 295 | 296 | Dave Wichers - dwichers@gmail.com 297 | 298 | Michael Brook 299 | 300 | Tom Parker 301 | 302 | Shruti kulkarni 303 | 304 | Yozo 305 | 306 | Eelgheez 307 | 308 | Aabashkin 309 | -------------------------------------------------------------------------------- /Injection_Prevention_CheatSheet_in_Java.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This document has for objective to provide some tips to handle *Injection* into Java application code. 4 | 5 | Sample codes used in tips are located [here](https://github.com/righettod/injection-cheat-sheets). 6 | 7 | # What is Injection ? 8 | 9 | [Injection](https://www.owasp.org/index.php/Top_10_2007-Injection_Flaws) in OWASP Top 10 is defined as following: 10 | 11 | *Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.* 12 | 13 | # General advices to prevent Injection 14 | 15 | The following point can be applied, in a general way, to prevent *Injection* issue: 16 | 17 | 1. Apply **Input Validation** (using whitelist approach) combined with **Output Sanitizing+Escaping** on user input/output. 18 | 2. If you need to interact with system, try to use API features provided by your technology stack (Java / .Net / PHP...) instead of building command. 19 | 20 | Additional advices are provided on this [cheatsheet](Input_Validation_Cheat_Sheet.md). 21 | 22 | # Specific Injection types 23 | 24 | *Examples in this section will be provided in Java technology (see Maven project associated) but advices are applicable to others technologies like .Net / PHP / Ruby / Python...* 25 | 26 | ## SQL 27 | 28 | ### Symptom 29 | 30 | Injection of this type occur when the application use untrusted user input to build a SQL query using a String and execute it. 31 | 32 | ### How to prevent 33 | 34 | Use *Query Parameterization* in order to prevent injection. 35 | 36 | ### Example 37 | 38 | ``` java 39 | /*No DB framework used here in order to show the real use of 40 | Prepared Statement from Java API*/ 41 | /*Open connection with H2 database and use it*/ 42 | Class.forName("org.h2.Driver"); 43 | String jdbcUrl = "jdbc:h2:file:" + new File(".").getAbsolutePath() + "/target/db"; 44 | try (Connection con = DriverManager.getConnection(jdbcUrl)) { 45 | 46 | /* Sample A: Select data using Prepared Statement*/ 47 | String query = "select * from color where friendly_name = ?"; 48 | List colors = new ArrayList<>(); 49 | try (PreparedStatement pStatement = con.prepareStatement(query)) { 50 | pStatement.setString(1, "yellow"); 51 | try (ResultSet rSet = pStatement.executeQuery()) { 52 | while (rSet.next()) { 53 | colors.add(rSet.getString(1)); 54 | } 55 | } 56 | } 57 | Assert.assertEquals(1, colors.size()); 58 | Assert.assertTrue(colors.contains("yellow")); 59 | 60 | /* Sample B: Insert data using Prepared Statement*/ 61 | query = "insert into color(friendly_name, red, green, blue) values(?, ?, ?, ?)"; 62 | int insertedRecordCount; 63 | try (PreparedStatement pStatement = con.prepareStatement(query)) { 64 | pStatement.setString(1, "orange"); 65 | pStatement.setInt(2, 239); 66 | pStatement.setInt(3, 125); 67 | pStatement.setInt(4, 11); 68 | insertedRecordCount = pStatement.executeUpdate(); 69 | } 70 | Assert.assertEquals(1, insertedRecordCount); 71 | 72 | /* Sample C: Update data using Prepared Statement*/ 73 | query = "update color set blue = ? where friendly_name = ?"; 74 | int updatedRecordCount; 75 | try (PreparedStatement pStatement = con.prepareStatement(query)) { 76 | pStatement.setInt(1, 10); 77 | pStatement.setString(2, "orange"); 78 | updatedRecordCount = pStatement.executeUpdate(); 79 | } 80 | Assert.assertEquals(1, updatedRecordCount); 81 | 82 | /* Sample D: Delete data using Prepared Statement*/ 83 | query = "delete from color where friendly_name = ?"; 84 | int deletedRecordCount; 85 | try (PreparedStatement pStatement = con.prepareStatement(query)) { 86 | pStatement.setString(1, "orange"); 87 | deletedRecordCount = pStatement.executeUpdate(); 88 | } 89 | Assert.assertEquals(1, deletedRecordCount); 90 | 91 | } 92 | ``` 93 | 94 | ### References 95 | 96 | - [SQL Injection Prevention Cheat Sheet](SQL_Injection_Prevention_Cheat_Sheet.md) 97 | 98 | ## JPA 99 | 100 | ### Symptom 101 | 102 | Injection of this type occur when the application use untrusted user input to build a JPA query using a String and execute it. It's quite similar to SQL injection but here the altered language is not SQL but JPA QL. 103 | 104 | ### How to prevent 105 | 106 | Use Java Persistence Query Language **Query Parameterization** in order to prevent injection. 107 | 108 | ### Example 109 | 110 | ``` java 111 | EntityManager entityManager = null; 112 | try { 113 | /* Get a ref on EntityManager to access DB */ 114 | entityManager = Persistence.createEntityManagerFactory("testJPA").createEntityManager(); 115 | 116 | /* Define parametrized query prototype using named parameter to enhance readability */ 117 | String queryPrototype = "select c from Color c where c.friendlyName = :colorName"; 118 | 119 | /* Create the query, set the named parameter and execute the query */ 120 | Query queryObject = entityManager.createQuery(queryPrototype); 121 | Color c = (Color) queryObject.setParameter("colorName", "yellow").getSingleResult(); 122 | 123 | /* Ensure that the object obtained is the right one */ 124 | Assert.assertNotNull(c); 125 | Assert.assertEquals(c.getFriendlyName(), "yellow"); 126 | Assert.assertEquals(c.getRed(), 213); 127 | Assert.assertEquals(c.getGreen(), 242); 128 | Assert.assertEquals(c.getBlue(), 26); 129 | } finally { 130 | if (entityManager != null && entityManager.isOpen()) { 131 | entityManager.close(); 132 | } 133 | } 134 | ``` 135 | 136 | ### References 137 | 138 | - [SQLi and JPA](https://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-persistence-api-jpa) 139 | 140 | ## Operating System 141 | 142 | ### Symptom 143 | 144 | Injection of this type occur when the application use untrusted user input to build a Operating System command using a String and execute it. 145 | 146 | ### How to prevent 147 | 148 | Use technology stack **API** in order to prevent injection. 149 | 150 | ### Example 151 | 152 | ``` java 153 | /* The context taken is, for example, to perform a PING against a computer. 154 | * The prevention is to use the feature provided by the Java API instead of building 155 | * a system command as String and execute it */ 156 | InetAddress host = InetAddress.getByName("localhost"); 157 | Assert.assertTrue(host.isReachable(5000)); 158 | ``` 159 | 160 | ### References 161 | 162 | - [Command Injection](https://www.owasp.org/index.php/Command_Injection) 163 | 164 | ## XML: XPath Injection 165 | 166 | ### Symptom 167 | 168 | Injection of this type occur when the application use untrusted user input to build a XPath query using a String and execute it. 169 | 170 | ### How to prevent 171 | 172 | Use **XPath Variable Resolver** in order to prevent injection. 173 | 174 | ### Example 175 | 176 | **Variable Resolver** implementation. 177 | 178 | ``` java 179 | /** 180 | * Resolver in order to define parameter for XPATH expression. 181 | * 182 | */ 183 | public class SimpleVariableResolver implements XPathVariableResolver { 184 | 185 | private final Map vars = new HashMap(); 186 | 187 | /** 188 | * External methods to add parameter 189 | * 190 | * @param name Parameter name 191 | * @param value Parameter value 192 | */ 193 | public void addVariable(QName name, Object value) { 194 | vars.put(name, value); 195 | } 196 | 197 | /** 198 | * {@inheritDoc} 199 | * 200 | * @see javax.xml.xpath.XPathVariableResolver#resolveVariable(javax.xml.namespace.QName) 201 | */ 202 | public Object resolveVariable(QName variableName) { 203 | return vars.get(variableName); 204 | } 205 | } 206 | ``` 207 | 208 | Code using it to perform XPath query. 209 | 210 | ``` java 211 | /*Create a XML document builder factory*/ 212 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 213 | 214 | /*Disable External Entity resolution for differents cases*/ 215 | //Do not performed here in order to focus on variable resolver code 216 | //but do it for production code ! 217 | 218 | /*Load XML file*/ 219 | DocumentBuilder builder = dbf.newDocumentBuilder(); 220 | Document doc = builder.parse(new File("src/test/resources/SampleXPath.xml")); 221 | 222 | /* Create and configure parameter resolver */ 223 | String bid = "bk102"; 224 | SimpleVariableResolver variableResolver = new SimpleVariableResolver(); 225 | variableResolver.addVariable(new QName("bookId"), bid); 226 | 227 | /*Create and configure XPATH expression*/ 228 | XPath xpath = XPathFactory.newInstance().newXPath(); 229 | xpath.setXPathVariableResolver(variableResolver); 230 | XPathExpression xPathExpression = xpath.compile("//book[@id=$bookId]"); 231 | 232 | /* Apply expression on XML document */ 233 | Object nodes = xPathExpression.evaluate(doc, XPathConstants.NODESET); 234 | NodeList nodesList = (NodeList) nodes; 235 | Assert.assertNotNull(nodesList); 236 | Assert.assertEquals(1, nodesList.getLength()); 237 | Element book = (Element)nodesList.item(0); 238 | Assert.assertTrue(book.getTextContent().contains("Ralls, Kim")); 239 | ``` 240 | 241 | ### References 242 | 243 | - [XPATH Injection](https://www.owasp.org/index.php/XPATH_Injection) 244 | 245 | ## HTML/JavaScript/CSS 246 | 247 | ### Symptom 248 | 249 | Injection of this type occur when the application use untrusted user input to build a HTTP response and sent it to browser. 250 | 251 | ### How to prevent 252 | 253 | Either apply strict input validation (whitelist approach) or use output sanitizing+escaping if input validation is not possible (combine both every time is possible). 254 | 255 | ### Example 256 | 257 | ``` java 258 | /* 259 | INPUT WAY: Receive data from user 260 | Here it's recommended to use strict input validation using whitelist approach. 261 | In fact, you ensure that only allowed characters are part of the input received. 262 | */ 263 | 264 | String userInput = "You user login is owasp-user01"; 265 | 266 | /* First we check that the value contains only expected character*/ 267 | Assert.assertTrue(Pattern.matches("[a-zA-Z0-9\\s\\-]{1,50}", userInput)); 268 | 269 | /* If the first check pass then ensure that potential dangerous character 270 | that we have allowed for business requirement are not used in a dangerous way. 271 | For example here we have allowed the character '-', and, this can 272 | be used in SQL injection so, we 273 | ensure that this character is not used is a continuous form. 274 | Use the API COMMONS LANG v3 to help in String analysis... 275 | */ 276 | Assert.assertEquals(0, StringUtils.countMatches(userInput.replace(" ", ""), "--")); 277 | 278 | /* 279 | OUTPUT WAY: Send data to user 280 | Here we escape + sanitize any data sent to user 281 | Use the OWASP Java HTML Sanitizer API to handle sanitizing 282 | Use the OWASP Java Encoder API to handle HTML tag encoding (escaping) 283 | */ 284 | 285 | String outputToUser = "You

user login

is owasp-user01"; 286 | outputToUser += ""; 287 | 288 | /* Create a sanitizing policy that only allow tag '

' and ''*/ 289 | PolicyFactory policy = new HtmlPolicyBuilder().allowElements("p", "strong").toFactory(); 290 | 291 | /* Sanitize the output that will be sent to user*/ 292 | String safeOutput = policy.sanitize(outputToUser); 293 | 294 | /* Encode HTML Tag*/ 295 | safeOutput = Encode.forHtml(safeOutput); 296 | String finalSafeOutputExpected = "You

user login

is owasp-user01"; 297 | Assert.assertEquals(finalSafeOutputExpected, safeOutput); 298 | ``` 299 | 300 | ### References 301 | 302 | - [XSS](https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)) 303 | - [OWASP Java HTML Sanitizer](https://github.com/owasp/java-html-sanitizer) 304 | - [OWASP Java Encoder](https://github.com/owasp/owasp-java-encoder) 305 | - [Java RegEx](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) 306 | 307 | ## LDAP 308 | 309 | A dedicated [cheatsheet](LDAP_Injection_Prevention_Cheat_Sheet.md) has been created. 310 | 311 | ## NoSQL 312 | 313 | ### Symptom 314 | 315 | Injection of this type occur when the application use untrusted user input to build a NoSQL API call expression. 316 | 317 | ### How to prevent 318 | 319 | As there many NoSQL database system and each one use a API for call, it's important to ensure that user input received and used to build the API call expression do not contains any character that have a special meaning in the target API syntax. This in order to avoid that it will be used to escape the initial call expression in order to create another one based on crafted user input. It's also important to not use string concatenation to build API call expression but use the API to create the expression. 320 | 321 | ### Example - MongoDB 322 | 323 | ``` java 324 | /* Here use MongoDB as target NoSQL DB */ 325 | String userInput = "Brooklyn"; 326 | 327 | /* First ensure that the input do no contains any special characters 328 | for the current NoSQL DB call API, 329 | here they are: ' " \ ; { } $ 330 | */ 331 | //Avoid regexp this time in order to made validation code 332 | //more easy to read and understand... 333 | ArrayList specialCharsList = new ArrayList() { { 334 | add("'"); 335 | add("\""); 336 | add("\\"); 337 | add(";"); 338 | add("{"); 339 | add("}"); 340 | add("$"); 341 | } }; 342 | specialCharsList.forEach(specChar -> Assert.assertFalse(userInput.contains(specChar))); 343 | //Add also a check on input max size 344 | Assert.assertTrue(userInput.length() <= 50); 345 | 346 | /* Then perform query on database using API to build expression */ 347 | //Connect to the local MongoDB instance 348 | try(MongoClient mongoClient = new MongoClient()){ 349 | MongoDatabase db = mongoClient.getDatabase("test"); 350 | //Use API query builder to create call expression 351 | //Create expression 352 | Bson expression = eq("borough", userInput); 353 | //Perform call 354 | FindIterable restaurants = db.getCollection("restaurants").find(expression); 355 | //Verify result consistency 356 | restaurants.forEach(new Block() { 357 | @Override 358 | public void apply(final org.bson.Document doc) { 359 | String restBorough = (String)doc.get("borough"); 360 | Assert.assertTrue("Brooklyn".equals(restBorough)); 361 | } 362 | }); 363 | } 364 | ``` 365 | 366 | ### References 367 | 368 | - [Testing for NoSQL injection](https://www.owasp.org/index.php/Testing_for_NoSQL_injection) 369 | - [SQL and NoSQL Injection](https://ckarande.gitbooks.io/owasp-nodegoat-tutorial/content/tutorial/a1_-_sql_and_nosql_injection.html) 370 | - [No SQL, No Injection?](https://arxiv.org/ftp/arxiv/papers/1506/1506.04082.pdf) 371 | 372 | ## Log Injection 373 | 374 | ### Symptom 375 | 376 | [Log Injection](https://www.owasp.org/index.php/Log_Injection) occurs when an application includes untrusted data in an application log message (e.g., an attacker can cause an additional log entry that looks like it came from a completely different user, if they can inject CRLF characters in the untrusted data). More information about this attack is available on the OWASP [Log Injection](https://www.owasp.org/index.php/Log_Injection) page. 377 | 378 | ### How to prevent 379 | 380 | To prevent an attacker from writing malicious content into the application log, apply defenses such as: 381 | 382 | - Filter the user input used to prevent injection of **C**arriage **R**eturn (CR) or **L**ine **F**eed (LF) characters. 383 | - Limit the size of the user input value used to create the log message. 384 | - Make sure [all XSS defenses](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) are applied when viewing log files in a web browser. 385 | 386 | ### Example using Log4j2 387 | 388 | Configuration of a logging policy to roll on 10 files of 5MB each, and encode/limit the log message using the [Pattern *encode{}{CRLF}*](https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout\%7CLog4j2), introduced in [Log4j2 v2.10.0](https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api), and the *-500m* message size limit.: 389 | 390 | ``` xml 391 | 392 | 393 | 394 | 395 | 396 | 398 | %d{ISO8601} %-5p - %encode{ %.-500m }{CRLF}%n 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | ``` 413 | 414 | Usage of the logger at code level: 415 | 416 | ``` java 417 | import org.apache.logging.log4j.LogManager; 418 | import org.apache.logging.log4j.Logger; 419 | ... 420 | // No special action needed because security actions are 421 | // performed at the logging policy level 422 | Logger logger = LogManager.getLogger(MyClass.class); 423 | logger.info(logMessage); 424 | ... 425 | ``` 426 | 427 | ### Example using Logback with the OWASP Security Logging library 428 | 429 | Configuration of a logging policy to roll on 10 files of 5MB each, and encode/limit the log message using the [CRLFConverter](https://github.com/javabeanz/owasp-security-logging/wiki/Log-Forging), provided by the [OWASP Security Logging Project](https://www.owasp.org/index.php/OWASP_Security_Logging_Project), and the *-500msg* message size limit: 430 | 431 | ``` xml 432 | 433 | 434 | 435 | 436 | 437 | App.log 438 | 439 | App-%i.log 440 | 1 441 | 10 442 | 443 | 444 | 5MB 445 | 446 | 447 | 449 | %relative [%thread] %-5level %logger{35} - %crlf(%.-500msg) %n 450 | 451 | 452 | 453 | 454 | 455 | 456 | ``` 457 | 458 | You also have to add the [OWASP Security Logging](https://github.com/javabeanz/owasp-security-logging/wiki/Usage-with-Logback) dependency to your project. 459 | 460 | Usage of the logger at code level: 461 | 462 | ``` java 463 | import org.slf4j.Logger; 464 | import org.slf4j.LoggerFactory; 465 | ... 466 | // No special action needed because security actions 467 | // are performed at the logging policy level 468 | Logger logger = LoggerFactory.getLogger(MyClass.class); 469 | logger.info(logMessage); 470 | ... 471 | ``` 472 | 473 | ### References 474 | 475 | - [PatternLayout](https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout) (See the `encode{}{CRLF}` function) 476 | 477 | ```text 478 | Note that the default Log4j2 encode{} encoder is HTML, which does NOT prevent log injection. 479 | 480 | It prevents XSS attacks against viewing logs using a browser. 481 | 482 | OWASP recommends defending against XSS attacks in such situations in the log viewer application itself, 483 | not by preencoding all the log messages with HTML encoding as such log entries may be used/viewed in many 484 | other log viewing/analysis tools that don't expect the log data to be pre-HTML encoded. 485 | ``` 486 | 487 | - [LOG4J Configuration](https://logging.apache.org/log4j/2.x/manual/configuration.html) 488 | - [LOG4J Appender](https://logging.apache.org/log4j/2.x/manual/appenders.html) 489 | - [Log Forging](https://github.com/javabeanz/owasp-security-logging/wiki/Log-Forging) - See the Logback section about the `CRLFConverter` this library provides. 490 | - [Usage of OWASP Security Logging with Logback](https://github.com/javabeanz/owasp-security-logging/wiki/Usage-with-Logback) 491 | 492 | # Authors and Primary Editors 493 | 494 | Dominique Righetto - dominique.righetto@owasp.org 495 | 496 | Dave Wichers - dave.wichers@owasp.org 497 | -------------------------------------------------------------------------------- /Injection_Prevention_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This article is focused on providing clear, simple, actionable guidance for preventing the entire category of Injection flaws in your applications. Injection attacks, especially [SQL Injection](https://www.owasp.org/index.php/SQL_Injection), are unfortunately very common. 4 | 5 | Application accessibility is a very important factor in protection and prevention of injection flaws. Only the minority of all applications within a company/enterprise are developed in house, where as most applications are from external sources. Open source applications give at least the opportunity to fix problems, but closed source applications need a different approach to injection flaws. 6 | 7 | Injection flaws occur when an application sends untrusted data to an interpreter. Injection flaws are very prevalent, particularly in legacy code, often found in SQL queries, LDAP queries, XPath queries, OS commands, program arguments, etc. Injection flaws are easy to discover when examining code, but more difficult via testing. Scanners and fuzzers can help attackers find them. 8 | 9 | Depending on the accessibility different actions must be taken in order to fix them. It is always the best way to fix the problem in source code itself, or even redesign some parts of the applications. But if the source code is not available or it is simply uneconomical to fix legacy software only virtual patching makes sense. 10 | 11 | # Application Types 12 | 13 | Three classes of applications can usually be seen within a company. Those 3 types are needed to identify the actions which need to take place in order to prevent/fix injection flaws. 14 | 15 | ## A1: New Application 16 | 17 | A new web application in the design phase, or in early stage development. 18 | 19 | ## A2: Productive Open Source Application 20 | 21 | An already productive application, which can be easily adapted. A Model-View-Controller (MVC) type application is just one example of having a easily accessible application architecture. 22 | 23 | ## A3: Productive Closed Source Application 24 | 25 | A productive application which cannot or only with difficulty be modified. 26 | 27 | # Forms of Injection 28 | 29 | There are several forms of injection targeting different technologies including SQL queries, LDAP queries, XPath queries and OS commands. 30 | 31 | ## Query languages 32 | 33 | The most famous form of injection is SQL Injection where an attacker can modify existing database queries. For more information see the [SQL Injection Prevention Cheat Sheet](SQL_Injection_Prevention_Cheat_Sheet.md). 34 | 35 | But also LDAP, SOAP, XPath and REST based queries can be susceptible to injection attacks allowing for data retrieval or control bypass. 36 | 37 | ### SQL Injection 38 | 39 | An SQL injection attack consists of insertion or "injection" of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. 40 | 41 | A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands. 42 | 43 | SQL Injection attacks can be divided into the following three classes: 44 | 45 | - **Inband:** data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page. 46 | - **Out-of-band:** data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester). 47 | - **Inferential or Blind:** there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server. 48 | 49 | #### How to test for the issue? 50 | 51 | **During code review** 52 | 53 | please check for any queries to the database are not done via prepared statements. 54 | 55 | If dynamic statements are being made please check if the data is sanitized before used as par of the statement. 56 | 57 | Auditors should always look for uses of sp_execute, execute or exec within SQL Server stored procedures. Similar audit guidelines are necessary for similar functions for other vendors. 58 | 59 | **Automated Exploitation** 60 | 61 | Most of the situation and techniques below here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using [SQLMap](https://www.owasp.org/index.php/Automated_Audit_using_SQLMap) 62 | 63 | Equally Static Code Analysis Data flow rules can detect of unsanitized user controlled input can change the SQL query. 64 | 65 | **Stored Procedure Injection** 66 | 67 | When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure. 68 | 69 | **Time delay Exploitation technique** 70 | 71 | The time delay exploitation technique is very useful when the tester find a Blind SQL Injection situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section). 72 | 73 | ```text 74 | http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))-- 75 | ``` 76 | 77 | In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds. 78 | 79 | **Out of band Exploitation technique** 80 | 81 | This technique is very useful when the tester find a Blind SQL Injection situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section. 82 | 83 | #### Remediation 84 | 85 | **Defense Option 1: Prepared Statements (with Parameterized Queries)** 86 | 87 | Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of `tom' or '1'='1`, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string `tom' or '1'='1`. 88 | 89 | **Defense Option 2: Stored Procedures** 90 | 91 | The difference between prepared statements and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, and then called from the application. 92 | 93 | Both of these techniques have the same effectiveness in preventing SQL injection so your organization should choose which approach makes the most sense for you. Stored procedures are not always safe from SQL injection. However, certain standard stored procedure programming constructs have the same effect as the use of parameterized queries when implemented safely* which is the norm for most stored procedure languages. 94 | 95 | *Note:* 'Implemented safely' means the stored procedure does not include any unsafe dynamic SQL generation. 96 | 97 | **Defense Option 3: White List Input Validation** 98 | 99 | Various parts of SQL queries aren't legal locations for the use of bind variables, such as the names of tables or columns, and the sort order indicator (ASC or DESC). In such situations, input validation or query redesign is the most appropriate defense. For the names of tables or columns, ideally those values come from the code, and not from user parameters. 100 | 101 | But if user parameter values are used to make different for table names and column names, then the parameter values should be mapped to the legal/expected table or column names to make sure unvalidated user input doesn't end up in the query. Please note, this is a symptom of poor design and a full re-write should be considered if time allows. 102 | 103 | **Defense Option 4: Escaping All User-Supplied Input** 104 | 105 | This technique should only be used as a last resort, when none of the above are feasible. Input validation is probably a better choice as this methodology is frail compared to other defenses and we cannot guarantee it will prevent all SQL Injection in all situations. 106 | 107 | This technique is to escape user input before putting it in a query. It's usually only recommended to retrofit legacy code when implementing input validation isn't cost effective. 108 | 109 | #### Example code - Java 110 | 111 | **Safe Java Prepared Statement Example** 112 | 113 | The following code example uses a `PreparedStatement`, Java's implementation of a parameterized query, to execute the same database query. 114 | 115 | ```java 116 | // This should REALLY be validated too 117 | String custname = request.getParameter("customerName"); 118 | // Perform input validation to detect attacks 119 | String query = "SELECT account_balance FROM user_data WHERE user_name = ?"; 120 | PreparedStatement pstmt = connection.prepareStatement(query); 121 | pstmt.setString(1, custname); 122 | ResultSet results = pstmt.executeQuery(); 123 | ``` 124 | 125 | We have shown examples in Java, but practically all other languages, including Cold Fusion, and Classic ASP, support parameterized query interfaces. 126 | 127 | **Safe Java Stored Procedure Example** 128 | 129 | The following code example uses a `CallableStatement`, Java's implementation of the stored procedure interface, to execute the same database query. The `sp_getAccountBalance` stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. 130 | 131 | ```java 132 | // This should REALLY be validated 133 | String custname = request.getParameter("customerName"); 134 | try { 135 | CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance(?)}"); 136 | cs.setString(1, custname); 137 | ResultSet results = cs.executeQuery(); 138 | // Result set handling... 139 | } catch (SQLException se) { 140 | // Logging and error handling... 141 | } 142 | ``` 143 | 144 | ### LDAP Injection 145 | 146 | LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements through techniques similar to [SQL Injection](https://www.owasp.org/index.php/SQL_Injection). LDAP injection attacks could result in the granting of permissions to unauthorized queries, and content modification inside the LDAP tree. For more information on LDAP Injection attacks, visit [LDAP injection](https://www.owasp.org/index.php/LDAP_injection). 147 | 148 | [LDAP injection](https://www.owasp.org/index.php/LDAP_injection) attacks are common due to two factors: 149 | 150 | 1. The lack of safer, parameterized LDAP query interfaces 151 | 2. The widespread use of LDAP to authenticate users to systems. 152 | 153 | #### How to test for the issue? 154 | 155 | **During code review** 156 | 157 | Please check for any queries to the LDAP escape special characters, see [here](LDAP_Injection_Prevention_Cheat_Sheet.md#defense-option-1-escape-all-variables-using-the-right-ldap-encoding-function). 158 | 159 | **Automated Exploitation** 160 | 161 | Scanner module of tool like OWASP [ZAP](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project) have module to detect LDAP injection issue. 162 | 163 | #### Remediation 164 | 165 | **Escape all variables using the right LDAP encoding function** 166 | 167 | The main way LDAP stores names is based on DN ([distinguished name](https://ldapwiki.com/wiki/Distinguished%20Names)). You can think of this like a unique identifier. These are sometimes used to access resources, like a username. 168 | 169 | A DN might look like this 170 | 171 | ```text 172 | cn=Richard Feynman, ou=Physics Department, dc=Caltech, dc=edu 173 | ``` 174 | 175 | or 176 | 177 | ```text 178 | uid=inewton, ou=Mathematics Department, dc=Cambridge, dc=com 179 | ``` 180 | 181 | There are certain characters that are considered special characters in a DN. The exhaustive list is the following: `\ # + < > , ; " =` and leading or trailing spaces 182 | 183 | Each DN points to exactly 1 entry, which can be thought of sort of like a row in a RDBMS. For each entry, there will be 1 or more attributes which are analogous to RDBMS columns. If you are interested in searching through LDAP for users will certain attributes, you may do so with search filters. In a search filter, you can use standard boolean logic to get a list of users matching an arbitrary constraint. Search filters are written in Polish notation AKA prefix notation. 184 | 185 | Example: 186 | 187 | ```text 188 | (&(ou=Physics)(| (manager=cn=Freeman Dyson,ou=Physics,dc=Caltech,dc=edu) 189 | (manager=cn=Albert Einstein,ou=Physics,dc=Princeton,dc=edu) )) 190 | ``` 191 | 192 | When building LDAP queries in application code, you MUST escape any untrusted data that is added to any LDAP query. There are two forms of LDAP escaping. Encoding for LDAP Search and Encoding for LDAP DN (distinguished name). The proper escaping depends on whether you are sanitizing input for a search filter, or you are using a DN as a username-like credential for accessing some resource. 193 | 194 | #### Example code - Java 195 | 196 | **Safe Java for LDAP escaping Example** 197 | 198 | ```java 199 | public String escapeDN (String name) { 200 | //From RFC 2253 and the / character for JNDI 201 | final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'}; 202 | String escapedStr = new String(name); 203 | //Backslash is both a Java and an LDAP escape character, 204 | //so escape it first 205 | escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\"); 206 | //Positional characters - see RFC 2253 207 | escapedStr = escapedStr.replaceAll("\^#","\\\\\\\\#"); 208 | escapedStr = escapedStr.replaceAll("\^ | $","\\\\\\\\ "); 209 | for (int i=0 ; i < META_CHARS.length ; i++) { 210 | escapedStr = escapedStr.replaceAll("\\\\" + 211 | META_CHARS[i],"\\\\\\\\" + META_CHARS[i]); 212 | } 213 | return escapedStr; 214 | } 215 | ``` 216 | 217 | Note, that the backslash character is a Java String literal and a regular expression escape character. 218 | 219 | ```java 220 | public String escapeSearchFilter (String filter) { 221 | //From RFC 2254 222 | String escapedStr = new String(filter); 223 | escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\5c"); 224 | escapedStr = escapedStr.replaceAll("\\\\\*","\\\\\\\\2a"); 225 | escapedStr = escapedStr.replaceAll("\\\\(","\\\\\\\\28"); 226 | escapedStr = escapedStr.replaceAll("\\\\)","\\\\\\\\29"); 227 | escapedStr = escapedStr.replaceAll("\\\\" + 228 | Character.toString('\\u0000'), "\\\\\\\\00"); 229 | return escapedStr; 230 | } 231 | ``` 232 | 233 | ### XPath Injection 234 | 235 | TODO 236 | 237 | ## Scripting languages 238 | 239 | All scripting languages used in web applications have a form of an `eval` call which receives code at runtime and executes it. If code is crafted using unvalidated and unescaped user input code injection can occur which allows an attacker to subvert application logic and eventually to gain local access. 240 | 241 | Every time a scripting language is used, the actual implementation of the 'higher' scripting language is done using a 'lower' language like C. If the scripting language has a flaw in the data handling code '[Null Byte Injection](http://projects.webappsec.org/w/page/13246949/Null%20Byte%20Injection)' attack vectors can be deployed to gain access to other areas in memory, which results in a successful attack. 242 | 243 | ## Operating System Commands 244 | 245 | OS command injection is a technique used via a web interface in order to execute OS commands on a web server. The user supplies operating system commands through a web interface in order to execute OS commands. 246 | 247 | Any web interface that is not properly sanitized is subject to this exploit. With the ability to execute OS commands, the user can upload malicious programs or even obtain passwords. OS command injection is preventable when security is emphasized during the design and development of applications. 248 | 249 | ### How to test for the issue? 250 | 251 | **During code review** 252 | 253 | Check if any command execute methods are called and in unvalidated user input are taken as data for that command. 254 | 255 | Out side of that, appending a semicolon to the end of a URL query parameter followed by an operating system command, will execute the command. `%3B` is url encoded and decodes to semicolon. This is because the `;` is interpreted as a command separator. 256 | 257 | Example: `http://sensitive/something.php?dir=%3Bcat%20/etc/passwd` 258 | 259 | If the application responds with the output of the `/etc/passwd` file then you know the attack has been successful. Many web application scanners can be used to test for this attack as they inject variations of command injections and test the response. 260 | 261 | Equally Static Code Analysis tools check the data flow of untrusted user input into a web application and check if the data is then entered into a dangerous method which executes the user input as a command. 262 | 263 | ### Remediation 264 | 265 | If it is considered unavoidable the call to a system command incorporated with user-supplied, the following two layers of defense should be used within software in order to prevent attacks 266 | 267 | 1. **Parametrization** - If available, use structured mechanisms that automatically enforce the separation between data and command. These mechanisms can help to provide the relevant quoting, encoding. 268 | 2. **Input validation** - the values for commands and the relevant arguments should be both validated. There are different degrees of validation for the actual command and its arguments: 269 | - When it comes to the **commands** used, these must be validated against a whitelist of allowed commands. 270 | - In regards to the **arguments** used for these commands, they should be validated using the following options: 271 | - Positive or “whitelist” input validation - where are the arguments allowed explicitly defined 272 | - White list Regular Expression - where is explicitly defined a whitelist of good characters allowed and the maximum length of the string. Ensure that metacharacters like `& | ; $ > < \` \ !` and white-spaces are not part of the Regular Expression. For example, the following regular expression only allows lowercase letters and numbers, and does not contain metacharacters. The length is also being limited to 3-10 characters: 273 | 274 | `^[a-z0-9]{3,10}$` 275 | 276 | ### Example code - Java 277 | 278 | **Incorrect Usage** 279 | 280 | ```java 281 | ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2"); 282 | ``` 283 | 284 | In this example, the command together with the arguments are passed as a one string, making easy to manipulate that expression and inject malicious strings. 285 | 286 | **Correct Usage** 287 | 288 | Here is an example that starts a process with a modified working directory. The command and each of the arguments are passed separately. This make it easy to validated each term and reduces the risk to insert malicious strings. 289 | 290 | ```java 291 | ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "TrustedArg1", "TrustedArg2"); 292 | Map env = pb.environment(); 293 | pb.directory(new File("TrustedDir")); 294 | Process p = pb.start(); 295 | ``` 296 | 297 | ## Network Protocols 298 | 299 | Web applications often communicate with network daemons (like SMTP, IMAP, FTP) where user input becomes part of the communication stream. Here it is possible to inject command sequences to abuse an established session. 300 | 301 | # Injection Prevention Rules 302 | 303 | ## Rule \#1 (Perform proper input validation): 304 | 305 | Perform proper input validation. Positive or “whitelist” input validation with appropriate canonicalization is also recommended, but **is not a complete defense** as many applications require special characters in their input. 306 | 307 | ## Rule \#2 (Use a safe API): 308 | 309 | The preferred option is to use a safe API which avoids the use of the interpreter entirely or provides a parameterized interface. Be careful of APIs, such as stored procedures, that are parameterized, but can still introduce injection under the hood. 310 | 311 | ## Rule \#3 (Contextually escape user data): 312 | 313 | If a parameterized API is not available, you should carefully escape special characters using the specific escape syntax for that interpreter. 314 | 315 | # Other Injection Cheatsheets 316 | 317 | [SQL Injection Prevention Cheat Sheet](SQL_Injection_Prevention_Cheat_Sheet.md) 318 | 319 | [OS Command Injection Defense Cheat Sheet](OS_Command_Injection_Defense_Cheat_Sheet.md) 320 | 321 | [LDAP Injection Prevention Cheat Sheet](LDAP_Injection_Prevention_Cheat_Sheet.md) 322 | 323 | [Injection Prevention Cheat Sheet in Java](Injection_Prevention_Cheat_Sheet_in_Java.md) 324 | 325 | # Authors and Primary Editors 326 | 327 | Jim Manico - jim@owasp.org 328 | 329 | Alexander Meisel - alexander.meisel@owasp.org 330 | 331 | Erlend Oftedal - erlend.oftedal@owasp.org 332 | 333 | Sherif Mansour - sherif.mansour@owasp.org 334 | -------------------------------------------------------------------------------- /Mobile_App_Pen_Test.md: -------------------------------------------------------------------------------- 1 | ## Mobile Application Penetration Testing Cheat Sheet 2 | 3 | The Mobile App Pentest cheat sheet was created to provide concise collection of high value information on specific mobile application penetration testing topics and checklist, which is mapped OWASP Mobile Risk Top 10 for conducting pentest. 4 | 5 | - [Mobile Application Security Testing Distributions](#mobile-application-security-testing-distributions) 6 | - [All-in-one Mobile Security Frameworks](#all-in-one-mobile-security-frameworks) 7 | - [Android Application Penetration Testing](#android-application-penetration-testing) 8 | - [Reverse Engineering and Static Analysis](#reverse-engineering-and-static-analysis) 9 | - [Dynamic and Runtime Analysis](#dynamic-and-runtime-analysis) 10 | - [Network Analysis and Server Side Testing](#network-analysis-and-server-side-testing) 11 | - [Bypassing Root Detection and SSL Pinning](#bypassing-root-detection-and-ssl-pinning) 12 | - [Security Libraries](#security-libraries) 13 | - [iOS Application Penetration Testing](#ios-application-penetration-testing) 14 | - [Access Filesystem on iDevice](#access-filesystem-on-idevice) 15 | - [Reverse Engineering and Static Analysis](#reverse-engineering-and-static-analysis) 16 | - [Dynamic and Runtime Analysis](#dynamic-and-runtime-analysis) 17 | - [Network Analysis and Server Side Testing](#network-analysis-and-server-side-testing) 18 | - [Bypassing Root Detection and SSL Pinning](#bypassing-root-detection-and-ssl-pinning) 19 | - [Security Libraries](#security-libraries) 20 | - [Contribution](#contribution) 21 | - [License](#license) 22 | 23 | #### Mobile Application Security Testing Distributions 24 | * [Appie](https://manifestsecurity.com/appie) - A portable software package for Android Pentesting and an awesome alternative to existing Virtual machines. 25 | * [Android Tamer](https://androidtamer.com/) - Android Tamer is a Virtual / Live Platform for Android Security professionals. 26 | * [AppUse](https://appsec-labs.com/AppUse/) - AppUse is a VM (Virtual Machine) developed by AppSec Labs. 27 | * [Androl4b](https://github.com/sh4hin/Androl4b) - A Virtual Machine For Assessing Android applications, Reverse Engineering and Malware Analysis 28 | * [Mobisec](http://sourceforge.net/projects/mobisec/) - Mobile security testing live environment. 29 | * [Santoku](https://santoku-linux.com/) - Santoku is an OS and can be run outside a VM as a standalone operating system. 30 | * [Vezir Project](https://github.com/oguzhantopgul/Vezir-Project) - Mobile Application Pentesting and Malware Analysis Environment. 31 | 32 | ### All-in-One Mobile Security Frameworks 33 | * [Mobile Security Framework - MobSF](https://github.com/ajinabraham/Mobile-Security-Framework-MobSF) - Mobile Security Framework is an intelligent, all-in-one open source mobile application (Android/iOS) automated pen-testing framework capable of performing static and dynamic analysis. 34 | * `python manage.py runserver 127.0.0.1:1337` 35 | * [Needle](https://github.com/mwrlabs/needle) - Needle is an open source, modular framework to streamline the process of conducting security assessments of iOS apps including Binary Analysis, Static Code Analysis, Runtime Manipulation using Cycript and Frida hooking, and so on. 36 | * [Objection](https://github.com/sensepost/objection) - Objection is a runtime mobile exploration toolkit, powered by Frida. It was built with the aim of helping assess mobile applications and their security posture without the need for a jailbroken or rooted mobile device. 37 | 38 | ### Android Application Penetration Testing 39 | #### Reverse Engineering and Static Analysis 40 | * [APKInspector](https://github.com/honeynet/apkinspector/) - APKinspector is a powerful GUI tool for analysts to analyze the Android applications. 41 | * [APKTool](http://ibotpeaches.github.io/Apktool/) - A tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications. 42 | * Disassembling Android apk file 43 | * `apktool d ` 44 | * Rebuilding decoded resources back to binary APK/JAR with certificate signing 45 | * `apktool b ` 46 | * `keytool -genkey -v -keystore keys/test.keystore -alias Test -keyalg RSA -keysize 1024 -sigalg SHA1withRSA -validity 10000` 47 | * `jarsigner -keystore keys/test.keystore dist/test.apk -sigalg SHA1withRSA -digestalg SHA1 Test` 48 | * [Sign](https://github.com/appium/sign) - Sign.jar automatically signs an apk with the Android test certificate. 49 | * [Bytecode Viewer](https://github.com/Konloch/bytecode-viewer) - Bytecode Viewer is an Advanced Lightweight Java Bytecode Viewer, It's written completely in Java, and it's open sourced. 50 | * [Jadx](https://github.com/skylot/jadx) - Dex to Java decompiler: Command line and GUI tools for produce Java source code from Android Dex and Apk files. 51 | * [Oat2dex](https://github.com/testwhat/SmaliEx) - A tool for converting .oat file to .dex files. 52 | * Deoptimize boot classes (The output will be in "odex" and "dex" folders) 53 | * `java -jar oat2dex.jar boot ` 54 | * Deoptimize application 55 | * `java -jar oat2dex.jar ` 56 | * Get odex from oat 57 | * `java -jar oat2dex.jar odex ` 58 | * Get odex smali (with optimized opcode) from oat/odex 59 | * `java -jar oat2dex.jar smali ` 60 | * [FindBugs](http://findbugs.sourceforge.net/) + [FindSecurityBugs](http://h3xstream.github.io/find-sec-bugs/) - FindSecurityBugs is a extension for FindBugs which include security rules for Java applications. 61 | * [Qark](https://github.com/linkedin/qark) - This tool is designed to look for several security related Android application vulnerabilities, either in source code or packaged APKs. 62 | * [SUPER](https://github.com/SUPERAndroidAnalyzer/super) - SUPER is a command-line application that can be used in Windows, MacOS X and Linux, that analyzes .apk files in search for vulnerabilities. It does this by decompressing APKs and applying a series of rules to detect those vulnerabilities. 63 | * [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework) - AndroBugs Framework is an efficient Android vulnerability scanner that helps developers or hackers find potential security vulnerabilities in Android applications. No need to install on Windows. 64 | * [Simplify](https://github.com/CalebFenton/simplify) - A tool for de-obfuscating android package into Classes.dex which can be use Dex2jar and JD-GUI to extract contents of dex file. 65 | * `simplify.jar -i "input smali files or folder" -o ` 66 | * [ClassNameDeobfuscator](https://github.com/HamiltonianCycle/ClassNameDeobfuscator) - Simple script to parse through the .smali files produced by apktool and extract the .source annotation lines. 67 | * [Android backup extractor](https://github.com/nelenkov/android-backup-extractor) - Utility to extract and repack Android backups created with adb backup (ICS+). Largely based on BackupManagerService.java from AOSP. 68 | Tip !! "adb backup" command can also be used for extracting application package with the following command: 69 | * `adb backup ` 70 | * `dd if=backup.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" > backup.tar` 71 | 72 | #### Dynamic and Runtime Analysis 73 | * [Cydia Substrate](http://www.cydiasubstrate.com/) - Cydia Substrate for Android enables developers to make changes to existing software with Substrate extensions that are injected in to the target process's memory. 74 | * [Xposed Framework](http://forum.xda-developers.com/xposed/xposed-installer-versions-changelog-t2714053) - Xposed framework enables you to modify the system or application aspect and behaviour at runtime, without modifying any Android application package(APK) or re-flashing. 75 | * [logcat-color](https://github.com/marshall/logcat-color) - A colorful and highly configurable alternative to the adb logcat command from the Android SDK. 76 | * [Inspeckage](https://github.com/ac-pm/Inspeckage) - Inspeckage is a tool developed to offer dynamic analysis of Android applications. By applying hooks to functions of the Android API, Inspeckage will help you understand what an Android application is doing at runtime. 77 | * [Frida](http://www.frida.re/) - The toolkit works using a client-server model and lets you inject in to running processes not just on Android, but also on iOS, Windows and Mac. 78 | * [Diff-GUI](https://github.com/antojoseph/diff-gui) - A Web framework to start instrumenting with the avaliable modules, hooking on native, inject JavaScript using Frida. 79 | * [House](https://github.com/nccgroup/house) - A runtime mobile application analysis toolkit with a Web GUI, powered by Frida, is designed for helping assess mobile applications by implementing dynamic function hooking and intercepting and intended to make Frida script writing as simple as possible. 80 | * [AndBug](https://github.com/swdunlop/AndBug) - AndBug is a debugger targeting the Android platform's Dalvik virtual machine intended for reverse engineers and developers. 81 | * Identifying application process using adb shell 82 | * `adb shell ps | grep -i "App keyword"` 83 | * Accessing the application using AndBug in order to identify loaded classes 84 | * `andbug shell -p ` 85 | * Tracing specific class 86 | * `ct ` 87 | * Debugging with jdb 88 | * `adb forward tcp: jdwp:` 89 | * `jdb -attach localhost:` 90 | * [Cydia Substrate: Introspy-Android](https://github.com/iSECPartners/Introspy-Android) - Blackbox tool to help understand what an Android application is doing at runtime and assist in the identification of potential security issues. 91 | * [Drozer](https://www.mwrinfosecurity.com/products/drozer/) - Drozer allows you to search for security vulnerabilities in apps and devices by assuming the role of an app and interacting with the Dalvik VM, other apps' IPC endpoints and the underlying OS. 92 | * Starting a session 93 | * `adb forward tcp:31415 tcp:31415` 94 | * `drozer console connect` 95 | * Retrieving package information 96 | * `run app.package.list -f ` 97 | * `run app.package.info -a ` 98 | * Identifying the attack surface 99 | * `run app.package.attacksurface ` 100 | * Exploiting Activities 101 | * `run app.activity.info -a -u` 102 | * `run app.activity.start --component ` 103 | * Exploiting Content Provider 104 | * `run app.provider.info -a ` 105 | * `run scanner.provider.finduris -a ` 106 | * `run app.provider.query ` 107 | * `run app.provider.update --selection ` 108 | * `run scanner.provider.sqltables -a ` 109 | * `run scanner.provider.injection -a ` 110 | * `run scanner.provider.traversal -a ` 111 | * Exploiting Broadcast Receivers 112 | * `run app.broadcast.info -a ` 113 | * `run app.broadcast.send --component --extra ` 114 | * `run app.broadcast.sniff --action ` 115 | * Exploiting Service 116 | * `run app.service.info -a ` 117 | * `run app.service.start --action --component ` 118 | * `run app.service.send --msg --extra --bundle-as-obj` 119 | 120 | #### Network Analysis and Server Side Testing 121 | * [Tcpdump](http://www.androidtcpdump.com) - A command line packet capture utility. 122 | * [Wireshark](https://www.wireshark.org/download.html) - An open-source packet analyzer. 123 | * Live packet captures in real time 124 | * `adb shell "tcpdump -s 0 -w - | nc -l -p 4444"` 125 | * `adb forward tcp:4444 tcp:4444` 126 | * `nc localhost 4444 | sudo wireshark -k -S -i –` 127 | * [Canape](http://www.contextis.com/services/research/canape/) - A network testing tool for arbitrary protocols. 128 | * [Mallory](https://intrepidusgroup.com/insight/mallory/) - A Man in The Middle Tool (MiTM) that use to monitor and manipulate traffic on mobile devices and applications. 129 | * [Burp Suite](https://portswigger.net/burp/download.html) - Burp Suite is an integrated platform for performing security testing of applications. 130 | * [OWASP ZAP](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project) - OWASP Zed Attack Proxy Project is an open-source web application security scanner. It is intended to be used by both those new to application security as well as professional penetration testers. 131 | * [Proxydroid](https://play.google.com/store/apps/details?id=org.proxydroid) - Global Proxy App for Android System. 132 | 133 | #### Bypassing Root Detection and SSL Pinning 134 | * [Xposed Module: Just Trust Me](https://github.com/Fuzion24/JustTrustMe) - Xposed Module to bypass SSL certificate pinning. 135 | * [Xposed Module: SSLUnpinning](https://github.com/ac-pm/SSLUnpinning_Xposed) - Android Xposed Module to bypass SSL certificate validation (Certificate Pinning). 136 | * [Cydia Substrate Module: Android SSL Trust Killer](https://github.com/iSECPartners/Android-SSL-TrustKiller) - Blackbox tool to bypass SSL certificate pinning for most applications running on a device. 137 | * [Cydia Substrate Module: RootCoak Plus](https://github.com/devadvance/rootcloakplus) - Patch root checking for commonly known indications of root. 138 | * [Android-ssl-bypass](https://github.com/iSECPartners/android-ssl-bypass) - an Android debugging tool that can be used for bypassing SSL, even when certificate pinning is implemented, as well as other debugging tasks. The tool runs as an interactive console. 139 | * [Frida CodeShare](https://codeshare.frida.re/) - The Frida CodeShare project is comprised of developers from around the world working together with one goal - push Frida to its limits in new and innovative ways. 140 | * Bypassing Root Detection 141 | * `frida --codeshare dzonerzy/fridantiroot -f YOUR_BINARY` 142 | * Bypassing SSL Pinning 143 | * `frida --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida -f YOUR_BINARY` 144 | 145 | #### Security Libraries 146 | * [PublicKey Pinning](https://www.owasp.org/images/1/1f/Pubkey-pin-android.zip) - Pinning in Android can be accomplished through a custom X509TrustManager. X509TrustManager should perform the customary X509 checks in addition to performing the pinning configuration. 147 | * [Android Pinning](https://github.com/moxie0/AndroidPinning) - A standalone library project for certificate pinning on Android. 148 | * [Java AES Crypto](https://github.com/tozny/java-aes-crypto) - A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from. 149 | * [Proguard](http://proguard.sourceforge.net/) - ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. 150 | * [SQL Cipher](https://www.zetetic.net/sqlcipher/sqlcipher-for-android/) - SQLCipher is an open source extension to SQLite that provides transparent 256-bit AES encryption of database files. 151 | * [Secure Preferences](https://github.com/scottyab/secure-preferences) - Android Shared preference wrapper than encrypts the keys and values of Shared Preferences. 152 | * [Trusted Intents](https://github.com/guardianproject/TrustedIntents) - Library for flexible trusted interactions between Android apps. 153 | * [End-to-end encryption](https://github.com/google/capillary) - Capillary is a library to simplify the sending of end-to-end encrypted push messages from Java-based application servers to Android clients. 154 | 155 | ### iOS Application Penetration Testing 156 | #### Access Filesystem on iDevice 157 | * [FileZilla](https://filezilla-project.org/download.php?show_all=1) - It supports FTP, SFTP, and FTPS (FTP over SSL/TLS). 158 | * [Cyberduck](https://cyberduck.io) - Libre FTP, SFTP, WebDAV, S3, Azure & OpenStack Swift browser for Mac and Windows. 159 | * [itunnel](https://code.google.com/p/iphonetunnel-usbmuxconnectbyport/downloads/list) - Use to forward SSH via USB. 160 | * [iProxy](https://github.com/tcurdt/iProxy) - Let's you connect your laptop to the iPhone to surf the web. 161 | * [iFunbox](http://www.i-funbox.com) - The File and App Management Tool for iPhone, iPad & iPod Touch. 162 | 163 | #### Reverse Engineering and Static Analysis 164 | * [otool](http://www.unix.com/man-page/osx/1/otool/) - The otool command displays specified parts of object files or libraries. 165 | * [Clutch](http://cydia.radare.org/) - Decrypted the application and dump specified bundleID into binary or .ipa file. 166 | * [Dumpdecrypted](https://github.com/stefanesser/dumpdecrypted) - Dumps decrypted mach-o files from encrypted iPhone applications from memory to disk. This tool is necessary for security researchers to be able to look under the hood of encryption. 167 | * `iPod:~ root# DYLD_INSERT_LIBRARIES=dumpdecrypted.dylib /var/mobile/Applications/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Scan.app/Scan` 168 | * [class-dump](http://stevenygard.com/projects/class-dump/) - A command-line utility for examining the Objective-C runtime information stored in Mach-O files. 169 | * [Weak Classdump](https://github.com/limneos/weak_classdump) - A Cycript script that generates a header file for the class passed to the function. Most useful when you cannot classdump or dumpdecrypted , when binaries are encrypted etc. 170 | * `iPod:~ root# cycript -p Skype weak_classdump.cy; cycript -p Skype` 171 | * `#cy weak_classdump_bundle([NSBundle mainBundle],"/tmp/Skype")` 172 | * [IDA Pro](https://www.hex-rays.com/products/ida/index.shtml) - IDA is a Windows, Linux or Mac OS X hosted multi-processor disassembler and debugger that offers so many features it is hard to describe them all. 173 | * [HopperApp](http://hopperapp.com/) - Hopper is a reverse engineering tool for OS X and Linux, that lets you disassemble, decompile and debug your 32/64bits Intel Mac, Linux, Windows and iOS executables. 174 | * [hopperscripts](https://github.com/Januzellij/hopperscripts) - Hopperscripts can be used to demangle the Swift function name in HopperApp. 175 | * [Radare2](http://www.radare.org/) - Radare2 is a unix-like reverse engineering framework and commandline tools. 176 | * [iRET](https://www.veracode.com/iret-ios-reverse-engineering-toolkit) - The iOS Reverse Engineering Toolkit is a toolkit designed to automate many of the common tasks associated with iOS penetration testing. 177 | 178 | #### Dynamic and Runtime Analysis 179 | * [cycript](http://www.cycript.org) - Cycript allows developers to explore and modify running applications on either iOS or Mac OS X using a hybrid of Objective-C++ and JavaScript syntax through an interactive console that features syntax highlighting and tab completion. 180 | * Show currently visible view controller 181 | * `cy# UIApp.keyWindow.rootViewController.visibleViewController` 182 | * Show view controller at the top of the navigation stack 183 | * `cy# UIApp.keyWindow.rootViewController.topViewController` 184 | * Get an array of existing objects of a certain class 185 | * `cy# choose(UIViewController)` 186 | * List method at runtime 187 | * `cy# classname.messages` or 188 | `` 189 | cy# function printMethods(className, isa) { 190 | var count = new new Type("I"); 191 | var classObj = (isa != undefined) ? objc_getClass(className)->isa : objc_getClass(className); 192 | var methods = class_copyMethodList(classObj, count); 193 | var methodsArray = []; 194 | for(var i = 0; i < *count; i++) { 195 | var method = methods[i]; 196 | methodsArray.push({selector:method_getName(method), implementation:method_getImplementation(method)}); 197 | } 198 | free(methods); 199 | return methodsArray; 200 | } 201 | `` 202 | * 203 | * `cy# printMethods("")` 204 | * Prints out all the instance variables 205 | * `cy# a=#0x15d0db80` 206 | * `cy# *a` or 207 | * ```cy# function tryPrintIvars(a){ var x={}; for(i in *a){ try{ x[i] = (*a)[i]; } catch(e){} } return x; }``` 208 | * `cy# a=#0x15d0db80` 209 | * `cy# tryPrintIvars(a)` 210 | * Manipulating through property 211 | * `cy# [a pinCode]` 212 | * `cy# [a setPinCode: @"1234"]` or `cy# a.setPinCode= @"1234"` 213 | * Method Swizzling 214 | * `cy# [a isValidPin]` 215 | * `cy# .prototype.isValidPin = function(){return 1;}` 216 | * [Frida-cycript](https://github.com/nowsecure/frida-cycript) - This is a fork of Cycript in which we replaced its runtime with a brand new runtime called Mjølner powered by Frida. This enables frida-cycript to run on all the platforms and architectures maintained by frida-core. 217 | * [Fridpa](https://github.com/tanprathan/Fridpa) - An automated wrapper script for patching iOS applications (IPA files) and work on non-jailbroken device. 218 | * [bfinject](https://github.com/BishopFox/bfinject) - bfinject loads arbitrary dylibs into running App Store apps. It has built-in support for decrypting App Store apps, and comes bundled with iSpy and Cycript. 219 | * [iNalyzer](https://appsec-labs.com/cydia/) - AppSec Labs iNalyzer is a framework for manipulating iOS applications, tampering with parameters and method. 220 | * [Passionfruit](https://github.com/chaitin/passionfruit) - Simple iOS app blackbox assessment tool with Fully web based GUI. Powered by frida.re and vuejs. 221 | * [idb](https://github.com/dmayer/idb) - idb is a tool to simplify some common tasks for iOS pentesting and research. 222 | * [snoop-it](http://cydia.radare.org/) - A tool to assist security assessments and dynamic analysis of iOS Apps. 223 | * [Introspy-iOS](https://github.com/iSECPartners/Introspy-iOS) - Blackbox tool to help understand what an iOS application is doing at runtime and assist in the identification of potential security issues. 224 | * [gdb](http://cydia.radare.org/) - A tool to perform runtime analysis of IOS applications. 225 | * [Apple configurator 2](https://itunes.apple.com/app/apple-configurator-2/id1037126344) - A utility which can be used to view live system log on iDevice. 226 | * [keychaindumper](http://cydia.radare.org/) - A tool to check which keychain items are available to an attacker once an iOS device has been jailbroken. 227 | * [BinaryCookieReader](http://securitylearn.net/wp-content/uploads/tools/iOS/BinaryCookieReader.py) - A tool to dump all the cookies from the binary Cookies.binarycookies file. 228 | 229 | #### Network Analysis and Server Side Testing 230 | * [Canape](http://www.contextis.com/services/research/canape/) - A network testing tool for arbitrary protocols. 231 | * [Mallory](https://intrepidusgroup.com/insight/mallory/) - A Man in The Middle Tool (MiTM) that use to monitor and manipulate traffic on mobile devices and applications. 232 | * [Burp Suite](https://portswigger.net/burp/download.html) - Burp Suite is an integrated platform for performing security testing of applications. 233 | * [OWASP ZAP](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project) - OWASP Zed Attack Proxy Project is an open-source web application security scanner. It is intended to be used by both those new to application security as well as professional penetration testers. 234 | * [Charles Proxy](http://www.charlesproxy.com) - HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. 235 | 236 | #### Bypassing Root Detection and SSL Pinning 237 | * [SSL Kill Switch 2](https://github.com/nabla-c0d3/ssl-kill-switch2) - Blackbox tool to disable SSL certificate validation - including certificate pinning - within iOS and OS X Apps. 238 | * [iOS TrustMe](https://github.com/intrepidusgroup/trustme) - Disable certificate trust checks on iOS devices. 239 | * [Xcon](http://apt.modmyi.com) - A tool for bypassing Jailbreak detection. 240 | * [tsProtector](http://cydia.saurik.com/package/kr.typostudio.tsprotector8/) - Another tool for bypassing Jailbreak detection. 241 | * [Frida CodeShare](https://codeshare.frida.re/) - The Frida CodeShare project is comprised of developers from around the world working together with one goal - push Frida to its limits in new and innovative ways. 242 | * Bypassing SSL Pinning 243 | * `frida --codeshare lichao890427/ios-ssl-bypass -f YOUR_BINARY` 244 | * `frida --codeshare dki/ios10-ssl-bypass -f YOUR_BINARY` 245 | 246 | #### Security Libraries 247 | * [PublicKey Pinning](https://www.owasp.org/images/9/9a/Pubkey-pin-ios.zip) - iOS pinning is performed through a NSURLConnectionDelegate. The delegate must implement connection:canAuthenticateAgainstProtectionSpace: and connection:didReceiveAuthenticationChallenge:. Within connection:didReceiveAuthenticationChallenge:, the delegate must call SecTrustEvaluate to perform customary X509 checks. 248 | * [OWASP iMAS](https://project-imas.github.com/) - iMAS is a collaborative research project from the MITRE Corporation focused on open source iOS security controls. 249 | 250 | ### Contribution 251 | Your contributions and suggestions are welcome. 252 | 253 | ### License 254 | 255 | [![Creative Commons License](http://i.creativecommons.org/l/by/4.0/88x31.png)](http://creativecommons.org/licenses/by/4.0/) 256 | 257 | This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/) 258 | -------------------------------------------------------------------------------- /XML_External_Entity_Prevention_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | *XML eXternal Entity injection* (XXE), which is now part of the [OWASP Top 10](https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project) via the point **A4**, is a type of attack against an application that parses XML input. 4 | 5 | XXE issue is referenced under the ID [611](https://cwe.mitre.org/data/definitions/611.html) in the [Common Weakness Enumeration](https://cwe.mitre.org/index.html) referential. 6 | 7 | This attack occurs when untrusted XML input containing a **reference to an external entity is processed by a weakly configured XML parser**. 8 | 9 | This attack may lead to the disclosure of confidential data, denial of service, [Server Side Request Forgery](https://www.owasp.org/index.php/Server_Side_Request_Forgery) (SSRF), port scanning from the perspective of the machine where the parser is located, and other system impacts. The following guide provides concise information to prevent this vulnerability. 10 | 11 | For more information on XXE, please visit [XML External Entity (XXE)](https://en.wikipedia.org/wiki/XML_external_entity_attack). 12 | 13 | # General Guidance 14 | 15 | The safest way to prevent XXE is always to disable DTDs (External Entities) completely. Depending on the parser, the method should be similar to the following: 16 | 17 | ``` java 18 | factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); 19 | ``` 20 | 21 | Disabling [DTD](https://www.w3schools.com/xml/xml_dtd.asp)s also makes the parser secure against denial of services (DOS) attacks such as [Billion Laughs](https://en.wikipedia.org/wiki/Billion_laughs_attack). If it is not possible to disable DTDs completely, then external entities and external document type declarations must be disabled in the way that’s specific to each parser. 22 | 23 | Detailed XXE Prevention guidance for a number of languages and commonly used XML parsers in those languages is provided below. 24 | 25 | # C/C++ 26 | 27 | ## libxml2 28 | 29 | The Enum [xmlParserOption](http://xmlsoft.org/html/libxml-parser.html#xmlParserOption) should not have the following options defined: 30 | 31 | - `XML_PARSE_NOENT`: Expands entities and substitutes them with replacement text 32 | - `XML_PARSE_DTDLOAD`: Load the external DTD 33 | 34 | Note: 35 | 36 | Per: According to [this post](https://mail.gnome.org/archives/xml/2012-October/msg00045.html), starting with libxml2 version 2.9, XXE has been disabled by default as committed by the following [patch](https://gitlab.gnome.org/GNOME/libxml2/commit/4629ee02ac649c27f9c0cf98ba017c6b5526070f). 37 | 38 | Search for the usage of the following APIs to ensure there is no `XML_PARSE_NOENT` and `XML_PARSE_DTDLOAD` defined in the parameters: 39 | 40 | - `xmlCtxtReadDoc` 41 | - `xmlCtxtReadFd` 42 | - `xmlCtxtReadFile` 43 | - `xmlCtxtReadIO` 44 | - `xmlCtxtReadMemory` 45 | - `xmlCtxtUseOptions` 46 | - `xmlParseInNodeContext` 47 | - `xmlReadDoc` 48 | - `xmlReadFd` 49 | - `xmlReadFile` 50 | - `xmlReadIO` 51 | - `xmlReadMemory` 52 | 53 | ## libxerces-c 54 | 55 | Use of `XercesDOMParser` do this to prevent XXE: 56 | 57 | ``` cpp 58 | XercesDOMParser *parser = new XercesDOMParser; 59 | parser->setCreateEntityReferenceNodes(false); 60 | ``` 61 | 62 | Use of SAXParser, do this to prevent XXE: 63 | 64 | ``` cpp 65 | SAXParser* parser = new SAXParser; 66 | parser->setDisableDefaultEntityResolution(true); 67 | ``` 68 | 69 | Use of SAX2XMLReader, do this to prevent XXE: 70 | 71 | ``` cpp 72 | SAX2XMLReader* reader = XMLReaderFactory::createXMLReader(); 73 | parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true); 74 | ``` 75 | 76 | # Java 77 | 78 | Java applications using XML libraries are particularly vulnerable to XXE because the default settings for most Java XML parsers is to have XXE enabled. To use these parsers safely, you have to explicitly disable XXE in the parser you use. The following describes how to disable XXE in the most commonly used XML parsers for Java. 79 | 80 | ## JAXP DocumentBuilderFactory, SAXParserFactory and DOM4J 81 | 82 | `DocumentBuilderFactory,` `SAXParserFactory` and `DOM4J` `XML` Parsers can be configured using the same techniques to protect them against XXE. 83 | 84 | Only the `DocumentBuilderFactory` example is presented here. The JAXP `DocumentBuilderFactory` [setFeature](https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setFeature(java.lang.String,%20boolean)) method allows a developer to control which implementation-specific XML processor features are enabled or disabled. 85 | 86 | The features can either be set on the factory or the underlying `XMLReader` [setFeature](https://docs.oracle.com/javase/7/docs/api/org/xml/sax/XMLReader.html#setFeature%28java.lang.String,%20boolean%29) method. 87 | 88 | Each XML processor implementation has its own features that govern how DTDs and external entities are processed. 89 | 90 | For a syntax highlighted example code snippet using `SAXParserFactory`, look [here](https://gist.github.com/asudhakar02/45e2e6fd8bcdfb4bc3b2). 91 | 92 | ``` java 93 | import javax.xml.parsers.DocumentBuilderFactory; 94 | import javax.xml.parsers.ParserConfigurationException; // catching unsupported features 95 | 96 | ... 97 | 98 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 99 | String FEATURE = null; 100 | try { 101 | // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all 102 | // XML entity attacks are prevented 103 | // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl 104 | FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; 105 | dbf.setFeature(FEATURE, true); 106 | 107 | // If you can't completely disable DTDs, then at least do the following: 108 | // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities 109 | // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities 110 | // JDK7+ - http://xml.org/sax/features/external-general-entities 111 | FEATURE = "http://xml.org/sax/features/external-general-entities"; 112 | dbf.setFeature(FEATURE, false); 113 | 114 | // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities 115 | // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities 116 | // JDK7+ - http://xml.org/sax/features/external-parameter-entities 117 | FEATURE = "http://xml.org/sax/features/external-parameter-entities"; 118 | dbf.setFeature(FEATURE, false); 119 | 120 | // Disable external DTDs as well 121 | FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; 122 | dbf.setFeature(FEATURE, false); 123 | 124 | // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" 125 | dbf.setXIncludeAware(false); 126 | dbf.setExpandEntityReferences(false); 127 | 128 | // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then 129 | // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks 130 | // (http://cwe.mitre.org/data/definitions/918.html) and denial 131 | // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk." 132 | 133 | // remaining parser logic 134 | ... 135 | } catch (ParserConfigurationException e) { 136 | // This should catch a failed setFeature feature 137 | logger.info("ParserConfigurationException was thrown. The feature '" + FEATURE 138 | + "' is probably not supported by your XML processor."); 139 | ... 140 | } catch (SAXException e) { 141 | // On Apache, this should be thrown when disallowing DOCTYPE 142 | logger.warning("A DOCTYPE was passed into the XML document"); 143 | ... 144 | } catch (IOException e) { 145 | // XXE that points to a file that doesn't exist 146 | logger.error("IOException occurred, XXE may still possible: " + e.getMessage()); 147 | ... 148 | } 149 | 150 | // Load XML file or stream using a XXE agnostic configured parser... 151 | DocumentBuilder safebuilder = dbf.newDocumentBuilder(); 152 | ``` 153 | 154 | [Xerces 1](http://xerces.apache.org/xerces-j/) [Features](http://xerces.apache.org/xerces-j/features.html): 155 | 156 | - Do not include external entities by setting [this feature](http://xerces.apache.org/xerces-j/features.html#external-general-entities) to `false`. 157 | - Do not include parameter entities by setting [this feature](http://xerces.apache.org/xerces-j/features.html#external-parameter-entities) to `false`. 158 | - Do not include external DTDs by setting [this feature](http://xerces.apache.org/xerces-j/features.html#load-external-dtd) to `false`. 159 | 160 | [Xerces 2](http://xerces.apache.org/xerces2-j/) [Features](http://xerces.apache.org/xerces2-j/features.html): 161 | 162 | - Disallow an inline DTD by setting [this feature](http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl) to `true`. 163 | - Do not include external entities by setting [this feature](http://xerces.apache.org/xerces2-j/features.html#external-general-entities) to `false`. 164 | - Do not include parameter entities by setting [this feature](http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities) to `false`. 165 | - Do not include external DTDs by setting [this feature](http://xerces.apache.org/xerces-j/features.html#load-external-dtd) to `false`. 166 | 167 | **Note:** The above defenses require Java 7 update 67, Java 8 update 20, or above, because the above countermeasures for `DocumentBuilderFactory` and SAXParserFactory are broken in earlier Java versions, per: [CVE-2014-6517](http://www.cvedetails.com/cve/CVE-2014-6517/). 168 | 169 | ## XMLInputFactory (a StAX parser) 170 | 171 | [StAX](http://en.wikipedia.org/wiki/StAX) parsers such as [`XMLInputFactory`](http://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLInputFactory.html) allow various properties and features to be set. 172 | 173 | To protect a Java `XMLInputFactory` from XXE, do this: 174 | 175 | ``` java 176 | // This disables DTDs entirely for that factory 177 | xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); 178 | // disable external entities 179 | xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); 180 | ``` 181 | 182 | ## TransformerFactory 183 | 184 | To protect a `javax.xml.transform.TransformerFactory` from XXE, do this: 185 | 186 | ``` java 187 | TransformerFactory tf = TransformerFactory.newInstance(); 188 | tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 189 | tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); 190 | ``` 191 | 192 | ## Validator 193 | 194 | To protect a `javax.xml.validation.Validator` from XXE, do this: 195 | 196 | ``` java 197 | SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); 198 | Schema schema = factory.newSchema(); 199 | Validator validator = schema.newValidator(); 200 | validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 201 | validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); 202 | ``` 203 | 204 | ## SchemaFactory 205 | 206 | To protect a `javax.xml.validation.SchemaFactory` from XXE, do this: 207 | 208 | ``` java 209 | SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); 210 | factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 211 | factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); 212 | Schema schema = factory.newSchema(Source); 213 | ``` 214 | 215 | ## SAXTransformerFactory 216 | 217 | To protect a `javax.xml.transform.sax.SAXTransformerFactory` from XXE, do this: 218 | 219 | ``` java 220 | SAXTransformerFactory sf = SAXTransformerFactory.newInstance(); 221 | sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 222 | sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); 223 | sf.newXMLFilter(Source); 224 | ``` 225 | 226 | **Note: Use of the following `XMLConstants` requires JAXP 1.5, which was added to Java in 7u40 and Java 8:** 227 | 228 | - `javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD` 229 | - `javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA` 230 | - `javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET` 231 | 232 | ## XMLReader 233 | 234 | To protect a Java `org.xml.sax.XMLReader` from XXE, do this: 235 | 236 | ``` java 237 | XMLReader reader = XMLReaderFactory.createXMLReader(); 238 | reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); 239 | // This may not be strictly required as DTDs shouldn't be allowed at all, per previous line. 240 | reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 241 | reader.setFeature("http://xml.org/sax/features/external-general-entities", false); 242 | reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 243 | ``` 244 | 245 | ## SAXReader 246 | 247 | To protect a Java `org.dom4j.io.SAXReader` from XXE, do this: 248 | 249 | ``` java 250 | saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); 251 | saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false); 252 | saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 253 | ``` 254 | 255 | Based on testing, if you are missing one of these, you can still be vulnerable to an XXE attack. 256 | 257 | ## SAXBuilder 258 | 259 | To protect a Java `org.jdom2.input.SAXBuilder` from XXE, do this: 260 | 261 | ``` java 262 | SAXBuilder builder = new SAXBuilder(); 263 | builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true); 264 | builder.setFeature("http://xml.org/sax/features/external-general-entities", false); 265 | builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 266 | Document doc = builder.build(new File(fileName)); 267 | ``` 268 | 269 | ## JAXB Unmarshaller 270 | 271 | Since a `javax.xml.bind.Unmarshaller` parses XML and does not support any flags for disabling XXE, it’s imperative to parse the untrusted XML through a configurable secure parser first, generate a source object as a result, and pass the source object to the Unmarshaller. For example: 272 | 273 | ``` java 274 | //Disable XXE 275 | SAXParserFactory spf = SAXParserFactory.newInstance(); 276 | spf.setFeature("http://xml.org/sax/features/external-general-entities", false); 277 | spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 278 | spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 279 | 280 | //Do unmarshall operation 281 | Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), 282 | new InputSource(new StringReader(xml))); 283 | JAXBContext jc = JAXBContext.newInstance(Object.class); 284 | Unmarshaller um = jc.createUnmarshaller(); 285 | um.unmarshal(xmlSource); 286 | ``` 287 | 288 | ## XPathExpression 289 | 290 | A `javax.xml.xpath.XPathExpression` is similar to an Unmarshaller where it can’t be configured securely by itself, so the untrusted data must be parsed through another securable XML parser first. 291 | 292 | For example: 293 | 294 | ``` java 295 | DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); 296 | df.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 297 | df.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); 298 | DocumentBuilder builder = df.newDocumentBuilder(); 299 | String result = new XPathExpression().evaluate( builder.parse( 300 | new ByteArrayInputStream(xml.getBytes())) ); 301 | ``` 302 | 303 | ## java.beans.XMLDecoder 304 | 305 | The [readObject()](https://docs.oracle.com/javase/8/docs/api/java/beans/XMLDecoder.html#readObject--) method in this class is fundamentally unsafe. 306 | 307 | Not only is the XML it parses subject to XXE, but the method can be used to construct any Java object, and [execute arbitrary code as described here](http://stackoverflow.com/questions/14307442/is-it-safe-to-use-xmldecoder-to-read-document-files). 308 | 309 | And there is no way to make use of this class safe except to trust or properly validate the input being passed into it. 310 | 311 | As such, we'd strongly recommend completely avoiding the use of this class and replacing it with a safe or properly configured XML parser as described elsewhere in this cheat sheet. 312 | 313 | ## Other XML Parsers 314 | 315 | There are many 3rd party libraries that parse XML either directly or through their use of other libraries. Please test and verify their XML parser is secure against XXE by default. If the parser is not secure by default, look for flags supported by the parser to disable all possible external resource inclusions like the examples given above. If there’s no control exposed to the outside, make sure the untrusted content is passed through a secure parser first and then passed to insecure 3rd party parser similar to how the Unmarshaller is secured. 316 | 317 | ### Spring Framework MVC/OXM XXE Vulnerabilities 318 | 319 | For example, some XXE vulnerabilities were found in [Spring OXM](https://pivotal.io/security/cve-2013-4152) and [Spring MVC](https://pivotal.io/security/cve-2013-7315). The following versions of the Spring Framework are vulnerable to XXE: 320 | 321 | - **3.0.0** to **3.2.3** (Spring OXM & Spring MVC) 322 | - **4.0.0.M1** (Spring OXM) 323 | - **4.0.0.M1-4.0.0.M2** (Spring MVC) 324 | 325 | There were other issues as well that were fixed later, so to fully address these issues, Spring recommends you upgrade to Spring Framework 3.2.8+ or 4.0.2+. 326 | 327 | For Spring OXM, this is referring to the use of org.springframework.oxm.jaxb.Jaxb2Marshaller. Note that the CVE for Spring OXM specifically indicates that 2 XML parsing situations are up to the developer to get right, and 2 are the responsibility of Spring and were fixed to address this CVE. 328 | 329 | Here's what they say: 330 | 331 | Two situations developers must handle: 332 | - For a `DOMSource`, the XML has already been parsed by user code and that code is responsible for protecting against XXE. 333 | - For a `StAXSource`, the XMLStreamReader has already been created by user code and that code is responsible for protecting against XXE. 334 | 335 | The issue Spring fixed: 336 | 337 | For SAXSource and StreamSource instances, Spring processed external entities by default thereby creating this vulnerability. 338 | 339 | Here's an example of using a StreamSource that was vulnerable, but is now safe, if you are using a fixed version of Spring OXM or Spring MVC: 340 | 341 | ``` java 342 | import org.springframework.oxm.Jaxb2Marshaller; 343 | import org.springframework.oxm.jaxb.Jaxb2Marshaller; 344 | 345 | Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); 346 | // Must cast return Object to whatever type you are unmarshalling 347 | marshaller.unmarshal(new StreamSource(new StringReader(some_string_containing_XML)); 348 | ``` 349 | 350 | So, per the [Spring OXM CVE writeup](https://pivotal.io/security/cve-2013-4152), the above is now safe. But if you were to use a DOMSource or StAXSource instead, it would be up to you to configure those sources to be safe from XXE. 351 | 352 | # .NET 353 | 354 | The following information for XXE injection in .NET is directly from this [web application of unit tests by Dean Fleming](https://github.com/deanf1/dotnet-security-unit-tests). 355 | 356 | This web application covers all currently supported .NET XML parsers, and has test cases for each demonstrating when they are safe from XXE injection and when they are not. 357 | 358 | Previously, this information was based on [James Jardine's excellent .NET XXE article](https://www.jardinesoftware.net/2016/05/26/xxe-and-net/). 359 | 360 | It originally provided more recent and more detailed information than the older article from [Microsoft on how to prevent XXE and XML Denial of Service in .NET](http://msdn.microsoft.com/en-us/magazine/ee335713.aspx), however, it has some inaccuracies that the web application covers. 361 | 362 | The following table lists all supported .NET XML parsers and their default safety levels: 363 | 364 | | XML Parser | Safe by default? | 365 | |-----------------------|------------------| 366 | | LINQ to XML | Yes | 367 | | XmlDictionaryReader | Yes | 368 | | XmlDocument | | 369 | | ...prior to 4.5.2 | No | 370 | | ...in versions 4.5.2+ | Yes | 371 | | XmlNodeReader | Yes | 372 | | XmlReader | Yes | 373 | | XmlTextReader | | 374 | | ...prior to 4.5.2 | No | 375 | | ...in versions 4.5.2+ | Yes | 376 | | XPathNavigator | | 377 | | ...prior to 4.5.2 | No | 378 | | ...in versions 4.5.2+ | Yes | 379 | | XslCompiledTransform | Yes | 380 | 381 | ## LINQ to XML 382 | 383 | Both the `XElement` and `XDocument` objects in the `System.Xml.Linq` library are safe from XXE injection by default. `XElement` parses only the elements within the XML file, so DTDs are ignored altogether. `XDocument` has DTDs [disabled by default](https://github.com/dotnet/docs/blob/master/docs/visual-basic/programming-guide/concepts/linq/linq-to-xml-security.md), and is only unsafe if constructed with a different unsafe XML parser. 384 | 385 | ## XmlDictionaryReader 386 | 387 | `System.Xml.XmlDictionaryReader` is safe by default, as when it attempts to parse the DTD, the compiler throws an exception saying that "CData elements not valid at top level of an XML document". It becomes unsafe if constructed with a different unsafe XML parser. 388 | 389 | ## XmlDocument 390 | 391 | Prior to .NET Framework version 4.5.2, `System.Xml.XmlDocument` is **unsafe** by default. The `XmlDocument` object has an `XmlResolver` object within it that needs to be set to null in versions prior to 4.5.2. In versions 4.5.2 and up, this `XmlResolver` is set to null by default. 392 | 393 | The following example shows how it is made safe: 394 | 395 | ``` csharp 396 | static void LoadXML() 397 | { 398 | string xxePayload = "]>" 399 | + "&win;"; 400 | string xml = "" + xxePayload; 401 | 402 | XmlDocument xmlDoc = new XmlDocument(); 403 | // Setting this to NULL disables DTDs - Its NOT null by default. 404 | xmlDoc.XmlResolver = null; 405 | xmlDoc.LoadXml(xml); 406 | Console.WriteLine(xmlDoc.InnerText); 407 | Console.ReadLine(); 408 | } 409 | ``` 410 | 411 | `XmlDocument` can become unsafe if you create your own nonnull `XmlResolver` with default or unsafe settings. If you need to enable DTD processing, instructions on how to do so safely are described in detail in the [referenced MSDN article](https://msdn.microsoft.com/en-us/magazine/ee335713.aspx). 412 | 413 | ## XmlNodeReader 414 | 415 | `System.Xml.XmlNodeReader` objects are safe by default and will ignore DTDs even when constructed with an unsafe parser or wrapped in another unsafe parser. 416 | 417 | ## XmlReader 418 | 419 | `System.Xml.XmlReader` objects are safe by default. 420 | 421 | They are set by default to have their ProhibitDtd property set to false in .NET Framework versions 4.0 and earlier, or their `DtdProcessing` property set to Prohibit in .NET versions 4.0 and later. 422 | 423 | Additionally, in .NET versions 4.5.2 and later, the `XmlReaderSettings` belonging to the `XmlReader` has its `XmlResolver` set to null by default, which provides an additional layer of safety. 424 | 425 | Therefore, `XmlReader` objects will only become unsafe in version 4.5.2 and up if both the `DtdProcessing` property is set to Parse and the `XmlReaderSetting`'s `XmlResolver` is set to a nonnull XmlResolver with default or unsafe settings. If you need to enable DTD processing, instructions on how to do so safely are described in detail in the [referenced MSDN article](https://msdn.microsoft.com/en-us/magazine/ee335713.aspx). 426 | 427 | ## XmlTextReader 428 | 429 | `System.Xml.XmlTextReader` is **unsafe** by default in .NET Framework versions prior to 4.5.2. Here is how to make it safe in various .NET versions: 430 | 431 | ### Prior to .NET 4.0 432 | 433 | In .NET Framework versions prior to 4.0, DTD parsing behavior for `XmlReader` objects like `XmlTextReader` are controlled by the Boolean `ProhibitDtd` property found in the `System.Xml.XmlReaderSettings` and `System.Xml.XmlTextReader` classes. 434 | 435 | Set these values to true to disable inline DTDs completely. 436 | 437 | ``` csharp 438 | XmlTextReader reader = new XmlTextReader(stream); 439 | // NEEDED because the default is FALSE!! 440 | reader.ProhibitDtd = true; 441 | ``` 442 | 443 | ### .NET 4.0 - .NET 4.5.2 444 | 445 | In .NET Framework version 4.0, DTD parsing behavior has been changed. The `ProhibitDtd` property has been deprecated in favor of the new `DtdProcessing` property. 446 | 447 | However, they didn't change the default settings so `XmlTextReader` is still vulnerable to XXE by default. 448 | 449 | Setting `DtdProcessing` to `Prohibit` causes the runtime to throw an exception if a `` element is present in the XML. 450 | 451 | To set this value yourself, it looks like this: 452 | 453 | ``` csharp 454 | XmlTextReader reader = new XmlTextReader(stream); 455 | // NEEDED because the default is Parse!! 456 | reader.DtdProcessing = DtdProcessing.Prohibit; 457 | ``` 458 | 459 | Alternatively, you can set the `DtdProcessing` property to `Ignore`, which will not throw an exception on encountering a `` element but will simply skip over it and not process it. Finally, you can set `DtdProcessing` to `Parse` if you do want to allow and process inline DTDs. 460 | 461 | ### .NET 4.5.2 and later 462 | 463 | In .NET Framework versions 4.5.2 and up, `XmlTextReader`'s internal `XmlResolver` is set to null by default, making the `XmlTextReader` ignore DTDs by default. The `XmlTextReader` can become unsafe if if you create your own nonnull `XmlResolver` with default or unsafe settings. 464 | 465 | ## XPathNavigator 466 | 467 | `System.Xml.XPath.XPathNavigator` is **unsafe** by default in .NET Framework versions prior to 4.5.2. 468 | 469 | This is due to the fact that it implements `IXPathNavigable` objects like `XmlDocument`, which are also unsafe by default in versions prior to 4.5.2. 470 | 471 | You can make `XPathNavigator` safe by giving it a safe parser like `XmlReader` (which is safe by default) in the `XPathDocument`'s constructor. 472 | 473 | Here is an example: 474 | 475 | ``` csharp 476 | XmlReader reader = XmlReader.Create("example.xml"); 477 | XPathDocument doc = new XPathDocument(reader); 478 | XPathNavigator nav = doc.CreateNavigator(); 479 | string xml = nav.InnerXml.ToString(); 480 | ``` 481 | 482 | ## XslCompiledTransform 483 | 484 | `System.Xml.Xsl.XslCompiledTransform` (an XML transformer) is safe by default as long as the parser it’s given is safe. 485 | 486 | It is safe by default because the default parser of the `Transform()` methods is an `XmlReader`, which is safe by default (per above). 487 | 488 | [The source code for this method is here.](http://www.dotnetframework.org/default.aspx/4@0/4@0/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/fx/src/Xml/System/Xml/Xslt/XslCompiledTransform@cs/1305376/XslCompiledTransform@cs) 489 | 490 | Some of the `Transform()` methods accept an `XmlReader` or `IXPathNavigable` (e.g., `XmlDocument`) as an input, and if you pass in an unsafe XML Parser then the `Transform` will also be unsafe. 491 | 492 | # iOS 493 | 494 | ## libxml2 495 | 496 | iOS includes the C/C++ libxml2 library described above, so that guidance applies if you are using libxml2 directly. 497 | 498 | However, the version of libxml2 provided up through iOS6 is prior to version 2.9 of libxml2 (which protects against XXE by default). 499 | 500 | ## NSXMLDocument 501 | 502 | iOS also provides an `NSXMLDocument` type, which is built on top of libxml2. 503 | 504 | However, `NSXMLDocument` provides some additional protections against XXE that aren't available in libxml2 directly. 505 | 506 | Per the 'NSXMLDocument External Entity Restriction API' section of this [page](https://developer.apple.com/library/ios/#releasenotes/Foundation/RN-Foundation-iOS/Foundation_iOS5.html): 507 | 508 | - iOS4 and earlier: All external entities are loaded by default. 509 | - iOS5 and later: Only entities that don't require network access are loaded. (which is safer) 510 | 511 | However, to completely disable XXE in an `NSXMLDocument` in any version of iOS you simply specify `NSXMLNodeLoadExternalEntitiesNever` when creating the `NSXMLDocument`. 512 | 513 | # PHP 514 | 515 | Per [the PHP documentation](http://php.net/manual/en/function.libxml-disable-entity-loader.php), the following should be set when using the default PHP XML parser in order to prevent XXE: 516 | 517 | ``` php 518 | libxml_disable_entity_loader(true); 519 | ``` 520 | 521 | A description of how to abuse this in PHP is presented in a good [SensePost article](https://www.sensepost.com/blog/2014/revisting-xxe-and-abusing-protocols/) describing a cool PHP based XXE vulnerability that was fixed in Facebook. 522 | 523 | # References 524 | 525 | - [XXE by InfoSecInstitute](https://resources.infosecinstitute.com/identify-mitigate-xxe-vulnerabilities/) 526 | - [OWASP Top 10-2017 A4: XML External Entities (XXE)](https://www.owasp.org/index.php/Top_10-2017_A4-XML_External_Entities_(XXE)) 527 | - [Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"](https://vsecurity.com//download/papers/XMLDTDEntityAttacks.pdf) 528 | - [FindSecBugs XXE Detection](https://find-sec-bugs.github.io/bugs.htm#XXE_SAXPARSER) 529 | - [XXEbugFind Tool](https://github.com/ssexxe/XXEBugFind) 530 | - [Testing for XML Injection (OTG-INPVAL-008)](https://www.owasp.org/index.php/Testing_for_XML_Injection_(OTG-INPVAL-008)) 531 | 532 | # Authors and Primary Editors 533 | 534 | Dave Wichers - dave.wichers@owasp.org 535 | 536 | Xiaoran Wang - xiaoran@attacker-domain.com 537 | 538 | James Jardine - james@jardinesoftware.com 539 | 540 | Tony Hsu (Hsiang-Chih) 541 | 542 | Dean Fleming 543 | -------------------------------------------------------------------------------- /DotNet_Security_CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This page intends to provide quick basic .NET security tips for developers. 4 | 5 | ## The .NET Framework 6 | 7 | The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies. 8 | 9 | ## Updating the Framework 10 | 11 | The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [Windows Update](http://windowsupdate.microsoft.com/) or from the Windows Update program on a Windows computer. 12 | 13 | Individual frameworks can be kept up to date using [NuGet](http://nuget.codeplex.com/wikipage?title=Getting%20Started&referringTitle=Home). As Visual Studio prompts for updates, build it into your lifecycle. 14 | 15 | Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort. 16 | 17 | # .NET Framework Guidance 18 | 19 | The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level. 20 | 21 | ## Data Access 22 | 23 | - Use [Parameterized SQL](https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.prepare?view=netframework-4.7.2) commands for all data access, without exception. 24 | - Do not use [SqlCommand](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx) with a string parameter made up of a [concatenated SQL String](https://docs.microsoft.com/en-gb/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities?view=vs-2017). 25 | - Whitelist allowable values coming from the user. Use enums, [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) or lookup values to assure that the data coming from the user is as expected. 26 | - Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [Enum.IsDefined](https://msdn.microsoft.com/en-us/library/system.enum.isdefined) can validate whether the input value is valid within the list of defined constants. 27 | - Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case. 28 | - Use of the [Entity Framework](http://msdn.microsoft.com/en-us/data/ef.aspx) is a very effective [SQL injection](https://www.owasp.org/index.php/SQL_Injection) prevention mechanism. **Remember that building your own ad hoc queries in Entity Framework is just as susceptible to SQLi as a plain SQL query**. 29 | - When using SQL Server, prefer [integrated authentication](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/using-integrated-authentication?view=sql-server-2017) over [SQL authentication](https://docs.microsoft.com/en-us/sql/relational-databases/security/choose-an-authentication-mode?view=sql-server-2017#connecting-through-sql-server-authentication). 30 | - Use [Always Encrypted](https://msdn.microsoft.com/en-us/library/mt163865.aspx) where possible for sensitive data (SQL Server 2016 and SQL Azure), 31 | 32 | ## Encryption 33 | 34 | - **Never, ever write your own encryption.** 35 | - Use the [Windows Data Protection API (DPAPI)](http://msdn.microsoft.com/en-us/library/ms995355.aspx) for secure local storage of sensitive data. 36 | - Use a strong hash algorithm. 37 | - In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [System.Security.Cryptography.SHA512](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx). 38 | - In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [System.Security.Cryptography.Rfc2898DeriveBytes](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx). 39 | - In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2](https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing) which has several significant advantages over `Rfc2898DeriveBytes`. 40 | - When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing. 41 | - Make sure your application or protocol can easily support a future change of cryptographic algorithms. 42 | - Use [Nuget](https://docs.microsoft.com/en-us/nuget/) to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly. 43 | 44 | ## General 45 | 46 | - Lock down the config file. 47 | - Remove all aspects of configuration that are not in use. 48 | - Encrypt sensitive parts of the `web.config` using `aspnet_regiis -pe` ([command line help](https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-2.0/k6h9cz8h(v=vs.80))). 49 | - For Click Once applications the .Net Framework should be upgraded to use version `4.6.2` to ensure `TLS 1.1/1.2` support. 50 | 51 | # ASP NET Web Forms Guidance 52 | 53 | ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development. 54 | 55 | - Always use [HTTPS](http://support.microsoft.com/kb/324069). 56 | - Enable [requireSSL](http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx) on cookies and form elements and [HttpOnly](http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx) on cookies in the web.config. 57 | - Implement [customErrors](https://msdn.microsoft.com/en-us/data/h0hfz6fc(v=vs.110)). 58 | - Make sure [tracing](http://www.iis.net/configreference/system.webserver/tracing) is turned off. 59 | - While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [ViewStateUserKey](http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2): 60 | 61 | ```csharp 62 | protected override OnInit(EventArgs e) { 63 | base.OnInit(e); 64 | ViewStateUserKey = Session.SessionID; 65 | } 66 | ``` 67 | 68 | If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie. 69 | 70 | ```csharp 71 | private const string AntiXsrfTokenKey = "__AntiXsrfToken"; 72 | private const string AntiXsrfUserNameKey = "__AntiXsrfUserName"; 73 | private string _antiXsrfTokenValue; 74 | protected void Page_Init(object sender, EventArgs e) 75 | { 76 | // The code below helps to protect against XSRF attacks 77 | var requestCookie = Request.Cookies[AntiXsrfTokenKey]; 78 | Guid requestCookieGuidValue; 79 | if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) 80 | { 81 | // Use the Anti-XSRF token from the cookie 82 | _antiXsrfTokenValue = requestCookie.Value; 83 | Page.ViewStateUserKey = _antiXsrfTokenValue; 84 | } 85 | else 86 | { 87 | // Generate a new Anti-XSRF token and save to the cookie 88 | _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); 89 | Page.ViewStateUserKey = _antiXsrfTokenValue; 90 | var responseCookie = new HttpCookie(AntiXsrfTokenKey) 91 | { 92 | HttpOnly = true, 93 | Value = _antiXsrfTokenValue 94 | }; 95 | if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) 96 | { 97 | responseCookie.Secure = true; 98 | } 99 | Response.Cookies.Set(responseCookie); 100 | } 101 | Page.PreLoad += master_Page_PreLoad; 102 | } 103 | protected void master_Page_PreLoad(object sender, EventArgs e) 104 | { 105 | if (!IsPostBack) 106 | { 107 | // Set Anti-XSRF token 108 | ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey; 109 | ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty; 110 | } 111 | else 112 | { 113 | // Validate the Anti-XSRF token 114 | 115 | if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || 116 | (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty)) 117 | { 118 | throw new InvalidOperationException("Validation of Anti-XSRF token failed."); 119 | } 120 | } 121 | } 122 | ``` 123 | 124 | - Consider [HSTS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) in IIS. See [here](https://support.microsoft.com/en-us/help/954002/how-to-add-a-custom-http-response-header-to-a-web-site-that-is-hosted) for the procedure. 125 | - This is a recommended `web.config` setup that handles HSTS among other things. 126 | 127 | ```xml 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 142 | 143 | 144 | 145 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | ``` 178 | 179 | - Remove the version header. 180 | 181 | ```xml 182 | 183 | ``` 184 | 185 | - Also remove the Server header. 186 | 187 | ```csharp 188 | HttpContext.Current.Response.Headers.Remove("Server"); 189 | ``` 190 | 191 | ## HTTP validation and encoding 192 | 193 | - Do not disable [validateRequest](http://www.asp.net/whitepapers/request-validation) in the `web.config` or the page setup. This value enables limited XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting. Complete request validation is recommended in addition to the built in protections. 194 | - The 4.5 version of the .NET Frameworks includes the [AntiXssEncoder](https://docs.microsoft.com/en-us/dotnet/api/system.web.security.antixss.antixssencoder?view=netframework-4.7.2) library, which has a comprehensive input encoding library for the prevention of XSS. Use it. 195 | - Whitelist allowable values anytime user input is accepted. 196 | - Validate the URI format using [Uri.IsWellFormedUriString](http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx). 197 | 198 | ## Forms authentication 199 | 200 | - Use cookies for persistence when possible. `Cookieless` auth will default to [UseDeviceProfile](https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcookiemode?view=netframework-4.7.2). 201 | - Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked. 202 | - Reduce the forms authentication timeout from the default of *20 minutes* to the shortest period appropriate for your application. If [slidingExpiration](https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthentication.slidingexpiration?view=netframework-4.7.2) is used this timeout resets after each request, so active users won't be affected. 203 | - If HTTPS is not used, [slidingExpiration](https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthentication.slidingexpiration?view=netframework-4.7.2) should be disabled. Consider disabling [slidingExpiration](https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthentication.slidingexpiration?view=netframework-4.7.2) even with HTTPS. 204 | - Always implement proper access controls. 205 | - Compare user provided username with `User.Identity.Name`. 206 | - Check roles against `User.Identity.IsInRole`. 207 | - Use the [ASP.NET Membership provider and role provider](https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/membership-and-role-provider), but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [ASP.NET Identity](http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity) instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [Password Storage Cheat Sheet](Password_Storage_Cheat_Sheet.md) for more information. 208 | - Explicitly authorize resource requests. 209 | - Leverage role based authorization using `User.Identity.IsInRole`. 210 | 211 | # ASP NET MVC Guidance 212 | 213 | ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. 214 | 215 | The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. 216 | 217 | This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test. 218 | 219 | ## A1 SQL Injection 220 | 221 | DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability. 222 | 223 | DO: Use parameterized queries where a direct sql query must be used. 224 | 225 | e.g. In entity frameworks: 226 | 227 | ```sql 228 | var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id"; 229 | context.Database.ExecuteSqlCommand( 230 | sql, 231 | new SqlParameter("@FirstName", firstname), 232 | new SqlParameter("@Id", id)); 233 | ``` 234 | 235 | DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). 236 | 237 | NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere. 238 | 239 | e.g 240 | 241 | ```sql 242 | string strQry = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='" 243 | + txtPassword.Text + "'"; 244 | EXEC strQry // SQL Injection vulnerability! 245 | ``` 246 | 247 | DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account 248 | 249 | ## A2 Weak Account management 250 | 251 | Ensure cookies are sent via httpOnly: 252 | 253 | ```csharp 254 | CookieHttpOnly = true, 255 | ``` 256 | 257 | Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration: 258 | 259 | ```csharp 260 | ExpireTimeSpan = TimeSpan.FromMinutes(60), 261 | SlidingExpiration = false 262 | ``` 263 | 264 | See [here](https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs) for full startup code snippet 265 | 266 | Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms: 267 | 268 | ```xml 269 | 270 | 271 | 272 | 273 | ``` 274 | 275 | Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha. 276 | 277 | ```csharp 278 | [HttpPost] 279 | [AllowAnonymous] 280 | [ValidateAntiForgeryToken] 281 | [AllowXRequestsEveryXSecondsAttribute(Name = "LogOn", 282 | Message = "You have performed this action more than {x} times in the last {n} seconds.", 283 | Requests = 3, Seconds = 60)] 284 | public async Task LogOn(LogOnViewModel model, string returnUrl) 285 | ``` 286 | 287 | DO NOT: Roll your own authentication or session management, use the one provided by .Net 288 | 289 | DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. 290 | 291 | The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. 292 | 293 | ## A3 Cross Site Scripting 294 | 295 | DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists 296 | 297 | You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library: 298 | 299 | `Install-Package AntiXSS` 300 | 301 | Then set in config: 302 | 303 | ```xml 304 | 305 | 309 | ``` 310 | 311 | DO NOT: Use the `[AllowHTML]` attribute or helper class `@Html.Raw` unless you really know that the content you are writing to the browser is safe and has been escaped properly. 312 | 313 | DO: Enable a [Content Security Policy](https://developers.google.com/web/fundamentals/security/csp/), this will prevent your pages from accessing assets it should not be able to access (e.g. a malicious script): 314 | 315 | ```xml 316 | 317 | 318 | 319 | 322 | ``` 323 | 324 | ## A4 Insecure Direct object references 325 | 326 | When you have a resource (object) which can be accessed by a reference (in the sample below this is the `id`) then you need to ensure that the user is intended to be there 327 | 328 | ```csharp 329 | // Insecure 330 | public ActionResult Edit(int id) 331 | { 332 | var user = _context.Users.FirstOrDefault(e => e.Id == id); 333 | return View("Details", new UserViewModel(user); 334 | } 335 | 336 | // Secure 337 | public ActionResult Edit(int id) 338 | { 339 | var user = _context.Users.FirstOrDefault(e => e.Id == id); 340 | // Establish user has right to edit the details 341 | if (user.Id != _userIdentity.GetUserId()) 342 | { 343 | HandleErrorInfo error = new HandleErrorInfo( 344 | new Exception("INFO: You do not have permission to edit these details")); 345 | return View("Error", error); 346 | } 347 | return View("Edit", new UserViewModel(user); 348 | } 349 | ``` 350 | 351 | ## A5 Security Misconfiguration 352 | 353 | Ensure debug and trace are off in production. This can be enforced using web.config transforms: 354 | 355 | ```xml 356 | 357 | 358 | ``` 359 | 360 | DO NOT: Use default passwords 361 | 362 | DO: (When using TLS) Redirect a request made over Http to https: In `Global.asax.cs`: 363 | 364 | ```csharp 365 | protected void Application_BeginRequest() 366 | { 367 | #if !DEBUG 368 | // SECURE: Ensure any request is returned over SSL/TLS in production 369 | if (!Request.IsLocal && !Context.Request.IsSecureConnection) { 370 | var redirect = Context.Request.Url.ToString() 371 | .ToLower(CultureInfo.CurrentCulture) 372 | .Replace("http:", "https:"); 373 | Response.Redirect(redirect); 374 | } 375 | #endif 376 | } 377 | ``` 378 | 379 | ## A6 Sensitive data exposure 380 | 381 | DO NOT: Store encrypted passwords. 382 | 383 | DO: Use a strong hash to store password credentials. Use Argon2, PBKDF2, BCrypt or SCrypt with at least 8000 iterations and a strong key. 384 | 385 | DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy. 386 | 387 | DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly. 388 | 389 | DO: Use TLS 1.2 for your entire site. Get a free certificate [LetsEncrypt.org](https://letsencrypt.org/). 390 | 391 | DO NOT: [Allow SSL, this is now obsolete](https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices#22-use-secure-protocols). 392 | 393 | DO: Have a strong TLS policy (see [SSL Best Practises](http://www.ssllabs.com/projects/best-practises/)), use TLS 1.2 wherever possible. Then check the configuration using [SSL Test](https://www.ssllabs.com/ssltest/) or [TestSSL](https://testssl.sh/). 394 | 395 | DO: Ensure headers are not disclosing information about your application. See [HttpHeaders.cs](https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs) , [Dionach StripHeaders](https://github.com/Dionach/StripHeaders/) or disable via `web.config`: 396 | 397 | ```xml 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | ``` 416 | 417 | ## A7 Missing function level access control 418 | 419 | DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level: 420 | 421 | ```csharp 422 | [Authorize(Roles = "Admin")] 423 | [HttpGet] 424 | public ActionResult Index(int page = 1) 425 | ``` 426 | 427 | or better yet, at controller level: 428 | 429 | ```csharp 430 | [Authorize] 431 | public class UserController 432 | ``` 433 | 434 | You can also check roles in code using identity features in .net: `System.Web.Security.Roles.IsUserInRole(userName, roleName)` 435 | 436 | # A8 Cross site request forgery 437 | 438 | DO: Send the anti-forgery token with every Post/Put request: 439 | 440 | ```csharp 441 | using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", 442 | @class = "pull-right" })) 443 | { 444 | @Html.AntiForgeryToken() 445 | 453 | } 454 | ``` 455 | 456 | Then validate it at the method or preferably the controller level: 457 | 458 | ```csharp 459 | [HttpPost] 460 | [ValidateAntiForgeryToken] 461 | public ActionResult LogOff() 462 | ``` 463 | 464 | Make sure the tokens are removed completely for invalidation on logout. 465 | 466 | ```csharp 467 | /// 468 | /// SECURE: Remove any remaining cookies including Anti-CSRF cookie 469 | /// 470 | public void RemoveAntiForgeryCookie(Controller controller) 471 | { 472 | string[] allCookies = controller.Request.Cookies.AllKeys; 473 | foreach (string cookie in allCookies) 474 | { 475 | if (controller.Response.Cookies[cookie] != null && 476 | cookie == "__RequestVerificationToken") 477 | { 478 | controller.Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1); 479 | } 480 | } 481 | } 482 | ``` 483 | 484 | NB: You will need to attach the anti-forgery token to Ajax requests. 485 | 486 | After .NET Core 2.0 it is possible to automatically generate and verify the antiforgery token. Forms must have the requisite helper as seen here: 487 | 488 | ```html 489 |
490 | @Html.AntiForgeryToken() 491 |
492 | ``` 493 | 494 | And then add the `[AutoValidateAntiforgeryToken]` attribute to the action result. 495 | 496 | ## A9 Using components with known vulnerabilities 497 | 498 | DO: Keep the .Net framework updated with the latest patches 499 | 500 | DO: Keep your [NuGet](https://docs.microsoft.com/en-us/nuget/) packages up to date, many will contain their own vulnerabilities. 501 | 502 | DO: Run the [OWASP Dependency Checker](https://www.owasp.org/index.php/OWASP_Dependency_Check) against your application as part of your build process and act on any high level vulnerabilities. 503 | 504 | ## A10 Unvalidated redirects and forwards 505 | 506 | A protection against this was introduced in Mvc 3 template. Here is the code: 507 | 508 | ```csharp 509 | public async Task LogOn(LogOnViewModel model, string returnUrl) 510 | { 511 | if (ModelState.IsValid) 512 | { 513 | var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password); 514 | if (logonResult.Success) 515 | { 516 | await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe); 517 | return RedirectToLocal(returnUrl); 518 | ... 519 | ``` 520 | 521 | ```csharp 522 | private ActionResult RedirectToLocal(string returnUrl) 523 | { 524 | if (Url.IsLocalUrl(returnUrl)) 525 | { 526 | return Redirect(returnUrl); 527 | } 528 | else 529 | { 530 | return RedirectToAction("Landing", "Account"); 531 | } 532 | } 533 | ``` 534 | 535 | Other advice: 536 | 537 | - Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the `X-Frame-Options` and `Strict-Transport-Security` (HSTS) headers. Full details [here](https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs) 538 | - Protect against a man in the middle attack for a user who has never been to your site before. Register for [HSTS preload](https://hstspreload.org/) 539 | - Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API. 540 | 541 | More information: 542 | 543 | For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [Security Essentials Baseline project](http://github.com/johnstaveley/SecurityEssentials/) 544 | 545 | # XAML Guidance 546 | 547 | - Work within the constraints of Internet Zone security for your application. 548 | - Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time. 549 | 550 | # Windows Forms Guidance 551 | 552 | - Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time. 553 | - Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time. 554 | 555 | ## WCF Guidance 556 | 557 | - Keep in mind that the only safe way to pass a request in RESTful services is via `HTTP POST`, with `TLS enabled`. GETs are visible in the `querystring`, and a lack of TLS means the body can be intercepted. 558 | - Avoid [BasicHttpBinding](https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.basichttpbinding?view=netframework-4.7.2). It has no default security configuration. Use [WSHttpBinding](https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.wshttpbinding?view=netframework-4.7.2) instead. 559 | - Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. [TransportWithMessageCredential](https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/ws-transport-with-message-credential) combines the two. 560 | - Test your WCF implementation with a fuzzer like the [ZAP](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project). 561 | 562 | # Authors and Primary Editors 563 | 564 | Bill Sempf - bill.sempf@owasp.org 565 | 566 | Troy Hunt - troyhunt@hotmail.com 567 | 568 | Jeremy Long - jeremy.long@owasp.org 569 | 570 | Shane Murnion 571 | 572 | John Staveley 573 | 574 | Steve Bamelis 575 | 576 | Xander Sherry 577 | 578 | Sam Ferree 579 | --------------------------------------------------------------------------------