Prevent csrf attacks

Source: Internet
Author: User
Tags md5 hash
Title: preventing csrf attacks
By nexus

Overview:

1. Hello World
2. Introduction
3. Authentication Technology
3.1 cookies hashing
3.2 HTTP
3.3 Verification Code
4. One-time token
5. Last words
1. Hello World

Welcome to the new playhack.net release project report for the new quarter. I am very glad that you will be back again to reproduce our c001 project.

Hope you like this new short paper and I invite you to browse all the new projects located in http://www.playhack.net.

Start: almost nothing, just a cigarette! :

Scream: I shouted to my playhack m8s null, omni, God and emdel, OFC o str0ke! NEX is back.
2. Introduction

I have some research on Cross-Site Request Forgery (csrf) technology, but I have little research on the measures that website developers should take. These days I am writing a distributed website with high security requirements for users and administrators who do not know what their tasks are: P.ProgramI was deeply entangled in this topic.

In this case, I must consider the possible attack threats that the program may eventually be exposed.

The most troublesome thing for me is session spoofing (or csrf, you can refer to it as you like), because this attack is completely based on the user identity, therefore, there is no possibility to prevent it.

If you don't know much about the session spoofing I just mentioned, you can read: http://www.playhack.net/view.php? Id = 30
3. Feasible Measures

OK. From here on, I must assume that you have thoroughly understood the implementation method of session spoofing attacks: P

Let's start a new journey.

Considering that a trusted user who has logged on to the website can perform some important or private operations, attackers attempt to remember a possible logon attack (but in most cases it is not feasible) and get the Session of the logged-on user to implement its clever behavior.

To hijack a user's seession, intruders carefully construct an appropriate webpage that contains hidden JavaScript Functions to recreate an original operation form, however, the attacker modified some form values and then allowed the attacker to access the page. During the page loading process, the above form will be submitted to a remote page, A request is completed in secret (not unknown to the attacker at this time). They use this method to take advantage of the user's trusted identity.

This method briefly explains how session spoofing attacks work, but an important question is, "How can I prevent my users from being victims of such attacks? "

Now, you may think of the following methods:

Check cookie creden
Check HTTP request routes
Use verification code
However, after some attempts, you will find that these methods are not the most appropriate solutions we should adopt. Let's look at them one by one.
3.1 cookies hashing

The first solution may be the simplest and quickest solution to solve this problem. Because attackers cannot obtain the cookies, they cannot construct corresponding forms.

The implementation method of this problem is similar to the following. On Some login pages, we create cookies based on the current session:

<? PHP
// Cookie value
$ Value = "something from somewhere ";
// Create a cookie which expires in one hour
Setcookie ("cookie", $ value, time () + 3600 );
?>

Here, we use hashes in cookies to authenticate this form.

<? PHP
// Hash the cookie
$ Hash = MD5 ($ _ cookie ['cooker']);
?>

In this case, you can perform the following operations on the dynamic web page in the background:

<? PHP
// Check if the "check" Var exists
If (isset ($ _ post ['check']) {
$ Hash = MD5 ($ _ cookie ['cooker']);
// Check if the values coincide
If ($ _ post ['check'] = $ hash ){
Do_something ();
} Else {
Echo "malicious request! ";
}
} Else {
Echo "malicious request! ";
}
?>

In fact, if we ignore the fact that users' cookies are easily stolen due to the XSS vulnerability on the website (we know this is not uncommon, this is a good solution for csrf. If we add random cookies to each form request of the user, this method will become safer, but this is not very suitable.
3.2 HTTP

The simplest way to check whether the access request is trusted is to obtain the access information in the HTTP request (that is, the HTTP header named Referer-Translator's note) and check whether it comes from the station or from a remote malicious page: this is a good solution, but it seems legal because it can fool the requests received by the server, this method cannot effectively prevent attacks.

Let's see why this is not a proper method.

The followingCodeAn example of the HTTP Referer implementation method is shown:

If (eregi ("www.playhack.net", $ _ server ['HTTP _ referer']) {
Do_something ();
} Else {
Echo "malicious request! ";
}

This detection will easily ignore HTTP Referer spoofing by an attacker. Attackers can use the following code:

Header ("Referer: www.playhack.net ");

Or other methods that counterfeit HTTP headers and send them in malicious scripts.

Because HTTP Referer is sent by the client browser rather than controlled by the server, you should not use this variable as a trust source.
3.3 Verification Code

Another way to solve this problem is to use a Random verification code in each form submitted by the user, so that the user can fill in the random string on the image in the text box, and check the submitted form.

This method was abandoned before, because the use of Verification Code images involves a bug called MHTML, which may be affected in some versions of Microsoft IE.

You can get detailed information about this defect on the secunia site: http://secunia.com/advisories/19738.

Here is an overview of secunia's explanation of this bug:

"This defect is caused by URL processor redirection for processing" MHTML. It can be used to access the current document from another website"

On the same page, you will find the website testing method from the secunia staff.

As a matter of fact, we know that this bug has been solved by Microsoft's Windows XP, Windows Vista, and ie6.0 fix packages.

Even if he does have security problems, there will be other reliable solutions in such a long time.
4. One-time token

Now let's look at the last solution that I want to introduce after research: After using these unreliable technologies, I try to make some different but more effective methods.

To prevent web forms from being attacked by session spoofing (csrf), I decided to detect every project that may be disguised or forged. Therefore, I need to create one-time tokens so that they cannot be guessed or disguised under any circumstances. These one-time tokens will be destroyed after their work is completed.

Let's start with generating the token value:

<? PHP
Function gen_token (){
// Generate the MD5 hash of a randomized uniq ID
$ Hash = MD5 (uniqid (RAND (), true ));
// Select a random number between 1 and 24 (32-8)
$ N = rand (1, 24 );
// Generate the token retrieving a part of the hash starting from
// The random N number with 8 of lenght
$ Token = substr ($ hash, $ N, 8 );
Return $ token;
}
?>

The PHP function uniqid () allows web developers to obtain a unique ID based on the current time (in milliseconds). This unique ID is conducive to generating a unique value.

We retrieve the MD5 hash of the corresponding id value, and then start from the hash with a number less than 24, select 8 letters,

The returned $ token variable retrieves an 8-bit long random token.

Now let's generate a session token and we will use it later.

<? PHP
Function gen_stoken (){
// Call the function to generate the token
$ Token = gen_token ();
// Destroy any eventually session token variable
Destroy_stoken ();
// Create the session token variable
Session_register (incluen_name );
$ _ Session [en_name] = $ token;
}
?>

In this function, we call the gen_token () function and use the returned token to copy its value to a new $ _ session variable.

Now let's take a look at how to generate a function that hides the input field for our form in the complete startup mechanism:

<? PHP
Function gen_input (){
// Call the function to generate the session token variable
Gen_stoken ();
// Generate the form input code
Echo "";
}
?>

We can see that this function calls the gen_stoken () function and generates HTML code that contains hidden fields in web forms.

Next let's look at the function to detect the session token submitted in the hidden domain:

<? PHP
Function token_check (){
// Check if the session token exists
If (is_stoken ()){
// Check if the request has been sent
If (isset ($ _ request [ftoken_name]) {
// If the form token is different from session token
// It's a malicious request
If ($ _ request [ftoken_name]! = $ _ Session [en_name]) {
Gen_error (1 );
Destroy_stoken ();
Exit ();
} Else {
Destroy_stoken ();
}
// If it isn't then it's a malicious request
} Else {
Gen_error (2 );
Destroy_stoken ();
Exit ();
}
// If it isn't then it's a malicious request
} Else {
Gen_error (3 );
Destroy_stoken ();
Exit ();
}
}
?>

This function detects the existence of $ _ session [incluen_name] and $ _ request [ftoken_name] (I used the $ _ Request Method to submit form variables in the get and post methods ). can be accepted ), then, check whether their values are the same. Therefore, check whether the current form submission is authenticated and authorized.

The focus of this function is that after each detection step is completed, the token will be destroyed and will be regenerated only on the next form page.

The usage of these functions is very simple. We only need to add some PHP code structures.

The following is a web form:

<? PHP
Session_start ();
Include ("functions. php ");
?>

The script code is as follows:

<? PHP
Session_start ();
Include ("functions. php ");

// Call the function to make the check
Token_check ();

// Your code
...
?>

As you can see, this detection is very simple, but it can prevent your user forms from being hijacked by attackers, so as to avoid unauthorized data authorization.
5. Conclusion

Let's make a conclusion on this short paper that your web application is not secure, but you can start to avoid most common attack technologies.

I hope that you will pay attention to the following points: Web developers should not ignore common program errors (such as XSS browser vulnerabilities ), it is a huge mistake not to consider these as potential threats to your users: You should always remember that they will affect the trust, security, and interoperability of your programs.

Cya!

Nexus

(The above PHP code is referenced from the Seride project, the project address is: http://projects.playhack.net/project.php? Id = 3)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.