
















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Common web application vulnerabilities, including Cross-Site Scripting (XSS), Insecure Direct Object References, Access to Restricted URLs, Unvalidated Redirects and Forwards, and Insecure File Uploads. It also provides recommendations for mitigating these risks.
Typology: Schemes and Mind Maps
1 / 24
This page cannot be seen from the preview
Don't miss anything!

















1. Purpose The intention of this document is to ensure that anyone who is involved in developing a web application or web site is aware of the potential insecurities and vulnerabilities that may be introduced into the code written to provide the web site's services and how these can be avoided or mitigated against by following these best practices. The precise method of implementation of best practice will vary depending on the coding language, web server platform and computer architecture that are used to deliver the web application.
Much of this document has been taken from the University of Montana's Web Application Best Practices guide which itself copies heavily from the OWASP Top 10 for 2013, and the General PHP Website Management Guidelines for QMUL Website Developers.
2. Data Security
Data held in a database or file accessible via the web application's URL that contains sensitive or personal information.
A public facing web site which is used to display staff members' publications and research interests reads its data from a database that also contains the personal mobile number, pay grade and sickness record of staff. A web application used by internal staff to manage student progress is available over the Internet. Part of this application can be accessed without logging in but still connects to the database to retrieve information.
Only data that is used by the web application should be present in the tables or views that the application's database user has access to. If there is a requirement to display some information publically then a different database user should be created for this and its access restricted to the fields it requires through views and database permissions. If data needs to be written back to the database then write permissions should be restricted to the smallest set of tables required. Obsolete data should be periodically deleted. Following this practice will reduce the impact that a security breach could cause. If only publically available information is stored in a database then an attacker will only be able to extract public information through an exploit. Any use of personal or sensitive data in a web application must be cleared with the Data Compliance Manager. Data Compliance states: Wherever possible the amount and type of information stored and collected should be kept to a minimum and steps taken to delete obsolete data on a regular basis. If you have no need for a field e.g. mobile phone number, then it should be removed and not included in future. This type of information should not reside on an externally accessible website or system unless absolutely necessary and if it does (or even if it doesn't) it should be protected appropriately i.e. behind IDcheck and with some added security such as encryption or by moving the website/data to a secure server.
4. SQL Injection (SQLi)
Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user- supplied data is submitted as part of a command or query. The attacker's hostile data tricks the application into executing unintended commands or changing data.
Given this piece of code which inserts user input directly into a query $sql = " SELECT fieldlist FROM table WHERE email = '$_POST[' EMAIL']' " ; The developer is expecting the user to submit a valid email address. However, there is nothing stopping a malicious user from submitting a string that entirely changes the query. Suppose the attacker submits: x' or 'x' = 'x' The query now becomes: $sql = "SELECT fieldlist FROM table WHERE email = 'x' or 'x' = 'x'; Since 'x' = 'x' is always true the query will return every record in the table. This is a trivial example but this technique can be used to construct much more damaging queries.
Preventing injection requires keeping un-trusted data separate from commands and queries. The preferred option is to use a safe API that avoids the use of the interpreter entirely or provides a parameterized interface such as a prepared query where parameters are passed as arguments rather than concatenated into the query string. If the expected input is numeric, an item from a known list of possibilities or in a prescribed format then the input can be checked to ensure it matches the expected parameters. If a parameterized API is not available, you should carefully escape special characters using the specific escape syntax for that interpreter (e.g. for MySQL use the mysql_real_escape_string function).
5. Cross Site Scripting (XSS)
XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute script in the victim's browser that can hijack user sessions, deface web sites or possibly introduce worms.
The application uses un-trusted data in the construction of the following HTML snippet without validation or escaping: page += " " ; The attacker modifies the "CC" parameter in their browser to: '>' This causes the victim's session ID to be sent to the attacker's website, allowing the attacker to hijack the user's current session.
Preventing XSS requires keeping un-trusted data separate from active browser content. The preferred option is to properly escape all un-trusted data (any user submitted data) based on the HTML context (body, attribute, JavaScript, CSS, or URL) that the data will be placed into. Developers need to include this escaping in their applications unless their UI framework does this for them. If the expected input is numeric, an item from a known list of possibilities or in a prescribed format then the input can be checked to ensure it matches the expected parameters. Disable the TRACE HTTP method to prevent Cross-site tracing.
7. Access to Restricted URLs
Frequently, an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly.
The website has an administration section contained within the /admin/ directory. http://example.com/app/home http://example.com/app/admin/listusers If access to the /admin/ directory is only restricted by not advertising the directory – it is not linked to from any public page or access to the /admin/ directory is allowed for any authorised user then an attacker will be able to discover this directory and gain access to its functionality. Such flaws are frequently introduced when links and buttons are simply not displayed to unauthorized users, but the application fails to protect the pages they target.
Preventing unauthorized URL access requires selecting an approach for requiring proper authentication and proper authorization for each page. Frequently, such protection is provided by one or more components external to the application code. Regardless of the mechanism(s), all of the following are recommended: The authentication and authorization policies should be role based, to minimize the effort required to maintain these policies. The policies should be highly configurable in order to minimize any hard coded aspects of the policy. The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific users and roles for access to every page. If the page is involved in a workflow, check to make sure the conditions are in the proper state to allow access at each stage in the workflow.
8. Transport Layer Protection
Applications frequently fail to authenticate, encrypt and protect the confidentiality and integrity of sensitive network traffic. When they do they sometimes support weak algorithms, use expired or invalid certificates or do not use them correctly.
A site simply doesn't use SSL for all pages that require authentication. Attacker monitors network traffic (like an open wireless or their neighbourhood cable modem network), and observes an authenticated victim's session cookie. Attacker then replays this cookie and takes over the user's session. A site has improperly configured SSL certificate which causes browser warnings for its users. Users have to accept such warnings and continue, in order to use the site. This causes users to get accustomed to such warnings. Phishing attack against the site's customers lures them to a lookalike site which doesn't have a valid certificate, which generates similar browser warnings. Since victims are accustomed to such warnings, they proceed and use the phishing site, giving away passwords or other private data. A site simply uses a standard database connection. If the database and web server are in different physical locations then the information (e.g. database name, user, and password) can be viewed as it goes across the network.
Providing proper transport layer protection can affect the site design. It's easiest to require SSL for the entire site. For performance reasons, some sites use SSL only on private or sensitive pages. However the overhead of SSL is not that great and it is rarely worth the gain in performance considering the risk of not encrypting sensitive information. At a minimum, do all of the following:
10. Authentication and Session Management
Authentication and session management includes all aspects of handling user authentication and managing active sessions. Authentication is a critical aspect of this process, but even solid authentication mechanisms can be undermined by flawed credential management functions, including password change, forgot my password, remember my password, account update, and other related functions. Because "walk by" attacks are likely for many web applications, all account management functions should require re-authentication even if the user has a valid session id.
Airline reservations application supports URL rewriting, putting session IDs in the URL: http://example.com/sale/saleitems;jsessionid=2P0OC2JDPX..LPSKHCJUN2JV?dest=Hawaii An authenticated user of the site wants to let his friends know about the sale. He e-mails the above link without knowing he is also giving away his session ID. When his friends use the link they will use his session and credit card Application's timeouts aren't set properly. User uses a public computer to access site. Instead of selecting "logout" the user simply closes the browser tab and walks away. Attacker uses the same browser an hour later, and that browser is still authenticated. Insider or external attacker gains access to the system's password database. User passwords are not encrypted, exposing every user's password to the attacker. Insider or external attacker gains access to an applications database. Usernames are stored plain text. The attacker now has a list of user names from which to launch brute force password attacks on any other application that uses usernames to authenticate users.
When possible QMUL applications should authenticate users against the LDAP directory using college username and password. By relying on the LDAP server to authenticate users many of the preventative measures listed in the next section are met. When possible applications should not rely on their own authentication mechanism but should use provided authentication tools.
11. Password Strength and Storage
If it is not possible to authenticate against the LDAP service then serious consideration must be given to the creation, storage and transmission of passwords.
Passwords should have restrictions that require a minimum size and complexity for the password. Complexity typically requires the use of minimum combinations of alphabetic, numeric, and/or non- alphanumeric characters in a user's password (e.g., at least one of each). Users should be required to change their password periodically. Users should be prevented from reusing previous passwords.
Users should be restricted to a defined number of login attempts per unit of time and repeated failed login attempts should be logged. Passwords provided during failed login attempts should not be recorded, as this may expose a user's password to whoever can gain access to this log. The system should not indicate whether it was the username or password that was wrong if a login attempt fails. Users should be informed of the date/time of their last successful login and the number of failed access attempts to their account since that time.
A single password change mechanism should be used wherever users are allowed to change a password, regardless of the situation. Users should always be required to provide both their old and new password when changing their password (like all account information). If forgotten passwords are emailed to users, the system should require the user to reauthenticate whenever the user is changing their e-mail address, otherwise an attacker who temporarily has access to their session (e.g., by walking up to their computer while they are logged in) can simply change their e-mail address and request a 'forgotten' password be mailed to them.
If an application needs to handle its own authentication it must not use the college username to identify users. All passwords must be stored in a salted hashed form to protect them from exposure, regardless of where they are stored.
The only effective technique is to encrypt the entire login transaction using something like SSL. Simple transformations of the password such as hashing it on the client prior to transmission provide little protection as the hashed version can simply be intercepted and retransmitted even though the actual plaintext password might not be known.
Ideally a user's entire session should be protected via SSL. If this is done, then the session ID (e.g., session cookie) cannot be grabbed off the network, which is the biggest risk of exposure for a session ID. If SSL is not viable for performance or other reasons then session IDs themselves must be protected in other ways. First, they should never be included in the URL as they can be cached by the browser, sent in the referrer header, or accidentally forwarded to a 'friend'. Session IDs should be long, complicated, random numbers that cannot be easily guessed. Session IDs can also be changed frequently during a session to reduce how long a session ID is valid. Session IDs must be changed when switching to SSL, authenticating, or other major transitions. Session IDs chosen by a user should never be accepted.
Systems should be designed to avoid allowing users to gain access to a list of the account names on the site. If lists of users must be presented, it is recommended that some form of pseudonym (screen name) that maps to the actual account be listed instead. That way, the pseudonym can't be used during a login attempt or some other hack that goes after a user's account.
12. Security Misconfiguration
Responsibly managing Web application security often involves the expertise of both developers and administrators and requires members from both sides of the project to properly ensure the security of a site's application. This is the case with respect to configuration.
Your application relies on a powerful framework like Struts or Spring. XSS flaws are found in these framework components you rely on. An update is released to fix these flaws but you don't update your libraries. Until you do, attackers can easily find and exploit these flaws in your app. The app server admin console is automatically installed and not removed. Default accounts aren't changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over. Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she reverse engineers to get all your custom code. She then finds a serious access control flaw in your application. Application server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide. You manage a Wordpress site. Some areas of the site are password protected. You have configured Wordpress to use SSL when users access the login pages. An upgrade is available and you apply it not realising the upgrade erased the settings that require SSL on the login pages. Submitted passwords are now sent in plain text across the network.
The primary recommendations for developers are to establish all of the following:
13. Encrypted Data
The first thing you have to determine is which data is sensitive enough to require encryption. For example, passwords, account names, student records, health records, and personal information should be encrypted anywhere it is stored long term.
An application encrypts credit card numbers in a database to prevent exposure to end users. However, the database is set to automatically decrypt queries against the credit card columns, allowing an SQL injection flaw to retrieve all the credit cards in cleartext. The system should have been configured to allow only back end applications to decrypt them, not the front end web application. An Application uses basic authentication and resides on a multi-user system. The password file is stored outside the web root so that it cannot be downloaded via the web. However other users on the same machine can read your files via the UNIX shell if the file is not properly protected. Another account on the machine is hacked and your password file becomes exposed. Because basic authentication does not use true encryption it is trivial to decode the passwords.
For all data deemed sensitive or confidential you must ensure:
15. File upload vulnerabilities
Uploaded files represent a significant risk to applications. The first step in many attacks is to get some code to the system to be attacked. Then the attack only needs to find a way to get the code executed. Using a file upload helps the attacker accomplish the first step. The consequences of unrestricted file upload can vary, including complete system takeover, an overloaded file system or database, forwarding attacks to back-end systems, and simple defacement. It depends on what the application does with the uploaded file and especially where it is stored.
Upload .jsp file into web tree - jsp code executed as web user Upload .gif to be resized - image library flaw exploited Upload huge files - file space denial of service Upload file using malicious path or name - overwrite critical file Upload file containing personal data - other users access it Upload file containing "tags" - tags get executed as part of being "included" in a web page Upload .exe file into web tree – victims download trojan executable Upload virus infected file – victims' machines infected Upload .html file containing script – victim exposed to cross site scripting
Avoid unnecessary file uploads. Limit the maximum size of file that can be uploaded and the maximum number of files that can be uploaded either by user or by time – only allowing 10 uploads per minute. Ensure that files uploaded by the user cannot be interpreted as script files by the web server, e.g. by checking the file extension (or whatever means your web server uses to identify script files). Ensure that files cannot be uploaded to unintended directories (directory traversal). Save the file with a generated file name, not the one that the user supplied. If this is not possible limit the filename length and remove all non-alphanumeric characters from the filename. Disable script execution in the upload directory. Ensure that the file extension matches the actual type of the file content. If only images are to be uploaded, consider re-compressing them using a secure library to ensure they are valid. Ensure that uploaded files are specified with the correct Content-type when delivered to the user. Prevent users from uploading problematic file types like HTML, CSS, JavaScript, XML, SVG and executables using a whitelist of allowed file types. Prevent users from uploading special files (e.g. .htaccess, web.config, robots.txt, crossdomain.xml, clientaccesspolicy.xml). Prevent users from overwriting application files. Virus scan the uploaded files. If accepting a zip or other form of archive file check each file in the archive. Don't present the uploaded file to other users without ensuring that they are not malicious.
16. Directory Traversal Description A Path Traversal attack aims to access files and directories that are stored outside the web root folder. By browsing the application, the attacker looks for absolute links to files stored on the web server. By manipulating variables that reference files with "dot-dot-slash (../)" sequences and its variations, it may be possible to access arbitrary files and directories stored on file system, including application source code, configuration and critical system files, limited by system operational access control. The attacker uses "../" sequences to move up to root directory, thus permitting navigation through the file system. This attack can be executed with an external malicious code injected on the path, like the Resource Injection attack. To perform this attack it's not necessary to use a specific tool; attackers typically use a spider/crawler to detect all URLs available. This attack is also known as "dot-dot-slash", "directory traversal", "directory climbing" and "backtracking".
The web application has a function that displays a named file. http://some_site.com.br/get-files.jsp?file=report.pdf It is possible to insert a malicious string as the file parameter to access files located outside the web publish directory. http://some_site.com.br/get-files.jsp?file=../../../../etc/passwd It is also possible to include files and scripts located on external website. http://some_site.com.br/some-page?page=http://other-site.com.br/other-page.htm/malicius- code.php Or allow an attacker to view the server's CGI source code. http://some_site.com.br/cgi-bin/main.cgi?file=main.cgi Even if the file path is not directly provided in the URL but via a cookie it is still trivial to script a directory traversal attack. GET /vulnerable.php HTTP/1. Cookie: TEMPLATE=../../../../etc/passwd Mitigation Prefer working without user input when using file system calls. Use indexes rather than actual portions of file names when templating or using language files (i.e. the parameter lang= 5 translates to Czechoslovakian, rather than allowing the user to enter the parameter lang=Czechoslovakian). Ensure the user cannot supply all parts of the path – surround it with your path code. Validate the user's input by only accepting known good – do not sanitize the data.