Saturday, March 26, 2011

Cross Site Request Forgery

 Through CSRF you can change the admin password,is not so inoffensive. Can be used with XSS,redirected from XSS.

 Basic example
- Code snippet from test.php

{ unlink('files/news'.$news.'.txt'); }
else {
die('File not deleted'); }


In this example you will see what is CSRF and how it works.In the "files" directory are saved the news written by the author.The news are saved like "news1.txt","news2.txt" etc. So the admin can delete the news.The news that he want to delete will be specified in "news" variable.If he want to delete the news1.txt the value of "news" will be "1".We cannot execute this without admin permissions,look,the script check if we are logged in.
I will show you an example.If we request :

The /news/news1.txt file will be deleted.The script directly delete the file without any notice.So we can use this to delete a file.All we need is to trick the admin to click our evil link and the file specified by us in the "news" variable will be deleted. 

Simple example
In a way the codes below are included in the index.php file ,I will not paste all the includes,there are a lot.  
Code snippet from includes/pages/admin.php

if ($_GET['act'] == '') {
include "includes/pages/admin/home.php";
} else {
include "includes/pages/admin/" . $_GET['act'] . ".php";

Here we can see how the "includes/pages/admin/members.php" is included in this file.If "act=members" the file below will be included. 

Code snippet from includes/pages/admin/members.php

if ($_GET['func'] == 'delete') {
$del_id = $_GET['id'];
$query2121 = "select ROLE from {$db_prefix}members WHERE ID='$del_id'";
$result2121 = mysql_query($query2121) or die("delete.php - Error in query: $query2121");
while ($results2121 = mysql_fetch_array($result2121)) {
$their_role = $results2121['ROLE'];
if ($their_role != '1') {
mysql_query("DELETE FROM {$db_prefix}members WHERE id='$del_id'") or die(mysql_error

We can see here that if "func=delete" will be called by URL,the script will delete from the database a user with the specified ID ( $id ) without any
confirmation.Example :

The script check if the admin is logged in so if we trick the admin to click our evil link the user who have the specified ID in the database will be deleted without any confirmation. 

How to fix?
Simple way : Use tokens.At each login,generate a random token and save it in the session.Request the token in URL to do administrative actions,if the token missing or is wrong,don't execute the action.I will show you only how to to check if the token is present and is correct.Example :
if(isset($_GET['news']) && $token=$_SESSION['token'])
{ unlink('files/news'.$news.'.txt'); }
else {
die('Error.'); }

The request will look like this one :[RANDOM_TOKEN]

So this request will be fine,the news will be deleted.
Another way : Do some complicated confirmations or request a password
to do administrative actions.



Post a Comment