Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

XSRF: What is it, How does it work, and How can you thwart it?

Written by pbmods, July 20th, 2007
A somewhat obscure hack has emerged recently that is an offshoot of the now-infamous XSS.

It is known as Cross-Site Request Forgery, or XSRF for short. XSRF is a form of temporary identity theft that can cause your computer to initiate banking transactions, send emails or text messages, or even change account info on your favorite site... without your ever realizing it!

THE GOOD NEWS

Before we get started on the doom and gloom, you should know that XSRF, while potentially very devastating, is actually very easy to defend against.

Also, many modern sites employ anti XSS and XSRF techniques (such as the ones listed at the bottom of this article) so that even if somebody tried to pull an XSRF on your account, it would not work.

THE SETUP

As an example of XSRF in action, suppose your favorite bank has a website that uses $_GET to pass account transaction data. So if you wanted to transfer $100 from account 1002 to account 1004, you'd go to:

Code: ( text )
  1. http://myawesomebank.com/transfer.php?from=1002&to=1004&amt=100


At this point, you are probably thinking, "there's something REALLY wrong with that!" And you're right. But no problem... even if somebody tried to go to this URL to make a quick $100, he'd still have to be logged in to do it, right?

Wrong.

So our intrepid hacker goes to your favorite forum site, and creates a post with an image tag in it. But instead of a valid image file, he gives it a nasty uri:
Code: ( text )
  1. <img src="http://myawesomebank.com/transfer.php?from=1002&to=1004&amt=100" />


THE HAPLESS VICTIM

Now for the fun part. Let's say you were recently visiting myawesomebank.com to check your account balance. Let's also say that, like most normal people, you didn't log out of your account before closing the browser window. Tsk Tsk.

You notice that there's a new post on your favorite forum site, so you go look at it. Oddly, there's an image on there, but it won't show up.

You refresh the page a few times, but you can't see the picture. You give up and go to bed.

The next day, when you go to check your account balance, you're short $500!

WHAT HAPPENED?

When you opened the page that contained the XSRF code, your browser saw an IMG tag and sent a request for the src of that image as part of loading the page.

Never mind that the src didn't end with a valid image extension; that's actually fairly common, as many sites will use a PHP (or other server-side) script to fetch images from a database or outside the server's document root.

So your browser sent the request, and it got a response, namely myawesomebank.com's "transaction complete" page. Of course, this wasn't valid image data, so your browser didn't show you anything.

"But," you might insist, "I wasn't on my bank's website when I loaded the XSRF code!" Maybe you THOUGHT you weren't, but according to your bank, since your session cookie was linked to an unexpired session, you actually were STILL LOGGED IN! Which means that any requests that got sent to your bank's server were processed, even though you didn't type the location into your address bar!

HOW TO PROTECT YOURSELF
  • ALWAYS log out of any site that you log into before closing your browser window or going to a different site.
  • If an image isn't loading (ESPECIALLY on a 'public-writable' site such as a forum or mailing list, DON'T REFRESH THE PAGE! Right-click on the image and select 'Propertes' (on IE or FireFox), or 'Copy Image Address' (on Safari) and VERIFY THAT THE FILE IS AN IMAGE.
  • If you think you are a victim of XSRF, TAKE ACTION IMMEDIATELY! Contact the administrator of the site that was targeted and get the damage undone!
  • If you think someone has posted XSRF code on a forum or other site, inform the site administrator IMMEDIATELY so that he can remove the code and ban the offender!

HOW TO SECURE YOUR SITE AGAINST XSRF
  • NEVER pass sensitive data in the address. Use POST as much as you can.
  • Check the referring page (via $_SESSION['HTTP_REFERER']) before executing any backend code! If the domain doesn't match yours, DON'T PROCESS THE REQUEST!
  • Enforce session timeout. When the User hasn't submitted any requests for a period of time, his session should automatically expire.

APPENDIX A: ENFORCING SESSION TIMEOUT

You ever notice how on some sites, if you leave the computer for awhile and then come back, when you click on a link, the site will ask you to log in again because "your session timed out due to inactivity".

How do they do that?

Well, you can't really use a 'timer' because the web doesn't work that way. You don't know when the User will click on a link... or even if he's still on your site! Instead, you have to do sort of a 'reverse timer'.

Instead of counting down from a static 'amount of time until expiration', you compare the timeout variable to the current time and then store the new timeout value.

Expressed in code:

When the User logs in, set his initial timeout value. Traditionally, the User gets 15 minutes of inactivity before his session becomes invalid. Of course, depending on the nature of your site, you may choose to use a different value.
Code: ( text )
  1. // When you log the User in, set his timeout:
  2. define('SESSION_TIMEOUT', 15);
  3. $_SESSION['timeout'] = (time() + (SESSION_TIMEOUT * 60));


Then put this code at the top of every page that requires the User to be logged in:
Code: ( text )
  1. session_start();
  2.  
  3. // Check to make sure the User is logged in.
  4. if(! checkToSeeIfUserIsLoggedIn(yourCodeGoesHere))
  5. {
  6.     .
  7.     .
  8.     .
  9. }
  10.  
  11. // Check to see if the current time is AFTER the session is marked for timeout.
  12. if(time() > $_SESSION['timeout'])
  13. {
  14.     // User's session has expired.  Go back to the login screen.
  15.     header('Location: login.php?message=timeout');
  16.     exit;
  17. }


You may also want to extend the User's timeout even when he is using the non-secured pages on your site:
Code: ( text )
  1. if(isset($_SESSION['timeout']))
  2.     $_SESSION['timeout'] = (time() + (SESSION_TIMEOUT * 60));

Last edited by pbmods : October 28th, 2007 at 11:44 PM. Reason: Put the 'refresh the page a few times' on a separate line to stop all the hate mail.
9 Comments Posted ( Post your comment )
tscott / July 24th, 2007 06:59 AM
Hey,
Nice Tutorial although I would like to add that this is VERY hard to do for hackers and is not as simple as.
Code: ( text )
  1. <img src="http://myawesomebank.com/transfer.php?from=1002&to=1004&amt=100" />


The only way you can use a PHP file like that is if it is a php generated image. The file itself can't do anything except parse the image otherwise html doesn't process it. I've tried to make a PHP generated image that takes logs. It's impossible and it's denied.

USUALLY this is done by your users clicking a php link (usually disguised as another object). That goes to a script that hijacks your cookie usually or it may include that file that they get from your cookie or session.

It could also be included to a site. But no, it can't be used as an image, you can breath a little easier now ;) . Although yeah... Definately check the referer although that is pretty easy to disguise but not for the purposes here.

$_GET is evil, never use it, On forms to change the page have it submit a post form. Or have them click a checkbox that equals the value of the next page. Etc... This totally will eliminate the need for $_GET.

~Tyler
volectricity / July 28th, 2007 01:44 AM
I felt that this article was very incomplete, so I'm going to add a bit.

You didn't mention how $_SERVER['PHP_SELF'] opens you up to XSS, or even the more dangerous forms of XSS, such as injection of JavaScript.

Did you know that you could go to ANY website, then simply type some JavaScript code and run it? The next time you make a post (finish typing it first), type this into the address bar:

javascript:document.vbform.submit();

This will submit the form. Luckily, this can't be injected into URLs using 'javascript:', but if you print any unfiltered URL data, a user can inject any code into that URL and pass the 'infected' URL to someone else.

For example, if I went to 'page.php?a=<script type="text/javascript">window.location='http://www.volectricity.com';</script>' and anywhere on your page, you printed out the value of $_GET['a'], I could pass that URL to someone and send them elsewhere. And, every single ASCII character can be url-encoded, so I could even force it to no longer be plain-text and you'd be none the wiser.


Also, you completely neglect XSS inside of HTML such as the dangers of unfiltered user profiles, comments, blog entries, forum signatures, and any other user input.

I just wrote the article on XSS today, so I was surprised to find this post missing all that I had mentioned.
pbmods / July 28th, 2007 01:47 AM
Tyler,

While you are correct that the browser will not display the code in the IMG tag, realize that the browser doesn't know if the SRC attribute's value represents a valid image. It can only find this out by sending a request for that file to the server!

In the case of the example illustrated in the article, the browser sends a request for transfer.php?from=1002&to=1004&amt=100 to myawesomebank.com. Since, according to myawesomebank.com, the User was still logged in, the script would EXECUTE THE TRANSFER, and then send back the 'transfer complete!' HTML page.

You would never see the actual HTML, of course, because the browser would not show non-image data inside of an IMG, but the damage was still done; the browser still sent a request to the bank website that initiated the $100 transfer.

Volectricity,

The 'oversight' was intentional. XSS is becoming a security buzzword, and I wanted to focus on XSRF, which is arguably a facet of XSS.
volectricity / July 28th, 2007 03:17 PM
Quote:
Originally Posted by pbmods
Volectricity,

The 'oversight' was intentional. XSS is becoming a security buzzword, and I wanted to focus on XSRF, which is arguably a facet of XSS.


Understood.

I'd also like to add that any tag that accepts a 'src' attribute is vulnerable to the <img> tag exploit. The 'src' attribute accepts any file and opens it, regardless of what it is.


I do like your suggestion for timing out sessions, however. :-D
The best way to do it is to also make sure that the session technically lasts longer than the timeout you have given so that the $_SESSION['timeout'] will still exist. The session GC is generally unpredictable.
nathj / August 8th, 2007 01:12 PM
Quote:
Originally Posted by volectricity
I felt that this article was very incomplete, so I'm going to add a bit.

You didn't mention how $_SERVER['PHP_SELF'] opens you up to XSS, or even the more dangerous forms of XSS, such as injection of JavaScript.

Did you know that you could go to ANY website, then simply type some JavaScript code and run it? The next time you make a post (finish typing it first), type this into the address bar:

javascript:document.vbform.submit();

This will submit the form. Luckily, this can't be injected into URLs using 'javascript:', but if you print any unfiltered URL data, a user can inject any code into that URL and pass the 'infected' URL to someone else.

For example, if I went to 'page.php?a=<script type="text/javascript">window.location='http://www.volectricity.com';</script>' and anywhere on your page, you printed out the value of $_GET['a'], I could pass that URL to someone and send them elsewhere. And, every single ASCII character can be url-encoded, so I could even force it to no longer be plain-text and you'd be none the wiser.


Also, you completely neglect XSS inside of HTML such as the dangers of unfiltered user profiles, comments, blog entries, forum signatures, and any other user input.

I just wrote the article on XSS today, so I was surprised to find this post missing all that I had mentioned.



Volectricity,

I read your article, very informative and opeened my eyes to a few areas I need to change on my own site. I note the suggested use of basename() so I did some reading around to see how it works.

What I don't understand is how this can be used to tell you where you are - what the current url is? I use $_SERVER['PHP_SELF'] to figure this out and it works nicely. The purpose is to disable a navigation item if you are on that page. How would basename be used in that case?

Cheers
nathj
volectricity / August 12th, 2007 01:44 AM
Quote:
Originally Posted by nathj
What I don't understand is how this can be used to tell you where you are - what the current url is? I use $_SERVER['PHP_SELF'] to figure this out and it works nicely. The purpose is to disable a navigation item if you are on that page. How would basename be used in that case?


basename() can be used to get the name of a particular file. $_SERVER['SCRIPT_NAME'] will give you the URL of the file actually being executed minus the XSS vulnerability of PHP_SELF.

Do some testing. print_r($_SERVER) and play around with the URL. A little interesting thing I noticed once was that PATH_INFO is created when you add a slash to the end of a script name, as well as PATH_TRANSLATED as though the server was attempting to check if two requests were being made at once. I can't state these as set in-stone facts though, because different servers work differently.

Really, the point of the article is never to trust URLs. They are user input no matter how you slice it.
crypthacks / August 12th, 2007 03:00 AM
Thanks for bringing this to our attention :)
pbmods / August 12th, 2007 03:31 AM
Quote:
Originally Posted by crypthacks
Thanks for bringing this to our attention :)


No problem (I'm hoping you were directing that at me!).
nathj / August 14th, 2007 07:01 AM
Quote:
Originally Posted by volectricity
basename() can be used to get the name of a particular file. $_SERVER['SCRIPT_NAME'] will give you the URL of the file actually being executed minus the XSS vulnerability of PHP_SELF.

Do some testing. print_r($_SERVER) and play around with the URL. A little interesting thing I noticed once was that PATH_INFO is created when you add a slash to the end of a script name, as well as PATH_TRANSLATED as though the server was attempting to check if two requests were being made at once. I can't state these as set in-stone facts though, because different servers work differently.

Really, the point of the article is never to trust URLs. They are user input no matter how you slice it.



Hi Volectricity,

Thanks for answering my question, I think I have a better understanding of what attacks may threaten a site, and how to handle some of them.

Cheers
nathj

Stats:
Views: 1791
Comments: 9