473,544 Members | 2,308 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

pbmods
5,821 Recognized Expert Expert
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:

Expand|Select|Wrap|Line Numbers
  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:
Expand|Select|Wrap|Line Numbers
  1. <img src="http://myawesomebank.com/transfer.php?from=1002&to=1004&amt=100" />
  2.  
THE HAPLESS VICTIM

Now for the fun part. Let's say you were recently visiting myawesomebank.c om 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.c om's "transactio n 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.
Expand|Select|Wrap|Line Numbers
  1. // When you log the User in, set his timeout:
  2. define('SESSION_TIMEOUT', 15);
  3. $_SESSION['timeout'] = (time() + (SESSION_TIMEOUT * 60));
  4.  
Then put this code at the top of every page that requires the User to be logged in:
Expand|Select|Wrap|Line Numbers
  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. }
  18.  
You may also want to extend the User's timeout even when he is using the non-secured pages on your site:
Expand|Select|Wrap|Line Numbers
  1. if(isset($_SESSION['timeout']))
  2.     $_SESSION['timeout'] = (time() + (SESSION_TIMEOUT * 60));
  3.  
Jul 20 '07 #1
11 26389
tscott
22 New Member
Hey,
Nice Tutorial although I would like to add that this is VERY hard to do for hackers and is not as simple as.
[html]
<img src="http://myawesomebank.c om/transfer.php?fr om=1002&to=1004 &amt=100" />
[/html]

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
Jul 24 '07 #2
kovik
1,044 Recognized Expert Top Contributor
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:docu ment.vbform.sub mit();

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=<sc ript type="text/javascript">win dow.location='h ttp://www.volectricit y.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.
Jul 28 '07 #3
pbmods
5,821 Recognized Expert Expert
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?fr om=1002&to=1004 &amt=100 to myawesomebank.c om. Since, according to myawesomebank.c om, 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.
Jul 28 '07 #4
kovik
1,044 Recognized Expert Top Contributor
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.
Jul 28 '07 #5
nathj
938 Recognized Expert Contributor
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:docu ment.vbform.sub mit();

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=<sc ript type="text/javascript">win dow.location='h ttp://www.volectricit y.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
Aug 8 '07 #6
kovik
1,044 Recognized Expert Top Contributor
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($_SERVE R) 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.
Aug 12 '07 #7
crypthacks
3 New Member
Thanks for bringing this to our attention :)
Aug 12 '07 #8
pbmods
5,821 Recognized Expert Expert
Thanks for bringing this to our attention :)
No problem (I'm hoping you were directing that at me!).
Aug 12 '07 #9
nathj
938 Recognized Expert Contributor
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($_SERVE R) 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
Aug 14 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

7
4841
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As InternetExplorer But then I cant see when a user exit my objIExplorer and than an error will show up when I try to open a link in the IE window that does...
5
3604
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug puposes only and is not normally visable to the user.) The Thread function is actually in the Form class. Now.. What I am seeing is that when I...
22
2572
by: Robert Bralic | last post by:
CAN anybody tell me any address where I can download some small(1000-2000) lines C++ proghram source. Or send me ,a small(1000-2000) lines C++ program source that I can compille with gpp under Linux Suse 7.1. I can't belive that C++ exists. Thanks in advance ! robert.bralic@si.htnet.hr
12
2921
by: Frank Hauptlorenz | last post by:
Hello Out there! I have a DB2 V7.2 Database (Fix11) on Win 2000 Professional. It was before a NT 4 based Domain - now it is a Win 2000 Domain. The database server is a domain member. Now sometimes Win 2000 Clients can't connect to the database. They connect over TCP/IP. The db2log says that the function getHostByName failed. It seems to...
11
2380
by: dreamcatcher | last post by:
bool isBlankLine(char *line) { char *tmp=line; bool blank=true; while(*tmp++!='\0') {
0
3077
by: BH | last post by:
I heard there are tools that can disassemble a .NET DLL or EXE into source code in high level language of the choice. I'm not talking about disassembling into the .NET Intermediate Language but languages like VB.NET or C#. Is there a way to thwart such tools?
0
2349
by: Jarod_24 | last post by:
How does tabindex work in ASP .net pages I dosen't seem to work quite like in regular forms. and there isn't any TabStop property either. 1 .How do you prevent a control form beign "tabbed". (hidden textboxes ect.) 2. How do get a control to get focus when the page is loaded (think username textfield on a loginpage) 3. Does the tab-order...
14
4818
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it can be done using the designer but I intentionally don't want to use that. The one reason is that you cannot change the code generated by the...
162
10102
by: Sh4wn | last post by:
Hi, first, python is one of my fav languages, and i'll definitely keep developing with it. But, there's 1 one thing what I -really- miss: data hiding. I know member vars are private when you prefix them with 2 underscores, but I hate prefixing my vars, I'd rather add a keyword before it. Python advertises himself as a full OOP language,...
0
7378
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7638
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7732
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5947
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4935
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3429
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
684
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.