Saturday, 25 July 2015

Directory Listing/Indexing

Directory listing is a web server function that displays a list of all the files when there is not an index file, such as index.php and default.asp in a specific website directory.
For example, when a user requests www.infosecaffairs.com without specifying a file, the web server will process this request and will return the index file for that directory and the actual website will show up. However, if the index file does not exist, the web server will return a list of the contents of that directory. This functionality can be parallelized with the directory listing command in operating systems’ command line, such as ‘ls’ on Unix and Linux systems and ‘dir’ on Windows. Furthermore, it should be noted that the Directory Listing might be caused as well by exploiting any software vulnerabilities using special requests
Background of Directory Listing/Indexing
When a web server reveals a directory's contents, the listing could contain information not intended for public viewing. Often web administrators rely on "Security Through Obscurity" assuming that if there are no hyperlinks to these documents, they will not be found, or no one will look for them. The assumption is incorrect. Today's vulnerability scanners, such as Wikto, can dynamically add additional directories/files to include in their scan based upon data obtained in initial probes. By reviewing the /robots.txt file and/or viewing directory indexing contents, the vulnerability scanner can now interrogate the web server further with these new data. Although potentially harmless, Directory Indexing could allow an information leak that supplies an attacker with the information necessary to launch further attacks against the system
Example
A user makes a website request to www.example.com/images/. The response from the server includes the directory listing content of the directory images, as seen in the below screenshot. 

Impact/ Information Disclosed
The following information could be obtained based on directory indexing data:
*Backup files - with extensions such as .bak, .old or .orig
*Temporary files - these are files that are normally purged from the server but for some reason are still available
*Hidden files - with filenames that start with a "." period.
*Naming conventions - an attacker may be able to identify the composition scheme used by the web site to name directories or files. Example: Admin vs. admin, backup vs. back-up, etc...
*Enumerate User Accounts - personal user accounts on a web server often have home directories named after their user account.
*Configuration file contents - these files may contain access control data and have extentions such as .conf, .cfg or .config
*Script Contents - Most web servers allow for executing scripts by either specifying a script location (e.g. /cgi-bin) or by configuring the server to try and execute files based on file permissions (e.g. the execute bit on *nix systems and the use of the Apache XBitHack directive). Due to these options, if directory indexing of cgi-bin contents are allowed, it is possible to download/review the script code if the permissions are incorrect.
Prevention of Directory Listing/Indexing
Disable directory listings in the web- or application-server configuration by default.
Restrict access to unnecessary directories and files.
Create an index (default) file for each directory.

Friday, 24 July 2015

Security Misconfiguration Vulnerability

Incorrect or Ineffective implementation of security at any layer of a system causes Security Misconfiguration Vulnerability. Security Misconfiguration, or poorly configured security controls, could allow malicious users to change your website, obtain unauthorized access, compromise files, or perform other unintended actions.
Security Misconfiguration can happen at any level of an application stack, including the platform, web server, application server, database, framework, and custom code. Developers and system administrators need to work together to ensure that the entire stack is configured properly.
Example Attack Scenarios
Scenario #1: 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.
Scenario #2: 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 decompiles and reverse engineers to get all your custom code. She then fined a serious access control flaw in your application.
Scenario #3: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide.
Scenario #4: App server comes with sample applications that are not removed from your production server. Said sample applications have well known security flaws attackers can use to compromise your server.

Prevention from Security Misconfiguration
*Regularly evaluate your Website and its environment, including the Web server, operating system, applications, and other resources your Website uses. While there is no one-size-fits-all security configuration, you can use these points to develop a plan that works for your situation:
*Keep third-party applications up to date. Check vendor's websites for updates, and install the most recent release.
*Change default user names and passwords. Use strong, unique passwords for every account.
*Disable directory listings if they are not necessary, or set access controls to deny all requests.
*Delete unnecessary files, such as configuration or install files.
*Keep private or internal data separate from public data. Use strong encryption for anything sensitive.
*Back up data regularly, and store backups appropriately.
*Set and review access controls, and update them as necessary.
*Consider running scans and doing audits periodically to help detect future misconfiguration or missing patches.

Thursday, 23 July 2015

Insecure Direct Object References Series: Prevention of Insecure Direct Object Reference

1. Access Control Check:
One essential defense is to check access control. On each use of a direct object reference from an untrusted source, the application should perform an access control check to ensure the user is authorized for the requested object or service. One way to implement this is to use role-based authorization. The idea behind is associating a list of roles with a user, and the service code queries the list to make decisions about whether the user has privilege to access the requested object or service at run time.
2. Indirect Reference Map:
An indirect reference map is a substitution of the internal reference with an alternate ID. It is used for mapping from a set of internal direct object references (i.e. database keys, filenames, etc. ) to a set of indirect reference that can be safely exposed externally
The direct references are user IDs that are integer and auto-incrementing. Take this as an example; an indirect reference map can be implemented as follows:
  • a) Create a map on the server between that actual key, user ID in the database (i.e. 1011, 1012, ...), and the substitution, which can be a long hash value or a GUID that is easily generated but difficult to predicted by users
  • b) The user ID is translated to its substitution key before being exposed to the UI.
  • c) After the substitution key is returned to the server, it is translated back to the original user ID before the record is retrieved.
3. Use per user or session indirect object references.
This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. The application has to map the per-user indirect reference back to the actual database key on the server.
4. Don’t expose the actual ID/name of objects
5. Minimize user ability to predict object IDs/Names
6. Use of ESAPI

Wednesday, 22 July 2015

Insecure Direct Object References Series : Test/Detect Insecure Direct Object References Vulnerability

Generally, the first step of testing this vulnerability is to “map out all locations in the application where user input is used to reference objects directly” .These locations include where user input is used to access a database row, a file, application pages, etc. Secondly, modify the value of the parameter used to reference objects and assess whether it is possible to retrieve objects belonging to other users and whether authorization can be bypassed.

Static Analysis
One important approach is code review of the application and verifies whether the following mechanisms are implemented safely:
(1) For direct references to restricted resources, the application needs to verify the user is authorized to access the exact resource they have requested.
(2) If the reference is an indirect reference, the mapping to the direct reference must be limited to values authorized for the current user.
Dynamic Analysis
One way to test would be by having multiple users to cover different owned objects and functions. For example, assume two users each having access to different objects and with different privileges (i.e. administrator users or normal users). Logon as one user to see whether there are direct references to objects or functionality that belong to other users. Another advantage of having multiple users is to save testing time in guessing different object names that belong to other users.
Typical scenarios for this vulnerability and the methods to test for each include:
The value of a parameter is used directly to retrieve a database record
Sample request:
                         http://foo.bar/somepage?invoice=12345
In this case, the value of the invoice parameter is used as an index in an invoices table in the database. The application takes the value of this parameter and uses it in a query to the database. The application then returns the invoice information to the user.
Since the value of invoice goes directly into the query, by modifying the value of the parameter it is possible to retrieve any invoice object, regardless of the user to whom the invoice belongs. To test for this case the tester should obtain the identifier of an invoice belonging to a different test user (ensuring he is not supposed to view this information per application business logic), and then check whether it is possible to access objects without authorization.
The value of a parameter is used directly to perform an operation in the system
Sample request:
                         http://foo.bar/changepassword?user=someuser
In this case, the value of the user parameter is used to tell the application for which user it should change the password. In many cases this step will be a part of a wizard, or a multi-step operation. In the first step the application will get a request stating for which user's password is to be changed, and in the next step the user will provide a new password (without asking for the current one).
The user parameter is used to directly reference the object of the user for whom the password change operation will be performed. To test for this case the tester should attempt to provide a different test username than the one currently logged in, and check whether it is possible to modify the password of another user.
The value of a parameter is used directly to retrieve a file system resource
Sample request:
                         http://foo.bar/showImage?img=img00011

In this case, the value of the file parameter is used to tell the application what file the user intends to retrieve. By providing the name or identifier of a different file (for example file=image00012.jpg) the attacker will be able to retrieve objects belonging to other users.
To test for this case, the tester should obtain a reference the user is not supposed to be able to access and attempt to access it by using it as the value of file parameter.
The value of a parameter is used directly to access application functionality
Sample request:
                         http://foo.bar/accessPage?menuitem=12
In this case, the value of the menu item parameter is used to tell the application which menu item (and therefore which application functionality) the user is attempting to access. Assume the user is supposed to be restricted and therefore has links available only to access to menu items 1, 2 and 3. By modifying the value of menu item parameter it is possible to bypass authorization and access additional application functionality. To test for this case the tester identifies a location where application functionality is determined by reference to a menu item, maps the values of menu items the given test user can access, and then attempts other menu items.
In the next part of the Insecure Direct Object References Series we will talk about some Insecure Direct Object Reference Prevention techniques

Tuesday, 21 July 2015

Insecure Direct Object References Series: Introduction and Why Vulnerability Occur

Introduction
Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files.
Insecure Direct Object Reference is an attack where attacker who is an authenticated system user, simply changes a parameter value that directly refers to a system object or another object the user isn’t authorized for. An attacker can manipulate direct object references to access other objects without authorization, unless an access control check is in place.
By exploiting Insecure Direct Object References, attackers can bypass authorization and access resources directly by modifying the value of a parameter used to directly point to an object ( i.e. by modifying the user account ID in a URL string to access the information of other users) . The potentially accessed resources can be database entries belong to other users, files in the system, and more
Why Insecure Direct Object References Vulnerability occurs
From the cases and examples presented above, we can see that insecure direct object typically caused by several design flaws, such as lack of access control, using direct reference to internal object that is exposed and predictable ( i.e. customer ID are easily guessed because it is integer and auto incrementing ).
In the next part of the Insecure Direct Object References Series we will talk about how to Test/Detect Insecure Direct Object References Vulnerability in the web application

Monday, 20 July 2015

Site Scripting Series: Cross Site Scripting Prevention techniques

1. Data Validation
Data validation is the process of ensuring that your application is running with correct data. If your PHP script expects an integer for user input, then any other type of data would be discarded. Every piece of user data must be validated when it is received to ensure it is of the corrected type, and discarded if it doesn’t pass the validation process.
2. Data Sanitization
Data sanitization focuses on manipulating the data to make sure it is safe by removing any unwanted bits from the data and normalizing it to the correct form
3. Encoding
Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into &lt; and &gt;, respectively.
The following pseudocode is an example of how user input could be encoded using HTML escaping and then inserted into a page by a server-side script:
     print "<html>"
     print "Latest comment: "
     print encodeHtml(userInput)
     print "</html>"
If the user input were the string <script>...</script>, the resulting HTML would be as follows:
    <html>
    Latest comment:
    &lt;script&gt;...&lt;/script&gt;
    </html>
Because all characters with special meaning have been escaped, the browser will not parse any part of the user input as HTML.
4. Auto-Escaping and Context-Aware Escaping templates
Sometimes it is advantageous to have everything assigned to Smarty automatically HTML-escaped to reduce the risks of XSS (cross-site scripting) vulnerabilities.
5. Content-security policy
Content-security policy is as a source whitelist. Typically when we make a request for a web page, our browsers trusts output that the server is delivering. CSP limits this trust model by sending Content-Security-Policy header that allows the application to specify a whitelist of trusted (expected) sources. When the browser receives this header, it will only render or execute resources from those sources.
In the event that an attacker does have the ability to inject malicious content that is reflected back against the user, the script will not match the whitelist, and will not be executed.
Example 1: A server wishes to load resources only from its own origin:
                  Content-Security-Policy: default-src 'self'
Example 2: An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
         Content-Security-Policy: default-src 'self'; img-src *; object-src media1.example.com                  media2.example.com *.cdn.example.com; script-src trustedscripts.example.com
Example 3: Online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
          Content-Security-Policy: default-src https: 'unsafe-inline' 'unsafe-eval'
Example 4: A website that relies on inline script elements wishes to ensure that script is only executed from its own origin, and those elements it intentionally inserted inline:
          Content-Security-Policy: script-src 'self' 'nonce-$RANDOM';
The inline script elements would then only execute if they contained a matching nonce attribute:             <script nonce="$RANDOM">...</script>
6. Javascript sandbox tools
7. Cookie security
Many web applications tie session cookies to the IP address of the user who originally logged in, and only permit that IP to use that cookie. This is effective in situations like if an attacker is only after the cookie
HTTP-only cookies: Http-Only flag allows a web server to set a cookie that is unavailable to client-side scripts. It disables client access via document.cookie and mitigates cookie theft via XSS
8. Application Firewall
By installing a third party application firewall, which intercepts XSS attacks before they reach the web server and the vulnerable scripts, and blocks them. For each input source, the application firewall inspects the data against various HTML tag patterns and Javascript patterns, and if any match, the request is rejected and the malicious input does not arrive to the server.
A full detailed guide to prevent XSS is also available on OWASP. You can read it here.

Sunday, 19 July 2015

Cross Site Scripting Series: Impact and Test Cross Site Scripting

Impact of Cross-Site Scripting
When attackers succeed in exploiting XSS vulnerabilities, they can gain access to account credentials. They can also spread web worms or access the user’s computer and view the user’s browser history or control the browser remotely. After gaining control to the victim’s system, attackers can also analyze and use other intranet applications.
By exploiting XSS vulnerabilities, an attacker can perform malicious actions, such as:
  • Hijack an account.
  • Spread web worms.
  • Access browser history and clipboard contents.
  • Control the browser remotely.
  • Scan and exploit intranet appliances and applications.
Test Cross-Site Scripting
A sample test is shown here against the most common parameter: the GET request. When the URL includes some parameter like title, it can be attempted to exploit directly in the browser:
           Page.php?title=<SCRIPT>alert("attack")</SCRIPT>
For each of the attack vectors described, you can test them in the following ways:
· GET - modify the parameter to an XSS string
· POST - insert the XSS string into a form field, or using an attack proxy
· Headers - modify a header to an XSS string
· Window.location - if using input in the new URL, try appending javascript
· document.referrer - Modify the referrer (header) to an XSS string
· document.URLUnencoded- The function returns the unencoded URL, so include a URL encoded XSS string in the URL to test this.
· Cookies - Inspect and modify the cookie values on your PC for testing. Insert XSS attacks in the cookie
Alternate Cross-Site Scripting Syntax
XSS using Script in Attributes

XSS attacks may be conducted without using <script></script> tags. Other tags will do exactly the same thing, for example:
             <body onload=alert('test1')>
             or other attributes like: onmouseover, onerror.
            onmouseover <b onmouseover=alert('Wufff!')>click me!</b>
            onerror <img src="http://url.to.file.which/not.exist" onerror=alert(document.cookie);>
XSS using Script Via Encoded URI Schemes
If we need to hide against web application filters we may try to encode string characters, e.g.: a=&#X41 (UTF-8) and use it in IMG tag: <IMG SRC=j&#X41vascript:alert('test2')>
There are many different UTF-8 encoding notations what give us even more possibilities.
XSS using code encoding
We may encode our script in base64 and place it in META tag. This way we get rid of alert() totally.      
          <META HTTP-EQUIV="refresh"
           CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg">
These and others examples can be found at the OWASP XSS Filter Evasion Cheat Sheet which is a true encyclopaedia of the alternate XSS syntax attack.In the next part of the Cross Site Scripting Series we will talk about the CrossSite Scripting Prevention techniques.

Prevention Techniques: Cross-site request forgery (CSRF)

1. The best defense against CSRF attacks is unpredictable tokens, a piece of data that the server can use to validate the request, and wh...