Sunday 26 July 2015

Sensitive Data Exposure Vulnerabilities

Sensitive data exposure vulnerabilities can occur when an application does not adequately protect sensitive information from being disclosed to attackers. For many applications this may be limited to information such as passwords, but it can also include information such as credit card data, session tokens, or other authentication credentials.
Example
Scenario #1: An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system should have encrypted the credit card numbers using a public key, and only allowed back-end applications to decrypt them with the private key.
Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data.
Testing of Sensitive data exposure vulnerabilities
The first thing you have to determine is which data is sensitive enough to require extra protection. For example, passwords, credit card numbers, health records, and personal information should be protected. For all such data:
*Is any of this data stored in clear text long term, including backups of this data?
*Is any of this data transmitted in clear text, internally or externally? Internet traffic is especially dangerous.
*Are any old / weak cryptographic algorithms used?
*Are weak crypto keys generated, or is proper key management or rotation missing?
*Are any browser security directives or headers missing when sensitive data is provided by / sent to the browser?
Prevention of Sensitive data exposure vulnerabilities
· Encrypt all sensitive data at rest and in transit in a manner that defends against these threats.
· Don’t store sensitive data unnecessarily. Discard it as soon as possible. Data you don’t have can’t be stolen.
· Disable auto complete on forms collecting sensitive data and disable caching for pages that contain sensitive data.

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.

Saturday 18 July 2015

Cross-Site Scripting Series :Types of Cross-Site Scripting

Stored Cross-Site Scripting
Stored attacks are those where the injected script is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information. Stored XSS is also sometimes referred to as Persistent or Type-I XSS.
1. The attacker uses one of the website's forms to insert a malicious string into the website's database.
2. The victim requests a page from the website.
3. The website includes the malicious string from the database in the response and sends it to the victim.
4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server.
Reflected Cross-Site Scripting
Reflected attacks are those where the injected script is reflected off the web server, such as in an error message, search result, or any other response. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web site. When a user is tricked into clicking on a malicious link, submitting a specially crafted form, or even just browsing to a malicious site, the injected code travels to the vulnerable web site, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server. Reflected XSS is also sometimes referred to as Non-Persistent or Type-II XSS.
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website includes the malicious string from the URL in the response.
4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server.
DOM-based Cross-Site Scripting
The DOM, or Document Object Model, is the structural format used to represent documents in a browser. The DOM enables dynamic scripts such as JavaScript to reference components of the document such as a form field or a session cookie.
In a DOM-based XSS attack, the malicious string is not actually parsed by the victim's browser until the website's legitimate JavaScript is executed. DOM based XSS does not require the web server to receive the malicious XSS payload. Instead, in a DOM-based XSS, the attacker abuses runtime embedding of attacker data in the client side, from within a page served from the web server.
DOM-based Cross-Site Scripting occurs when script manipulates the pages DOM allowing an attacker to run script on victim browser. DOM-based Cross-Site Scripting will observed in run time only not in source code or not in response
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website receives the request, but does not include the malicious string in the response.
4. The victim's browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page.
5. The victim's browser executes the malicious script inserted into the page, sending the victim's cookies to the attacker's server.

In the next part of the Cross-Site Scripting Series we will talk about the impact of Cross-Site Scripting and how to test Cross-SiteScripting
References
http://excess-xss.com/

Friday 17 July 2015

Cross-Site Scripting Series: Inroduction

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user's browser, often causing side effects such as data compromise, or the stealing of a user session. This can allow an attacker to impersonate a user to steal their details, or act in their place without consent.XSS Flaws occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. 
Description of Cross-Site Scripting
Cross-Site Scripting (XSS) attacks occur when:
· Data enters a Web application through an untrusted source, most frequently a web request.
· The data is included in dynamic content that is sent to a web user without being validated for malicious content.
The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash, or any other type of code that the browser may execute. A successful XSS attack compromises the security of both the website and its users.
XSS vulnerability arises when web applications take data from users and dynamically include it in web pages without first properly validating the data. XSS vulnerabilities allow an attacker to execute arbitrary commands and display arbitrary content in a victim user's browser. A successful XSS attack leads to an attacker controlling the victim’s browser or account on the vulnerable web application.
Example
     
index.php: <?php
$name = $_GET['name'];
echo "Welcome $name<br>";
echo "<a href="http://infosecaffairs.blogspot.com/">Click to Download</a>";
?>
Now the attacker will craft an URL as follows and send it to the victim:
   
index.php?name=guest<script>alert('XSS')</script>
    
When the victim loads the above URL into the browser, he will see an alert box which says ‘attacked’. Even though this example doesn’t do any damage, other than the annoying ‘attacked’ pop-up, you can see how an attacker can use this method to do several damaging things.
In the next part of the series we will discuss about the Types of XSS vulnerabilities

Thursday 16 July 2015

XML injection

XML injection occurs when:
1. Data enters a program from an untrusted source.
2. The data is written to an XML document.
Applications typically use XML to store data or send messages. When used to store data, XML documents are often treated like databases and can potentially contain sensitive information. XML messages are often used in web services and can also be used to transmit sensitive information. XML message can even be used to send authentication credentials.
The semantics of XML documents and messages can be altered if an attacker has the ability to write raw XML. In the most benign case, an attacker may be able to insert extraneous tags and cause an XML parser to throw an exception. In more nefarious cases of XML injection, an attacker may be able to add XML elements that change authentication credentials or modify prices in an XML e-commerce database. In some cases, XML injection can lead to cross-site scripting or dynamic code evaluation.
Example
By inserting the following values: Username: tony
Password: Un6R34kb!e
E-mail: s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com
the application will build a new node and append it to the XML database:
<?xml version="1.0" encoding="ISO-8859-1"?> 
<users> 
               <user> 
                               <username>gandalf</username> 
                               <password>!c3</password> 
                               <userid>0</userid>
                               <mail>gandalf@middleearth.com</mail>
               </user> 
               <user> 
                               <username>Stefan0</username> 
                               <password>w1s3c</password> 
                               <userid>500</userid>
                               <mail>Stefan0@whysec.hmm</mail>
               </user> 
               <user> 
                               <username>tony</username> 
                               <password>Un6R34kb!e</password> 
                               <userid>500</userid>
                               <mail>s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com</mail>
               </user> 
</users>
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. 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. Let's suppose that the XML document is specified by the following DTD:

<!DOCTYPE users [
                 <!ELEMENT users (user+) >
                 <!ELEMENT user (username,password,userid,mail+) >
                 <!ELEMENT username (#PCDATA) >
                 <!ELEMENT password (#PCDATA) >
                 <!ELEMENT userid (#PCDATA) >
                 <!ELEMENT mail (#PCDATA) >
]>
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. 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 a comment start/end sequence: Username: tony Password: Un6R34kb!e</password><!-- E-mail: --><userid>0</userid><mail>s4tan@hell.com In this case, the final XML database is: <?xml version="1.0" encoding="ISO-8859-1"?>
<users> 
               <user> 
                               <username>gandalf</username> 
                               <password>!c3</password> 
                               <userid>0</userid>
                               <mail>gandalf@middleearth.com</mail>
               </user> 
               <user> 
                               <username>Stefan0</username> 
                               <password>w1s3c</password> 
                               <userid>500</userid>
                               <mail>Stefan0@whysec.hmm</mail>
               </user> 
               <user> 
                               <username>tony</username> 
                               <password>Un6R34kb!e</password><!--</password> 
                               <userid>500</userid>
                               <mail>--><userid>0</userid><mail>s4tan@hell.com</mail>
               </user>
</users>
The original userid node has been commented out, leaving only the injected one. The document now complies with its DTD rules.

Tuesday 14 July 2015

XPath Injection

XPath Injection attacks occur when a web site uses user-supplied information to construct an XPath query for XML data. By sending intentionally malformed information into the web site, an attacker can find out how the XML data is structured, or access data that he may not normally have access to. He may even be able to elevate his privileges on the web site if the XML data is being used for authentication (such as an XML based user file).
Example Vulnerability
We'll use this XML snippet for the examples. <?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee ID="1">
<FirstName>Arnold</FirstName>
<LastName>Baker</LastName>
<UserName>ABaker</UserName>
<Password>SoSecret</Password>
<Type>Admin</Type>
</Employee>
<Employee ID="2">
<FirstName>Peter</FirstName>
<LastName>Pan</LastName>
<UserName>PPan</UserName>
<Password>NotTelling</Password>
<Type>User</Type>
</Employee>
</Employees>
Suppose we have a user authentication system on a web page that used a data file of this sort to login users. Once a username and password have been supplied the software might use XPath to look up the user:
VB:
Dim FindUserXPath as String
FindUserXPath = "//Employee[UserName/text()='" & Request("Username") & "' And
Password/text()='" & Request("Password") & "']"
C#:
String FindUserXPath;
FindUserXPath = "//Employee[UserName/text()='" + Request("Username") + "' And
Password/text()='" + Request("Password") + "']";
With a normal username and password this XPath would work, but an attacker may send a bad username and password and get an XML node selected without knowing the username or password, like this: Username: blah' or 1=1 or 'a'='a
Password: blah
FindUserXPath becomes //Employee[UserName/text()='blah' or 1=1 or
'a'='a' And Password/text()='blah']
Logically this is equivalent to:
//Employee[(UserName/text()='blah' or 1=1) or
('a'='a' And Password/text()='blah')]
In this case, only the first part of the XPath needs to be true. The password part becomes irrelevant, and the UserName part will match ALL employees because of the "1=1" part.
Prevention of XPath Injection
Just like the techniques to avoid SQL injection, you need to use a parameterized XPath interface if one is available, or escape the user input to make it safe to include in a dynamically constructed query. If you are using quotes to terminate untrusted input in a dynamically constructed XPath query, then you need to escape that quote in the untrusted input to ensure the untrusted data can't try to break out of that quoted context. In the following example, single quotes (') are used to terminate the Username and Password parameters. So, we need to replace any ' characters in this input with the XML encoded version of that character, which is "&apos;".
Another better mitigation option is to use a precompiled XPath query. Precompiled XPath queries are already preset before the program executes, rather than created on the fly after the user's input has been added to the string. This is a better route because you don't have to worry about missing a character that should have been escaped.

Monday 13 July 2015

LDAP Injection

The Lightweight Directory Access Protocol is a protocol for querying and modifying directory services running over TCP/IP LDAP is a protocol for accessing a directory. A directory contains objects; generally those related to users, groups, computers, printers and so on; company structure information (although frankly you can extend it and store anything in there).
LDAP gives you query methods to add, update and remove objects within a directory (and a bunch more, but those are the central ones).
LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements using a local proxy. This could result in the execution of arbitrary commands such as granting permissions to unauthorized queries, and content modification inside the LDAP tree. The same advanced exploitation techniques available in SQL Injection can be similarly applied in LDAP Injection.
LDAP injection is a server side attack, which could allow sensitive information about users and hosts represented in an LDAP structure to be disclosed, modified, or inserted. This is done by manipulating input parameters afterwards passed to internal search, add, and modify functions.
Examples
Example 1
In a page with a user search form, the following code is responsible to catch input value and generate a LDAP query that will be used in LDAP database. <input type="text" size=20 name="userName">Insert the username</input>
The LDAP query is narrowed down for performance and the underlying code for this function might be the following: String ldapSearchQuery = "(cn=" + $userName + ")";
System.out.println(ldapSearchQuery);
If the variable $userName is not validated, it could be possible accomplish LDAP injection, as follows:
If a user puts “*” on box search, the system may return all the usernames on the LDAP base
If a user puts “jonys) (| (password = * ) )”, it will generate the code bellow revealing jonys’ password ( cn = jonys ) ( | (password = * ) )
How to Test LDAP Injection
Example 1: Search Filters
Let's suppose we have a web application using a search filter like the following one: searchfilter="(cn="+user+")"
which is instantiated by an HTTP request like this: http://www.example.com/ldapsearch?user=John
If the value 'John' is replaced with a '*', by sending the request: http://www.example.com/ldapsearch?user=*
the filter will look like: searchfilter="(cn=*)"
which matches every object with a 'cn' attribute equals to anything.
If the application is vulnerable to LDAP injection, it will display some or all of the users' attributes, depending on the application's execution flow and the permissions of the LDAP connected user.
A tester could use a trial-and-error approach, by inserting in the parameter '(', '|', '&', '*' and the other characters, in order to check the application for errors.
Example 2: Login
If a web application uses LDAP to check user credentials during the login process and it is vulnerable to LDAP injection, it is possible to bypass the authentication check by injecting an always true LDAP query (in a similar way to SQL and XPATH injection ).
Let's suppose a web application uses a filter to match LDAP user/password pair.
searchlogin= "(&(uid="+user+")(userPassword={MD5}"+base64(pack("H*",md5(pass)))+"))";
By using the following values: user=*)(uid=*))(|(uid=*
pass=password
the search filter will results in: searchlogin="(&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))";
which is correct and always true. This way, the tester will gain logged-in status as the first user in LDAP tree.
Prevention of LDAP Injection
Mechanisms used to prevent code injection techniques include defensive programming, sophisticated input validation, dynamic checks and static source code analysis. The work on mitigating LDAP injections must involve similar techniques.
The attacks presented in the previous sections are performed on the application layer, therefore firewalls and intrusion detection mechanisms on the network layer have no effect on preventing any of these LDAP injections. However, general security recommendations for LDAP directory services can mitigate these vulnerabilities or minimize their impact by applying minimum exposure point and minimum privileges principles

Sunday 12 July 2015

OS command injection

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.

How to Test OS command injection
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.
Example URL before alteration: http://sensitive/cgi-bin/userData.pl?doc=user1.txt
Example URL modified: http://sensitive/cgi-bin/userData.pl?doc=/bin/ls|
This will execute the command “/bin/ls”.
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
Example: http://sensitive/something.php?dir=%3Bcat%20/etc/passwd

Example
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: POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33
Doc=Doc1.pdf

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:
POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33
Doc=Doc1.pdf+|+Dir c:\

If the application doesn't validate the request, we can obtain the following result: Exec Results for 'cmd.exe /c type "C:\httpd\public\doc\"Doc=Doc1.pdf+|+Dir c:\'
Output...
Il volume nell'unità C non ha etichetta.
Numero di serie Del volume: 8E3F-4B61
Directory of c:\
18/10/2006 00:27 2,675 Dir_Prog.txt
18/10/2006 00:28 3,887 Dir_ProgFile.txt
16/11/2006 10:43
Doc
11/11/2006 17:25
Documents and Settings
25/10/2006 03:11
I386
14/11/2006 18:51
h4ck3r
30/09/2005 21:40 25,934
OWASP1.JPG
03/11/2006 18:29
Prog
18/11/2006 11:20
Program Files
16/11/2006 21:12
Software
24/10/2006 18:25
Setup
24/10/2006 23:37
Technologies
18/11/2006 11:14
3 File 32,496 byte
13 Directory 6,921,269,248 byte disponibili
Return code: 0
In this case, we have successfully performed an OS injection attack.

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...