Showing posts with label Session Management. Show all posts
Showing posts with label Session Management. Show all posts

15/04/2014

PHP Source Code Chunks of Insanity (Post Pages) Part 3

Intro 

This post is going to talk about source code reviewing PHP and demonstrate how a relatively small chunk of code can cause you lots of problems.

The Code

In this article we are going to analyze the code displayed below. The code displayed below might seem innocent for some , but obviously is not. We are going to assume that is used by some web site to post the user comments securely.
<?php require_once 'common.php'; validateMySession(); ?> <html> <head> <title>User Posts</title> </head> <body> <h1>Showing current posts</h1> <form action='awsomePosts.php'>
<p>MySearch: <input type='text'  value='<?php if (isset($_GET['search'])) echo htmlentities($_GET['search'])?>'></p> <p><input type='submit' value='MySearch'></p>
</form> <?php showAwsomePosts();?> </body>
</html>
If you look carefully the code you will se that the code is vulnerable to the following issue: Stored XSS!!
    
Think this is not accurate , think better.

The Stored XSS

An adversary would need to have very good knowledge of encoding/XSS attacks to exploit this vulnerability. This vulnerability is based on a well known UTF-­‐7 encoding attack that is considered to be old. Other filter bypassing techniques can be used to bypass htmlentities such as JavaScript events.

Vulnerable Code: 
1:  <p>MySearch: <input type='text' value='<?php if (isset($_GET['search'])) echo htmlentities($_GET['search'])?>'></p>// Vulnerable to XSS UTF-­‐7 attack  
The page that the potential XSS resides on doesn't provide a page charset header (e.g. header('Content-­‐ Type: text/html; charset=UTF-­‐8'); or <HEAD><META HTTP-­‐EQUIV="CONTENT-­‐TYPE" CONTENT="text/html; charset=UTF-­‐8">), any browser that is set to UTF-­‐7 encoding can be exploited with the following XSS input (she don't need the charset statement if the user's browser is set to auto-­‐ detect and there is no overriding content-­‐types on the page in Internet Explorer and Netscape rendering engine mode). This does not work in any modern browser without changing the encoding type.

Example1 UTF-­‐7 Encoding

Input Payload :

1:  <script>alert(1)</script>  

Output (UTF-­‐7): 
1:  +ADw-­‐script+AD4-­‐alert('XSS')+ADw-­‐/script+AD4APA-­‐/vulnerable+AD4-­‐  

Example2 JavaScript Events

Injecting also JavaScript events to the htmlentities function of php will also by pass the filter.

The code before injection:     
1<p>MySearch: <input type='text' value='<?php if (isset($_GET['search'])) echo htmlentities($_GET['search'])?>'></p>  

The code after injection:
<p>MySearch: <input type='text' value='onerror='alert(String.fromCharCode(88, 83, 83))'></p>  


Note: This example needs further testing to see if it is applicable.

Remedial Code:

Provide Server Side filters for the vulnerability. Make use of regular expressions and html encode the variables whether displayed back to the user or not.

1st Layer of defense 
1:  //XSS filter the value because this value might be printed later on back in the user. if preg_match ("/[a-­‐zA-­‐Z]+/", "", $search){  
2:  showPosts();  
3:  }  
Note: Using regular expressions to replace parts of the input and proceed with further processing the input is not recommended, once a malicious input is identified should be rejected (e.g. using preg_match instead of preg_replace).

2nd Layer of defense 
1:  header('Content-­‐Type: text/html; charset=UTF-­‐8');  
2:  // This function will convert both double and single quotes. mb_convert_encoding($search, 'UTF-­‐8');  


Countermeasures Summarized
  1. Specify charset clearly (HTTP header is recommended)
  2. Don't place the text attacker can control before <meta>
  3. Specify recognizable charset name by browser.
  4. Apply regular expressions based on the white list mentality.
Note: mb_convert_encoding converts the character encoding of the input string to the desired encoding. 

References:

1. https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#UTF-­‐7_encoding 
2. http://php.net/manual/en/function.mb-­‐convert-­‐encoding.php
3. http://shiflett.org/blog/2005/dec/google-­‐xss-­‐example
4. http://www.motobit.com/util/charset-­‐codepage-­‐conversion.asp
5. http://openmya.hacker.jp/hasegawa/security/utf7cs.html 
6. http://wiremask.eu/?p=tutorials&id=10 


14/04/2014

PHP Source Code Chunks of Insanity (Logins Pages) Part 1

Intro 

This post is going to talk about source code reviewing PHP and demonstrate how a relatively small chunk of code can cause you lots of problems.

The Code

In this article we are going to analyze the code displayed below. The code displayed below might seem innocent for some , but obviously is not. We are going to assume that is used by some web site to validate the credentials and allow the users to login.

 <?php  
     require_once 'commonFunctionality.php';  
        if (validateCredentials($someUsername, $somePassword)) {  
           header('Location: myIndex.php'); }  
        else {  
           header('Location: wrong_login.php'); }  
 ?>  

If you look carefully the code you will se that the code is vulnerable to the following issues:
  1. Reflected/Stored XSS
  2. Session Fixation/Session Hijacking 
  3. Lock Out Mechanism Not In Place
Think this is not accurate , think better.

Session Fixation/Session Hijacking

An adversary may on purpose exploit this vulnerability without the need of developing any costume tools (e.g. the session gets exposed in a blog post or within the same application or is passed in the http referrer and gets cached in a Web Proxy controlled by an adversary). Also this attack might be used to abuse user privileges (e.g. escalate privileges of one user by manipulating the session identifier, perform vertical and horizontal privilege escalation etc.). It should be noted at this point that the issues described above are possible only if the web application makes decisions based only on the session identifier.

Vulnerable Code:
session_unset(); // Improper handling of the session.  

Explanation:

The function shown above does not properly handle the session. The session_unset function just clears the $_SESSION variable. It’s equivalent to doing $_SESSION = array(); So this does only affect the local $_SESSION variable instance, but not the session data in the session storage, everything else remains unchanged, including the session identifier. In this occasion the session_unset is used to clear the session from user information, instead of the session_destroy function in the login page (instead of the logout page), which translates into not logging out properly the previous user (e.g. the next user will possibly again access to the account of the previous user).The Web Application makes decisions without evaluating other cookie parameters to give access to Web Resources (e.g. the decision making process is the username, a variable called logged_in and the session id). Ideally this should partly be fixed by using also another variable e.g. $_SESSION[‘logged_in’] = true (see code below). 

Exploitation:

An adversary may on purpose exploit this vulnerability without the need of developing any costume tools (e.g. the session gets exposed in a blog post or within the same application or is passed in the http referrer and gets cached in a Web Proxy controlled by an adversary). Also this attack might be used to abuse user privileges (e.g. escalate privileges of one user by manipulating the session identifier, perform vertical and horizontal privilege escalation etc.). It should be noted at this point that the issues described above are possible only if the web application makes decisions based only on the session identifier.

Business Impact:

The possibility of this vulnerability going public (e.g. blog posts start appearing in the internet revealing the issue) would cause severe costumer reputation and revenue loss; this vulnerability allows an adversary to potentially launch personalized phishing attacks (e.g. deceive a user in clicking a link with a fixed session etc.) abuse web application user privileges and possibly allow phishing campaigns. 

Remedial Code: 
 function init_session() { ...  
 session_start(); // Start the php session  
 session_regenerate_id(true); // regenerated the session, delete the old one. $_SESSION['logged_in'] = true;  
 ... }  
Regenerate the session ID anytime the session's status changes. That means any of the following:
  1. User authentication (e.g. in the login page, other multiple authentication stages etc.).
  2. Storing privilege level information in the session (e.g. temporary random variables, valid only
    for the current session etc.)
  3. Regenerate the session identifier whenever the user's privilege level changes. 
Lock Out Mechanism Not In Place

An adversary may on purpose exploit this vulnerability without the need of developing any costume tools (e.g. make use of Burp Intruder or Hydra to perform online password cracking attacks etc.).

Vulnerable Code:

 $username = $_POST['username']; $password = $_POST['password'];  
Note: The Web Application should implement server side controls in the login page to prevent password brute forcing attacks.

Remedial Code:


 function lockout($username, $password) { $now = time();  
 $counter = 0  
 if (validateCredentials){  
 $counter = $counter+1// Save that in database, retrieve login attempt times and compare the  
 times ...  
 } }  

The Web Application should take the following actions to prevent online dictionary attacks:
  1. Make use of login attempt counters (e.g. allow 3 failed attempts within 30 minutes).
  2. Associate the user IP with the session (e.g. generate proper audit trails to later on ban that ip).
    Include the user's IP address from $_SERVER['REMOTE_ADDR'] in the session. Store it in
    $_SESSION['remote_ip'].
  3. Run integrity checks of the session (although this functionality might be included in another
    function).
  4. Include the user agent from $_SERVER['HTTP_USER_AGENT'] in the session. Store it in a session
    variable $_SESSION['user_agent']. Then, on each subsequent request check that it matches (Note: The user agent can be very easily spoofed). 
Note: It should also be noted that since the session parameters are also populated with sensitive information such as the username, further actions should be performed to remove all this information (e.g. replace username with temporary user-­‐id). Gaining access to the username can significantly reduce a brute-­‐force login attempt. 

Reflected/Stored XSS

An adversary can exploit this vulnerability without the need of developing any costume tools. Point and click tools are available in the Internet and might be used to exploit this vulnerability (e.g. Social Engineering Tool etc.). Further escalating on the issue an adversary might use this attack to compromise multiple company sites (e.g. make use of it as an XSS proxy).

Note: This might also lead into unrestricted redirection attacks. Due to limited amount of time in my disposal no further investigation was conducted (e.g. load the login page to an Apache as and see if the variable username is passed the URL or the location header field.) 

Vulnerable Code:
 $_SESSION['username'] = $username;  

Note: Even though we don’t have access to the rest of the Web App code, it is highly likely that the username value might be displayed back to the user and the Http header fields. 

Remedial Code: 

Provide Server Side filters for the vulnerability. Make use of regular expressions and html encode the variables whether displayed back to the user or not (for providing security in depth and making sure that the Set-­‐Cookie header field or other fields cannot be abused).

1st Layer of defense

 $username = preg_match ("/[^a-­‐zA-­‐Z0-­‐9_\-­‐]+/", "", $username)  

Note: Ideally the username should be replaced with a temporary user id (preferable random that expires along with the cookie session). Using regular expressions to replace parts of the input and proceed with further processing the input is not recommended, once a malicious input is identified should be rejected (e.g. using preg_replace instead of preg_match). Also note that this functionality should ideally be also part of the validateCredentials function or the input should be processed before used by the validateCredentials function. 

2nd Layer of defense


1. // This function will convert both double and single quotes. 
2. htmlentities($username , ENT_QUOTES);  

Input: 
 <script>alert(1)</script>   

Output:
 &#x3c;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3e;&#x61;&#x6c;&#x65;&#x72;&#x7 4;&#x28;&#x31;&#x29;&#x3c;&#x2f;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3e;  


Note: With htmlentities, all characters which have HTML character entity equivalents are translated into these entities (displayed above). 

References:

  1. https://www.owasp.org/index.php/Account_lockout_attack
  2. http://stackoverflow.com/questions/17217777/difference-­‐between-­‐unset-­‐and-­‐session-­‐unset-­‐ in-­‐php
  3. http://shiflett.org/articles/session-­‐fixation
  4. http://shiflett.org/articles/session-­‐hijacking 

26/12/2012

CSRFing the Web...

Introduction

Nowadays hacking, as already mentioned in my previous articles, has been industrialized, meaning that professional hackers are constantly hired to make money out of practically anything and therefore all Web Application vulnerabilities have to be understood and defeated.

This article is going to talk about what Cross Site Request Forgery (CSRF) is, explain how can someone perform a successful CSRF attack and describe how to amplify a CSRF attack (e.g. combine CSRF with other vulnerabilities). CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated (simplistically speaking). With a little help from social engineering (like sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker's choosing.

A successful CSRF exploit can compromise end user data and operation in case of a normal user. If the targeted end user is the administrator account, this can compromise the entire web application. More specifically CSRF is a Web Application vulnerability that has to exploit more than one design flaws in order to be successful. The design flaws that a CSRF attack can take advantage of are:
  1. Input Validation (e.g. Convert POST to GET) 
  2. Access Control (e.g. Session Fixation) 
  3. Privilege Assignment (e.g. Horizontal Privilege Escalation)
Note: Of course depending on the situation other type of vulnerabilities can be combined with a CSRF as part of a post exploitation process such as SQL Injection (e.g. SQL Inject the cookie and get access to valid cookie repository in the database).

History of CSRF

CSRF vulnerabilities have been known and in some cases exploited since 2001. Because it is carried out from the user's IP address, some website logs might not have evidence of CSRF. Exploits are under-reported, at least publicly, and as of 2007 there are few well-documented examples. About 18 million users of eBay's Internet Auction Co. at Auction.co.kr in Korea lost personal information in February 2008. Customers of a bank in Mexico were attacked in early 2008 with an image tag in email. The link in the image tag changed the DNS entry for the bank in their ADSL router to point to a malicious website impersonating the bank.

Severity of CSRF

According to the United States Department Of Homeland Security the most dangerous CSRF vulnerability ranks in at the 909th most dangerous software bug ever found. Other severity metrics have been issued for CSRF vulnerabilities that result in remote code execution with root privileges as well as a vulnerability that can compromise a root certificate, which will completely undermine a public key infrastructure.

But what exactly is a CSRF

CSRF is a form of confused deputy attack. Imagine you’re a malcontent who wants to harm another person in a maximum security jail. You’re probably going to have a tough time reaching that person due to your lack of proper credentials. A potentially easier approach to accomplish your misdeed is to confuse a deputy to misuse his authority to commit the dastardly act on your behalf. That’s a much more effective strategy for causing mayhem.

In the case of a CSRF attack, the confused deputy is your browser. After logging into a website, the website will issue your browser an authentication token within a cookie (well not always). Within each subsequent http POST or GET requests send, the cookie bind to the request will let the site know that you are authorized to take whatever action you’re taking. Here I am referring to a typical authentication and authorization scheme that most Web Application use.

Suppose you visit a malicious website soon after visiting your bank website or visit another website while being logged to your bank web account. Your session on the previous site might still be valid (btw please de-validate session before closing the browser). Thus, visiting a carefully crafted malicious website (perhaps you clicked on a spam link) could cause an Html form post to the previous website. Your browser would send the authentication cookie back to that site and appear to be making a request on your behalf, even though you did not intend to do so.

Yes but what is a CSRF

A CSRF is a POST or GET http request that when send to the vulnerable Web Application under certain conditions can cause the Web Application to perform an action on behalf of the user. Now meaningful CSRF attacks are those that can cause loss of Integrity or Confidentiality or Availability of the victim user data. For example if an e-Banking Web site is vulnerable to CSRF and the function of the Web Site that is vulnerable is responsible for transferring money, then this is a CSRF with high severity and should be fixed.

This is an example of a simple CSRF:

http://www.vulnerable.com/?transferEuros=3000?maliciousUserAccount=9832487   

Note: The link displayed above when clicked can authorize a malicious user to transfer 3000 euros from of the victim user account to the malicious user account with id 9832487, assuming of course that no proper counter measures have been taken.

The following diagram shows how can this happen more analytically:   




Note: The diagram above shows the steps an attacker can take to exploit the vulnerability (step 4 designtes the execution of the CSRF payload that performs the malicious action). It is pretty much similar to a Cross Site Script attack scenario. An attacker sends an e-mail to an Html enabled e-mail client that contains some sample images deliberately uploaded to a malicious server (controlled by the attacker), along with the malicious URL (or a malicious html form) that performs the CSRF function, waits until the user opens the e-mail and downloads the images or sets his/her e-mail to receive a notification when the victim user reads his/her e-mail. Thens he/she waits infront of the logs of the malicious image server or waits to receive a read e-mail receipt in his/her mailbox. After the image is downloaded or the read receipt is received he/she will try to verify that the malicious function was executed. Another scenario would be to calculate what times user interact with the web site and calculate the attack times before sending the malicious URL/Html form.

The diagram above explains that the CSRF (meaning the vulnerable link described previously) can be injected into an HTML enabled e-mail and be executed by a legitimate user. Now if the link (or else the CSRF vulnerable link) is bind to the Web Application session (which it should be) then the victim user would have to be logged to the vulnerable Web Application for the attack to be successful. If the link is not bind to the Web Application session then the this is not a CSRF vulnerability, is an Insecure Direct Object References vulnerability or Failure to Restrict URL Access also described by OWASP top 10 chart. Both vulnerabilities have to do with inappropriate access control and are completely irrelevant to CSRF or CSRF like vulnerabilities.

Now that you got a better grasp of what a CSRF attack is I can be more technical and explain more on how a CSRF attack look like by using http requests. So again the link described above looks as a Http request like that:

GET /homepage/transferEuros=3000?maliciousUserAccount=9832487 HTTP/1.1
Host: victim.com
Keep-Alive: timeout=15
Connection: Keep-Alive
Cookie: Authentication-Token
Accept: */*

Note: The vulnerable link when clicked will generate the GET request shown above and will, if it is successful, generate a 200 Http response message saying that the transaction was completed successfully.

Explaining more what a CSRF is

The following diagram shows thoroughly how a CSRF can be exploited:



Step 1: Mallory sends a phishing email to Bob, inviting him to visit her web server in order, for example, to win an iPhone 5. She has already created a web page at her web server with a hidden request to the Web Application where Bob is logged in. She has added some buttons to lure the victim in order to click on her page and win the iPhone!

Step 2: Bob visits the page at Mallory's Web server. Maybe he is greedy or he may not, however he clicks on the button in order to win the iPhone!...

Step 3: The forged request is "legitimized" with Bob's logged-in session and is executed at the web application.

A real-world analogy would be the following: Mallory presented a bank cheque to Bob and Bob puts under his name and signature, but haven't examined what sum of money is written on the cheque.In the following attack scenario, we can see how a malicious user can add a user to a web application just by fooling a logged-in administrator to click on a link.

A different approach to CSRF

Now that I explained a simple CSRF attack it is time to explain a more advanced scenario on how to exploit a CSRF. A CSRF most of the time is not easily recognizable and that is why lots of people cannot identify a CSRF unless it is really obvious, just like the one I just described. A CSRF issue raises when:
  1. A Web Application performs critical functions using GET Http requests (e.g. to transfer money, add users by just clicking a link etc).
  2. Does not distinguish between POST and GET requests (e.g. a Html form can be easily converted into a GET request, meaning that a Html POST request can be converted to a link etc). 
  3. Has a loose association or else not tight access control (e.g. does not use AntiCSRF tokens, is vulnerable to session fixation e.t.c).
  4. Is vulnerable to Cross Site Scripting (e.g. someone can use JavaScript to formate a valid Html POST form by using the XMLHTTP object along with an auto submit script etc). 
  5. The application is passing the session to the URL along with the AntiCSRF token.
  6. The session can be fixated and the AntiCSRF token is predictable or static.
Note: There are a lot more ways to perform a CSRF attack, but there are out of scope.

CSRF and POST to GET Interchange

It is common knowledge that when the Web Application does not distinguish between POST and GET requests an attacker can convert a POST Http request to a GET Http request and generate a link equivalent to the one described previously. Burp Suite does that automatically that from the proxy tab by right clicking the request and doing a change method (it also recalculates the Http request size in the content size field).

The attack just described is can be enhanced by using an auto submit script such as this one:

"JavaScript"> setTimeout('document.CSRFHtmlForm.submit()',5000);

Note: A very useful tool is the CSRF PoC tool also found in Burp Suite. Burp Suit CSRF PoC will generate a quick CSRF PoC for you (most of the time you would have to modify that to be realistic).

CSRF and Cross Site Scripting (XSS)

Cross-Site Scripting (XSS) attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in 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 your browser and used with that site. These scripts can even rewrite the content of the HTML page. But can also inject an Html form with an auto submit script to execute the malicious CSRF. The example is very easy to understand so I wont have to give an example.

Note1: You can see how an XSS vulnerability can be combined with a CSRF  attack at the CSRF tool section (e.g. by injection also the auto submit javascript code along with the CSRF).

Note2: Of course an XSS can be combined with a CSRF attack using the XMLHTTP and auto submit javascript features. A very good XSS (XMLHTTP)/CSRF example can be found here. The specific post explains an XSS/CSRF bug found in gmail.

CSRF and Session Fixation

Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of inducing a user to authenticate himself with a known session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim's browser use it.

The session fixation attack is a class of Session Hijacking, which steals the established session between the client and the Web Server after the user logs in. Instead, the Session Fixation attack fixes an established session on the victim's browser, so the attack starts before the user logs in. There are several techniques to execute the attack; it depends on how the Web application deals with session tokens. Below are some of the most common technique:
  • Session token in the URL argument: The Session ID is sent to the victim in a hyperlink and the victim accesses the site through the malicious URL.
  • Session token in a hidden form field: In this method, the victim must be tricked to authenticate in the target Web Server, using a login form developed for the attacker. The form could be hosted in the evil web server or directly in html formatted e-mail.
  • Session ID in a cookie:
    • Client-side script:
      • Most browsers support the execution of client-side scripting. In this case, the aggressor could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the function document.cookie, the browser which executes the command becomes capable of fixing values inside of the cookie that it will use to keep a session between the client and the Web Applicatio
    • <META> tag:
      • <META> tag also is considered a code injection attack, however, different from the XSS attack where undesirable scripts can be disabled, or the execution can be denied. The attack using this method becomes much more efficient because it's impossible to disable the processing of these tags in the browsers.
After describing the Session Fixation attack I will explain the attack scenario described in the picture using new chain of vulnerabilities (e.g. Session Fixation -> CSRF). An attacker sends an e-mail to an Html enabled e-mail client that contains some sample images uploaded to a malicious server, along with the malicious URL that performs the CSRF function and this time is bind to the fixed session (by using one or more of the techniques described above), waits until the user opens the e-mail and downloads the images or sets his/her e-mail to receive a notification when the victim user reads his/her e-mail. Thens he/she waits the logs of the malicious image server to be updated or waits to receive a read e-mail receipt in his/her mailbox. After the image is downloaded (and he/she sees that from e.g. /www/var/apache.logs etc) or the read receipt is received he/she will try to verify that the malicious function was executed.

The link with the fixated token will produce a GET Http request that looks like this:

GET /homepage/transferEuros=3000?maliciousUserAccount=9832487 HTTP/1.1
Host: victim.com
Keep-Alive: timeout=15
Connection: Keep-Alive
Cookie: Fixated Session

Note1: Obviously a Session Fixation attack can have devastating results even without the use of CSRF flaw. What I am saying here is that a Session Fixation combined with a CSRF attack amplifies the attack (e.g. the attacker will optimize his/her time attack frame by exploiting a chain of vulnerabilities rather than a single vulnerability).

Note2: Similar exploitation scenarios you can have when the web application does not provide the user with an authentication mechanism e.g. open registration forms used for submitting credit card details.

CSRF and bad architecture design

Although this category might not be exactly a CSRF issue, it is still very similar to a CSRF attack. This type of attack refers to the occasions were no proper random values are generated (based on user credentials) or values that are generated but do not have a session like behavior e.g. lack of authorization,  none random CAPTCHA, lack of entity authentication etc. By integrating this type of behavior to your application you endanger the application to became victim to multiple type of attacks.   

CSRF and Clickjaking

Clickjacking, also known as a "UI redress attack", happens is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. Thus, the attacker is "hijacking" clicks meant for their page and routing them to other another page, most likely owned by another application, domain, or both. Using a similar technique, keystrokes can also be hijacked. With a carefully crafted combination of stylesheets, iframes, and text boxes, a user can be led to believe they are typing in the password to their email or bank account, but are instead typing into an invisible frame controlled by the attacker.

For example, imagine an attacker who builds a web site that has a button on it that says "click here for a free iPod". However, on top of that web page, the attacker has loaded an iframe with your vulnerable e-banking account, and lined up exactly the "transfer money" button directly on top of the "free iPod" button. The victim tries to click on the "free iPod" button but instead actually clicked on the invisible "transfer money" button. In essence, the attacker has "hijacked" the user's click, hence the name "Clickjacking". Again the attack scenario would be the similar to the ones just described above so there is no need for me to modify and explain again the attack scenarion. What is interesting though would be to show you an iframe that performs a CSRF attack.

Well an iframe that performs a CSRF attack would look something like that:

<iframe src="http://www.victim.com/homepage/transferEuros=3000?maliciousUserAccount=9832487">

Note: You can see how beautiful this attack is and how simple and smooth can be implemented.

CSRF and Exposed Session Variables

By simply passing the session or other session variables in the URL e.g. such the AntiCSRF token, means asking for trouble. The Session Tokens (Cookie, SessionID, Hidden Field), if exposed, will usually enable an attacker to impersonate a victim and access the application illegitimately. As such, it is important that they are protected from eavesdropping at all times – particularly whilst in transit between the Client browser and the application servers.

The information here relates to how transport security applies to the transfer of sensitive Session ID data rather than data in general, and may be stricter than the caching and transport policies applied to the data served by the site. Using a personal proxy, it is possible to ascertain the following about each request and response:
  • Protocol used (e.g., HTTP vs. HTTPS)
  • HTTP Headers
  • Message Body (e.g., POST or page content)
Each time Session ID data is passed between the client and the server, the protocol, cache, and privacy directives and body should be examined. Transport security here refers to Session IDs passed in GET or POST requests, message bodies, or other means over valid HTTP requests. As you already understand stealing the Session ID and/or the AntiCSRF token might result in the attacker being able to form links such as the following one:

http://www.vulnerable.com/?sessionid=ligdlgkjdng?anticsrftoken=kjnsdldfksjdnk?transferEuros=3000?maliciousUserAccount=9832487   

Note: The above information can be used to generate a link for a malicious user.

The attack scenario?

For my demo I choose multidae vulnerable web application which can be found on OWASP's Vulnerable Apps VM, an intercepting proxy tool (I used Portswigger's Burp Proxy, however it is not essential, just a "View Source" from any browser can work on most cases) and an Apache web server.

In the following picture you can see the main page of Multidae's web application as it can be browsed by any -non authenticated- user.




In this web application any user can register an account, but our goal is to register the account with the administrator's privileges. Below is the "register user" page that any, unauthenticated user can see.




If we view the source of the "Register Account" page, we can identify the forms (and therefore the POST request) that are being sent to the web application. That data are then processed by the application and the user is created.


Now, the attacker can create his own form at his web server and populate the HTML fields with the data of the user he wants to create on the system. (Note: no code expertise is needed in order to create this HTML page!). The following picture, you can see the HTML page that creates on his web server. He creates a user named "andrew", with password "qwerty".


Now he launches the web server (192.168.200.14) hosting this page. At this point, he needs the user's interaction. This could be accomplished, for example, by a phishing attack scenario: the victim receives an email inviting the victim to visit the attacker's page saying "click here to win an iPhone 5", or he could attach this message this "iPhone 5 message" at the page he created!

Just imagine:



And this is how it will appear on the victim's web browser:


The victim, which is at the same time logged in with this account at Multidae web application, is now tricked to click on the button and submit a register user form with the username and password set by the attacker.

 Now user "andrew" can log in with the password set during the CSRF request.


At point the CSRF attack scenario is completed. We sucessfuly managed to exploit a CSRF vulnerability and add a user to the vulnerable web application.

The CASE studies for CSRF

This site here contains many popular web sites that were vulnerable to CSRF attacks. An interesting extract from the article can be found here:

"1. ING Direct (ingdirect.com)
Status: Fixed
We found a vulnerability on ING’s website that allowed additional accounts to be created on behalf of an arbitrary user. We were also able to transfer funds out of users’ bank accounts. We believe this is the first CSRF vulnerability to allow the transfer of funds from a financial institution. Specific details are described in our paper.
2. YouTube (youtube.com)
Status: Fixed
We discovered CSRF vulnerabilities in nearly every action a user could perform on YouTube. An attacker could have added videos to a user’s "Favorites," added himself to a user’s "Friend" or "Family" list, sent arbitrary messages on the user’s behalf, flagged videos as inappropriate, automatically shared a video with a user’s contacts, subscribed a user to a "channel" (a set of videos published by one person or group) and added videos to a user’s "QuickList" (a list of videos a user intends to watch at a later point). Specific details are described in our paper.
3. MetaFilter (metafilter.com)
Status: Fixed
A vulnerability existed on Metafilter that allowed an attacker to take control of a user’s account. A forged request could be used to set a user’s email address to the attacker’s address. A second forged request could then be used to activate the "Forgot Password" action, which would send the user’s password to the attacker’s email address. Specific details are described in our paper.
(MetaFilter fixed this vulnerability in less than two days. We appreciate the fact that MetaFilter contacted us to let us know the problem had been fixed.)
4. The New York Times (nytimes.com)
Status: Not Fixed. We contacted the New York Times in September, 2007As of September 24, 2008, this vulnerability still exists. This problem has been fixed."

Note: You can see from the above extract that CSRF issues are very popular these days.

Tools for CSRFing the Web

The Burp Proxy tool (the Pro version of course) can be used to generate a proof-of-concept (PoC) cross-site request forgery (CSRF) attack for a given request.To access this function, select a URL or HTTP request anywhere within Burp, and choose "Generate CSRF PoC" within "Engagement tools" in the context menu.

When you execute this function, Burp shows the full request you selected in the top panel, and the generated CSRF HTML in the lower panel. The HTML uses a form with a suitable action URL, encoding type and parameters, to generate the required request when the browser submits the form.You can edit the request manually, and click the "Regenerate" button to regenerate the CSRF HTML based on the updated request.

You can test the effectiveness of the generated PoC in your browser, using the "Test in browser" button. When you select this option, Burp gives you a unique URL that you can paste into your browser (configured to use the current instance of Burp as its proxy). The resulting browser request is served by Burp with the currently displayed HTML, and you can then determine whether the PoC is effective by monitoring the resulting request(s) that are made through the Proxy.Some points should be noted regarding form encoding:

    •    Some requests (e.g. those containing raw XML or JSON) have bodies that can only be generated using a form with plain text encoding. With each type of form submission using the POST method, the browser will include a Content-Type header indicating the encoding type of the form that generated the request. In some cases, although the message body exactly matches that required for the attack request, the application may reject the request due to an unexpected Content-Type header. Such CSRF-like conditions might not be practically exploitable. Burp will display a warning in the CSRF PoC generator if this is liable to occur.

    •    If you manually select a form encoding type that cannot be used to produce the required request, Burp will generate a best effort at a PoC and will display a warning.

    •    If the CSRF PoC generator is using plain text encoding, then the request body must contain an equals character in order for Burp to generate an HTML form which results in that exact body. If the original request does not contain an equals character, then you may be able to introduce one into a suitable position in the request, without affecting the server's processing of it.

CSRF PoC Options

The following options are available:

    •    Include auto-submit script - Using this option causes Burp to include a small script in the HTML that causes a JavaScript-enabled browser to automatically submit the form (causing the CSRF request) when the page is loaded.

    •    Form encoding - This option lets you specify the type of encoding to use in the form that generates the CSRF request. The "Auto" option is generally preferred, and causes Burp to select the most appropriate encoding capable of generating the required request. 

The following picture shows a screen shot from Burp CSRF PoC tool while doing right click on an intercepted request:


The following picture shows the generated CSRF PoC:


Note: Right click the intercepted Http GET or POST request and click CSRF PoC. It should not be a problem if the web application accepts POST to GET interchanges for obvious reasons.


Prevention Measures That Do NOT Work

Using a Secret Cookie:

Remember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.

Only Accepting POST Requests:

Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.

Multi-Step Transactions:

Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or deduce each step of the completed transaction, then CSRF is possible.

URL Rewriting:


This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.

CSRF countermeasures 

CSRF attacks are very hard to trace and probably are not traceable unless one the two or more of the following conditions are met:
  1. Detailed Web Application user auditing exists and is enabled.
  2. Concurrent logins are not allowed (allowing concurrent logins would remove none repudiation).
  3. The Web Application binds the Web Application session with the user IP (that way if the user is behind a NAT only users from the same intranet would be able to perform a CSRF attack).
  4. AntiCSRF tokens are used per Web Application function. An AntiCSRF token in order to be effective would have to be:
    • Truly Random.
    • Bind to every Web Application function (different per Web Application function).
    • Behave like a session (e.g. expire after a certain time, expire e.t.c).
    • Use a two factor authentication per token (e.g make of a RSA token to generate the AntiCSRF to perform a transaction etc).
Other technologies for protecting against CSRF

In the web there are numerous references regarding the implementation of anti-CSRF tokens. Some examples can be found here: 
The mentality promoted by the above technologies is abvious, we should deploy a mechanism that would make unique every session initiated by the user. This can be achieved by sending the browser an anti-CSRF token that would be appended in every request the browser sends to the server. The above technique is being explained in more technical terms in OWASP's CSRF Prevention cheat sheet:

"These challenge tokens are the inserted within the HTML forms and links associated with sensitive server-side operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. Inclusion of a required security token in HTTP requests associated with sensitive business functions helps mitigate CSRF attacks as successful exploitation assumes the attacker knows the randomly generated token for the target victim's session. This is analogous to the attacker being able to guess the target victim's session identifier."

Epilogue

This blog post attempted to cover thoroughly the subject of CSRF and I believe that I managed to do that. Now there are obviously a lot more things to say about how to protect against a CSRF but for the purposes of this post is out of scope. Merry Christmas and a Happy New year.

References:
  1. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
  2. http://en.wikipedia.org/wiki/Cross-site_request_forgery
  3. https://www.owasp.org/index.php/Testing_for_Exposed_Session_Variables_(OWASP-SM-004)
  4. http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx
  5. https://www.owasp.org/index.php/Session_fixation
  6. http://ajaxian.com/archives/gmail-csrf-security-flaw
  7. http://www.portswigger.net/burp/help/suite_functions_csrfpoc.html
  8. https://nealpoole.com/blog/2012/03/csrf-clickjacking-and-the-role-of-x-frame-options/
  9. http://fragilesecurity.blogspot.gr/2012/11/cross-site-request-forgery-legitimazing.html
  10. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  11. https://blogs.apache.org/infra/entry/apache_org_04_09_2010
  12. https://freedom-to-tinker.com/blog/wzeller/popular-websites-vulnerable-cross-site-request-forgery-attacks/
  13. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Viewstate_.28ASP.NET.29

29/07/2012

Hacking the Session for fun and profit

Intro

This post is about describing from the security perspective how the life cycle of a Web Application should be. By saying life cycle I mean all the stages a session goes through and what are the steps to be taken on order to properly test the session. Very recently I had a discussion about session management with a colleague of mine and he seemed confused about what session management is and how it should be handled. Now if you lookup the OWASP session management cheat sheet you are going to find lots of interesting information overlapping the information presented here but, there is no information in the internet that has a complete and easy to understand guide about how to test a session.

What is a Session and how should it behave

A web application session is a user credential "representative" for as long as the user is logged in (well not always). In more simple words the user credentials after a successful log-in should be translated into one or more cryptographically secure variable that:
  1. Should not leak (e.g. no session passed in web application URL) while being valid.
  2. Should not be predictable (that is what cryptographically secure means).
  3. Should expire under certain conditions (e.g. user log out).
  4. Should not be recyclable (e.g. do not save in database). 
  5. Should be mascaraed (e.g. do not use the default framework .NET name).
  6. Should be tamper-prof (e.g. run regular integrity checks).
  7. Should not be cloned (e.g. concurrent log-ins should not be supported).
  8. Should be audited (e.g. track user id and session pair and log events)
  9. Should have a 1-1 relationship with the username or user id (e.g. one session variable should translate in one username)   
Note: If one or more of the conditions described above is not met then your session is open to be attacked.

Session life cycle conceptual representation

The following diagram shows the session life cycle and how it should be according to me view. The purple color shows what it should be checked, the green shows how to perform hardening, all other is parts of the diagram is about about attacks that can be performed at that specific session stage. The attacks in red are the most critical and should be characterized as high impact attacks, the attacks in yellow should be characterized as medium impact and the attacks in green have information leakage impact in the web application.
  
  

Note: See how the the session attacks performed after the session authorization are all red. Take note also to the fact that almost all attacks concerning session are red.

The following diagram explains the signs used above:


Note: The image above is self explanatory.

The Session Checklist

The following part of the article attempts to specify the exact characyetristics a session should have and what you should check in more detail:
  • Session Properties:
  1. Session ID Name Fingerprinting
    1. Change Session Default Name
    2. Use additional proper costume secure tokens
  2. Session ID Length
    1. Chose Big Length (e.g. the session ID length must be at least 128 bits 16)
  3. Session ID Entropy
    1. Use true random numer generator for the session
    2. Refresh after login
  4. Session ID Content (or Value)
    1. Don't save critical Web Application Data in session
    2. Use meaningless data to the session 
  • Session Attributes:
  1. Secure Attribute
    1. Set secure flag (or simply enforce SSLv3/TLSv1)
  2. HttpOnly Attribute
    1. Set HttpOnly flag
    2. Disable TRACE http method
  3. Domain and Path Attributes
    1. Restrict Path
    2. Do not include cross domain scripts from none trusted third parties 
  4. Expire and Max-Age Attributes 
    1. Make sure cookies expire after log-off 
  • Session Input Validation Defense Mechanisms:
  1. Manage Session ID as Any Other User Input
  2. Renew the Session ID After Any Privilege Level Change
  3. Renew Session after authorizing the session
  • Session Leakage
  1. Do not pass session into Http referrer header field. 
  2. Do not pass session into web application urls.
  • Session Termination:
  1. Idle Timeout (e.g. after 15 minutes of user inactivity)
  2. Absolute Timeout (e.g. force expiration after 3 hours)
  3. Manual Session Expiration (e.g. increase user security awareness by giving them de-validation options)
  4. Logout Button 
  5. Force Session Logout On Web Browser Window Close Events
  6. Automatic Client Logout 3 Session Attacks Detections
    1. Session ID Guessing and Brute Force Detection
    2. Detecting Session ID Anomalies
    3. Binding the Session ID to Other User Properties 
  • Session Event Auditing:
  1. Monitor Session Creation
  2. Monitor Destruction of Session IDs 
  3. Monitor simultaneous Session Log-ons
  4. Export session auditing into syslog format and feed it to an event correlation engine
  5. Implement costume e-mail alerts (e.g. for multiple access denied events). 
Cookie/Session token reverse engineering

Questions to answer about cookie reverse engineering:

  1. Unpredictability: a cookie must contain some amount of hard-to-guess data. The harder it is to forge a valid cookie, the harder is to break into legitimate user's session. If an attacker can guess the cookie used in an active session of a legitimate user, he/she will be able to fully impersonate that user (session hijacking). In order to make a cookie unpredictable, random values and/or cryptography can be used.
  2. Tamper resistance: a cookie must resist malicious attempts of modification. If we receive a cookie like IsAdmin=No, it is trivial to modify it to get administrative rights, unless the application performs a double check (for instance, appending to the cookie an encrypted hash of its value)
  3. Expiration: a critical cookie must be valid only for an appropriate period of time and must be deleted from disk/memory afterwards, in order to avoid the risk of being replayed. This does not apply to cookies that store non-critical data that needs to be remembered across sessions (e.g., site look-and-feel).
  4. "Secure” flag: a cookie whose value is critical for the integrity of the session should have this flag enabled in order to allow its transmission only in an encrypted channel to deter eavesdropping.
Epilogue 

The diagram shown above should be enough to give you a good information and a new perspective about how session should be handled. Hope this helped.....

Reference:

https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
https://www.owasp.org/index.php/Testing_for_Session_Management_Schema_(OWASP-SM-001)