Common security issues in PHP development and solutions (such as SQL injection, CSRF, XSS, CC, etc.) _php tips

Source: Internet
Author: User
Tags html tags mysql injection parse error file permissions

Talking about PHP security and anti-SQL injection, prevent XSS attack, anti-theft chain, anti-CSRF

Objective:

First of all, the author is not a web security experts, so this is not a Web security expert-level article, but learning notes, careful summary of the article, there are some of our phper not easy to find or say not to pay attention to things. So I write down to facilitate later inspection. There must be a dedicated web security tester in a large company, and security is not a phper area to consider. But as a phper for security knowledge is: "Know that there is such a thing, programming naturally have attention."

Directory:

1. Some security configuration of PHP
(1) Turn off the PHP hint error function
(2) Turn off some "bad features"
(3) Strict configuration file permissions.
2, strict data validation, your users are not all "good" people
2.1 To ensure the security and robustness of the program, data validation should include content.
2.2 Programmers are apt to miss Point or to notice things
3. Anti-injection
3.1 Simple to determine whether there are injection holes and principles
3.2 Common MySQL injection statements
(1) Without user name and password
(2) In the case of not entering a password, using a user
(3) Guess the password of a user
(4) To insert the data when the right to mention
(5) Renewal of the right to mention and insertion of the right to the same
(6) Malicious updates and deletions
(7) Union, join, etc.
(8) Wildcard symbol%, _
(9) There is also a lot of guessing table information injected into SQL
33 Some methods of anti-injection
2.3.1 PHP can be used to prevent injection of some functions and considerations.
2.3.2 the anti-injected character priority.
2.3.3 Anti-injection code
(1) The parameter is the number directly using the Intval () function
(2) Filtering for non-text parameters
(3) Text data anti-injection code.
(4) There are, of course, other codes combined with addslashes and mysql_escape_string.
4. Prevent XSS attacks
4.1XSS attack Process
4.2 Common XSS attack places
4.3 Anti-XSS method
5, CSRF
5.1 Simple explanation CSRF principle
5.2 Methods of prevention
6, anti-theft chain
7. Anti-rejection cc attack

1. Some security configuration of PHP


(1) Turn off the PHP hint error function

To change the display_errors into a php.ini.

Copy Code code as follows:
Display_errors = Off



or join in before PHP file


Copy Code code as follows:
Error_reporting (0)

1 use error_reporting (0); failure Example:

A file code:

Copy Code code as follows:
?
error_reporting (0);
Echo 555
echo 444;
?>



Error:


Copy Code code as follows:
Parse error:parse error, expecting ', ', ' or '; ' in E:\webphp\2.php to line 4



2 use error_reporting (0); successful example:


A file code:


Copy Code code as follows:

<?php
error_reporting (0);
Include ("b.php");
?>



B File Code:


Copy Code code as follows:

<?php
Echo 555
echo 444;
?>



This is a lot of Phper said with error_reporting (0) does not work. The first example a.php inside has fatal error, causes cannot execute, cannot execute the server does not know has this function, therefore has the same error.

In the second example, A.php succeeds, and the server knows that there is a suppression error function, so even if b.php has errors, it is suppressed.

PS: Cannot restrain MySQL error.

(2) Turn off some "bad features"

1) Turn off Magic quotes function

MAGIC_QUOTES_GPC = off in php.ini
Avoid and addslashes repeat escapes

2) Close register_globals = Off

Register_globals = off in php.ini

In the case of register_globals = On

Address column: Http://www.jb51.net?bloger=benwin

Copy Code code as follows:

<?php
$bloger = $_get[' Bloger ']//because register_globals = on so this step can not be used directly with $bloger
Echo $bloger;
?>

This can cause some uninitialized variables to be easily modified, which may be fatal. So turn off the register_globals = Off

(3) Strict configuration file permissions.

Assigning permissions to the appropriate folder, such as files that contain uploaded pictures, cannot have Execute permissions, only read

2, strict data validation, your users are not all "good" person.

I remember the author and a friend in the discussion of data validation, he said a word: you do not put your users all think so bad! But the question I want to say should not be in our development scenario, what we need to do is strictly verify the control data flow, even if one of the 100 million users is a bad user is enough to kill, say good users sometimes in the data input box inadvertently entered the Chinese, he has inadvertently become "bad".

2.1 To ensure the security and robustness of the program, data validation should include

(1) Whether the key data exists. If the delete data ID exists
(2) The data type is correct. If the delete data id is an integer
(3) The length of the data. If the field is a char (10) type, strlen the length of the data
(4) Whether the data have dangerous characters

Data validation Some people advocate that the function is completed and then slowly write security verification, but also some edge development side write verification. The author favors the latter, both of the authors have tried, and then found that the latter to write a relatively robust, mainly because the new development of the thought of a relatively complete security issues, such as the development of the function to write when there are two problems, a phper in a hurry to complete the index hastily finished, two is really missing some point.
2.2 Programmers are apt to miss Point or to note things:

(1) into the library data must be safe verification, the author of a company in Guangzhou to participate in a company's internal system development, see the $_post data directly to the class function Classfunctionname ($_post), the reason is the company's internal use, not so strict. Not to mention the logic operation and data manipulation coupled high and low problem, even the judgment is not judged by the operation is fatal. Security verification must be, without any reason to evade.
(2) Data length problems, such as database table field char (25), most phper consider whether it is empty, the data type is correct, but ignore the length of characters, ignore the good more is lazy to judge the length. (This more appears in the novice, the author once also had this kind of thought)
(3) The front end with JS to determine the verification, the background does not need to judge verification. This is also fatal, to know how to forge a form on a few minutes, JS judge just to reduce the number of users submitted to improve the user experience, reduce the HTTP request to reduce server pressure, in the security situation can not prevent "villain", of course, if the legitimate user in the JS verification control is perfect, But as phper we can not only JS verification and discard again security verification.
(4) Lack of validation of some properties such as Select, CheckBox, Radio, button, etc. on a Web page the developer has set its value and range (whitelist value), which are generally not validated in JS validation, Because the legitimate user only has the right to choose not to modify, and then phper in the back-end to accept data processing validation of this data, this is an inertial thinking, security problems will have, the villain a pseudo form.
(5) The corresponding element name of the form corresponds to the field name of the datasheet, such as the field of the user table user name is user_name, and then the user name input box in the form is user_name, which is no different from Bauku.
(6) Filtration of dangerous characters such as anti-injection will be explained independently.

3. Anti-injection

3.1 Simple to determine whether there are injection holes and principles.

URL: http://www.jb51.net/benwin.php?id=1 run normally, SQL statements such as: SELECT * from phpben where id = 1

(1) URL: http://www.jb51.net/benwin.php?id=1 ' SQL statements such as: SELECT * from phpben where id = 1 ' and then run an exception that indicates that the benwin.php file does not have a value for the ID Line "'" Filter and intval () reshaping conversion, of course want to know if there is no other word Furu "%", "/*" and so can be used in a similar way to exhaustive test (many test software use)
(2) Web address: http://www.jb51.net/benwin.php?id=1 and 1=1 SQL statements may be select * from Phpben where id = 1 and 1=1, run normally and result and HTTP://WW W.jb51.net/benwin.php?id=1 results, it means that benwin.php may not filter for spaces "", "and" (this is possible, so take a look at the next point)
(3) Web address: http://www.jb51.net/benwin.php?id=1 and 1=2 SQL statements may be select * from Phpben where id = 1 and 1=2 if the run result exception describes the SQL statement "an D 1=2 "works, so all 3 conditions are satisfied are very certain benwin.php there is an injection loophole."

PS: Here with the Get method validation, post can also, as long as the value of the above input, you can verify one by one.

3.2 Common MySQL injection statements.

(1) Without user name and password

Copy Code code as follows:

Normal statement
$sql = "SELECT * from Phpben where user_name= ' admin ' and pwd = ' 123 '";
In the Username box, enter ' or ' = ' or ' or ' or ' 1 = ' 1 and then SQL follows
$sql = "SELECT * from Phpben where user_name= ' or ' = ' or ' and pwd = '";
$sql = "SELECT * from Phpben where user_name= ' or 1= ' 1 ' and pwd = '";



This does not need to enter a password. In other words, I see the Login box has the impulse to try.

(2) Use a user without entering a password.

Copy Code code as follows:

Normal statement
$sql = "SELECT * from Phpben where user_name= ' $username ' and pwd = ' $pwd '";
The user name used is benwin the username box input Benwin ' # password is all available, then $sql into
$sql = "SELECT * from Phpben where user_name= ' Benwin '" and pwd = ' $pwd ' ";



This is because one of the notes in MySQL is "#", which in the above statement has been marked with the following, so the password may not be entered or entered arbitrarily. Some people on the internet said with "/*" to note that the author would like to mention that only the beginning of note did not end note "* *", MySQL will not say "/**/" can not note, but it is difficult to add on the "* *" to end note, and "–" can also note that MySQL but note "-" After at least one space is "-", of course, the anti-injection code to take into account three kinds of, it is worth mentioning that many of the anti-injection code does not "-" take into account the scope of the anti-injection.

(3) Guess the password of a user

Copy Code code as follows:

Normal statement
$sql = "SELECT * from phpben.com where user_name= ' $username ' and pwd = ' $pwd '";
Enter "Benwin" and Left (pwd,1) = ' P ' # in the Password entry box, then $sql is
$sql = "SELECT * from phpben.com where user_name= ' Benwin ' and Left (pwd,1) = ' P ' # ' and pwd = ' $pwd '";



If you run a normal password, the first character of the password is P, with Richai the remainder of the character.

(4) To insert the data when the right to mention

Copy Code code as follows:

Normal statement with a level of 1
$sql = "INSERT INTO phpben.com (' user_name ', ' pwd ', ' Level ') VALUES (' Benwin ', ' iampwd ', 1)";
By modifying the password string, the statement becomes
$sql = "INSERT INTO phpben.com (' user_name ', ' pwd ', ' Level ') VALUES (' Benwin ', ' iampwd ', 5) # ', 1)";
$sql = "INSERT INTO phpben.com (' user_name ', ' pwd ', ' Level ') VALUES (' Benwin ', ' iampwd ', 5)--', 1"; This gives the user with a permission of 1 the right to rank 5.






(5) Renewal of the right to mention and insertion of the right to the same
Copy Code code as follows:

Normal statement
$sql = "Update phpben set ' user_name ' = ' benwin ', level=1";
The resulting $sql by entering the username value
$sql = "Update phpben set ' user_name ' = ' benwin ', level=5# ', level=1";
$sql = "Update phpben set ' user_name ' = ' benwin ', level=5--', level=1";






(6) Malicious updates and deletions
Copy Code code as follows:

Normal statement
$sql = "Update phpben set ' user_name ' = ' benwin ' WHERE id = 1";
After injection, the malicious code is "1 or id>0"
$sql = "Update phpben set ' user_name ' = ' benwin ' where ID =1 or id>0";
Normal statement
$sql = "Update phpben set ' user_name ' = ' benwin ' where id=1";
After injection
$sql = "Update phpben set ' user_name ' = ' benwin ' where id>0# ' where id=1 ';
$sql = "Update phpben set ' user_name ' = ' benwin ' where id>0--' where id=1 ';






(7) union, join, etc.
Copy Code code as follows:

Normal statement
$sql = "SELECT * from Phpben1 where ' user_name ' = ' benwin '";
After injection
$sql = "SELECT * from Phpben1 where ' user_name ' = ' benwin ' Uninon select * from phpben2# '";
$sql = "SELECT * from Phpben1 where ' user_name ' = ' Benwin ' left join......# '";






(8) wildcard symbol%, _
Copy Code code as follows:

Normal statement
$sql = "SELECT * from Phpben where ' user_name ' = ' benwin '";
Injected wildcard symbol% matches multiple characters, while one _ matches one character, such as __ matches two characters
$sql = "SELECT * from Phpben where ' user_name ' like '%b '";
$sql = "SELECT * from Phpben where ' user_name ' like ' _b_ '";



So as long as there is a user name of the beginning of B can be normal operation, "_b_" is a match three characters, and these three characters in the middle of a character B. This is why the addslashes () function is prompted to note that there is no escape% and _ (in fact, this is a lot of phper don't know to ask what to filter% and _ underline, just blindly follow the online code to go)

(9) There is also a lot of guessing table information injected into SQL

Copy Code code as follows:

Normal statement
$sql = "SELECT * from Phpben1 where ' user_name ' = ' benwin '";
Guessing table name, running normally indicates existence of PHPBEN2 table
$sql = "SELECT * from Phpben1 where ' user_name ' = ' benwin ' and (select COUNT (*) from Phpben2) >0# '";
Guessing the table field, and running normally indicates that there are fields in phpben2 tables Colum1
$sql = "SELECT * from Phpben1 where ' user_name ' = ' benwin ' and (select COUNT (colum1) from phpben2) >0# '";
Guess field value
$sql = "SELECT * from Phpben1 where ' user_name ' = ' Benwin ' and Left (pwd,1) = ' P '" ";

Of course, there are many, the author did not study the level of professionals, these are more common, it is also phper should know and master, rather than blindly in the online copy and paste some of the anti-injection code, but understand it.

Some of the following anti-injection methods may be easier to read back.

3.3 Some methods of anti-injection

3.3.1 PHP can be used to prevent injection of some functions and considerations.

(1) addslashes and stripslashes.

Addslashes to these "", "" "," \ "," NULL "add oblique rod" \ "," \ "," \ "," \null ", stripslashes on the contrary, here is to pay attention to whether the php.ini opened the magic_quotes_gpc= On, open if use addslashes will appear duplicate. So use the time to first GET_MAGIC_QUOTES_GPC () check

Common code is similar:

Copy Code code as follows:

if (!GET_MAGIC_QUOTES_GPC ())
{
$ABC = Addslashes ($ABC);
}



In fact, this a little bit of learning php people know, but I would like to introduce the system (the front is not an expert-level article), so also by the way written. Addslashes

(2) mysql_escape_string () and Mysql_ real _escape_string ()

Mysql_real_escape_string must be available in the case of (PHP 4 >= 4.3.0, PHP 5). Or you can only use mysql_escape_string.

Copy Code code as follows:

if (php_version >= ' 4.3 ')
{
$string = mysql_real_escape_string ($string);
}else
{
$string = mysql_escape_string ($string);
}



Mysql_escape_string () and Mysql_ real _escape_string () do not depend on the latter to determine the current database connection character set, in other words, a similar error occurs without the database being connected:


Copy Code code as follows:

Warning:mysql_real_escape_string () [function.mysql-real-escape-string]: Access denied for user ' ODBC ' @ ' localhost ' ( Using Password:no) in E:\webphp\test.php on line 11






(3) Character substitution function and matching function
Str_replace (), perg_replace () These functions are also mentioned here because these functions can be used to filter or replace some sensitive, fatal characters.

3.3.2 The anti-injected character priority.

Anti-injection must first know what injected characters or keywords, common MySQL injection characters have character-delimited symbols such as "'", "" "," "and" "", "" "or", "MySQL Notes" Furu "#", "–", "/**/"; MySQL wildcard "%", "_" ; MySQL keyword "select|insert|update|delete|*|union|join|into|load_file|outfile"

(1) For some of the parameters of the specified format, the highest priority of the injection is the space "".

such as some bank card number, ID number, mail, phone number, birthday, zip code, etc. these have their own provisions of the format and format can not have the parameters of the space symbol, in the filtering time generally first filtered out spaces (including some space "variant"), because other characters define symbols, logic keywords, mysql note, Note that the following figure shows what is important is "'", "" "

PS: Variants of the space characters are: "%20", "\ n", "\ r", "\ r \ n", "\n\r", "Chr (" 32″) "and that's why Mysql_escape_string () and mysql_real_escape_string () Two functions escape "\ n", "\ r". In fact, a lot of phper only know escaped \n,\r and do not know why, in the MySQL parsing \n,\r as a space processing, the author tests validated, here is not to paste code.

(2) "and", "or", "\", "#", "-"

The logic key can combine a lot of injection code; MySQL notes all the characters behind the inherent SQL code to make the injected SQL statements work; "\" is also able to combine a lot of injected character \x00,\x1a.

Ps:sql parsing "#", "–" is not considered by most MySQL anti-injection code, and is also ignored by many phper. And because some phper assign values to the parameters, it's useful to "-" to separate them, therefore, I suggest that you do not write the parameters, of course, you can filter the parameters of the Time "–" (note that there are spaces, no space is not resolved to note) When a whole filter rather than filter "-", so as to avoid excessive filtering parameters.

(3) "null", "%", "_"

These few can not be independent, do not under certain circumstances, such as the wildcard character "%,_" should be in the MySQL like clause premise. So "%", "_" filtering is generally filtered in search-related, can not be included in the usual filter queue, because some such as mailboxes can have "_" characters

(4) keyword "Select|insert|update|delete|*|union|join|into|load_file|outfile"

Perhaps you will ask how these important keywords are so low priority. The author would like to say because these keywords in the absence of "", "" "," "," and "," or "and so on in case of purchase no harm. In other words, these keywords are not "independent" and "dependent" is particularly large. Of course, low priority, does not mean not to filter.


3.3.3 Anti-injection code.

(1) The parameter is the number directly using the Intval () function

Note: Now many online anti-injection code is just using Addslashes (), mysql_escape_string (), mysql_real_escape_string () or any combination of the three filters, but Phper thought filtered, Inadvertently, there is a loophole, that is, when the parameter is a number:

Copy Code code as follows:
$id = addslashes ($_post[' id ')); Correct is $id = Intval ($_post[' id '));
$sql = "SELECT * from phpben.com where id = $id";
$sql = "SELECT * from phpben.com where ID =1 or 1=1";



Comparison is easy to find, post over the data through the Addslashes filter is indeed a lot of injection has not worked, but $id did not intval, resulting in the existence of loopholes, this is a small detail, inadvertently lead to loopholes.

(2) Filtering for non-text parameters

Text parameter refers to the title, message, content and so on may have "'", "'" and so on, filtering can not be completely escaped or replaced.

But not text data can.

Copy Code code as follows:



function _str_replace ($STR)


{


$str = Str_replace ("", "", $str);


$str = Str_replace ("\ n", "", $str);


$str = Str_replace ("\ R", "", $str);


$str = Str_replace ("'", "", $str);


$str = Str_replace (' "," ", $str);


$str = Str_replace ("or", "", $str);


$str = Str_replace ("and", "", $str);


$str = Str_replace ("#", "", $str);


$str = Str_replace ("\", "", $str);


$str = Str_replace ("--", "", $str);


$str = Str_replace ("null", "", $str);


$str = str_replace ("%", "", $str);


$str = Str_replace ("_", "", $str);


$str = Str_replace ("&gt;", "", $str);


$str = Str_replace ("&lt;", "", $str);


$str = str_replace ("=", "", $str);


$str = Str_replace ("char", "", $str);


$str = Str_replace ("Declare", "", $str);


$str = Str_replace ("Select", "", $str);


$str = Str_replace ("Create", "", $str);


$str = str_replace ("delete", "", $str);


$str = Str_replace ("Insert", "", $str);


$str = Str_replace ("Execute", "", $str);


$str = Str_replace ("Update", "", $str);


$str = Str_replace ("Count", "", $str);


return $str;


}

PS: There are also some general href from the list page is "phpben.php?action=delete&id=1", this time notice, _str_replace ($_get[' action ') will filter out the parameters, I generally do not use sensitive key as a parameter, such as delete will be written as Del,update written Edite, as long as the readability can not be affected;

There are also the above Code filter underline the author notes, because some parameters can use underline, oneself weigh how to filter;

Some code key words when the focus of filtering objects, in fact, the keyword str_replace very easy "Meng", Str_replace ("Ininsertsert") filtered characters or insert, so the key is other characters rather than MySQL keyword.

(3) Text data anti-injection code.

The text parameter is the title, the message, the content and so on these data cannot also use Str_replace () to filter out, thus causes the data integrity, this is very undesirable.

Code:

Copy Code code as follows:



function No_inject ($STR)





{


if (Is_array ($STR))


{


foreach ($str as $key =&gt; $val)


{


$str [$key]=no_inject ($val);


}


}else


{


$str = Str_replace ("", "", $str);


$str = Str_replace ("\", "\", $STR);


$str = Str_replace ("'", "'", $str);


$str = Str_replace (' "," "", $str);


$str = Str_replace ("or", "or", $str);


$str = Str_replace ("and", "and", $STR);


$str = Str_replace ("#", "#", $str);


$str = Str_replace ("--", "--", $str);


$str = Str_replace ("null", "null", $STR);


$str = str_replace ("%", "%", $str);


$str = Str_replace ("_", "", $str);


$str = Str_replace ("&gt;", "&gt;", $str);


$str = Str_replace ("&lt;", "&lt;", $str);


$str = str_replace ("=", "=", $str);


$str = Str_replace ("char", "char", $STR);


$str = Str_replace ("Declare", "declare", $STR);


$str = Str_replace ("Select", "select", $str);


$str = Str_replace ("Create", "create", $STR);


$str = str_replace ("delete", "delete", $str);


$str = Str_replace ("Insert", "Insert", $STR);


$str = Str_replace ("Execute", "execute", $STR);


$str = Str_replace ("Update", "Update", $STR);


$str = Str_replace ("Count", "Count", $STR);


}


return $str;


}






(4) There are, of course, other codes combined with addslashes and mysql_escape_string.

Anti-injection code in fact come and go are those combinations, and then according to their own program code, the author of the code is not considered the whole, as Cookes, session, request are not fully filtered. The important thing is to know the principle, why filter these characters, and what harm the characters have.

4. Prevent XSS attacks

Xss:cross Site Script Cross-site scripting, why not called CSS, in order not to be confused with div+css.

4.1XSS Attack Process:

(1) found an XSS vulnerability in a station.

(2) Inject the XSS vulnerability code. Can JS code, trojan, script files and so on, here if a station benwin.php this file has loopholes.

(3) through a number of methods to deceive a station related personnel to run benwin.php, which use some of the relevant staff member information such as cookies, permissions and so on.

Related personnel:

Administrator (such as bar moderator), the administrator generally has certain permissions. The purpose is to borrow the administrator's privileges or carry out the right to add or add the administrator, or add a backdoor, or upload a trojan, or further infiltration and other related operations.

A station member: member runs the benwin.php of a station. The purpose is generally to steal the information of the member at station A.

Method:

1 at a station to trick the relevant person to benwin.php information, such as Web site, this is a local decoy

2 in other sites to send deception information or send e-mail messages and so on.

Generally through the camouflage URL to cheat a station related personnel click into benwin.php

(4) The third step is generally an XSS attack, if you want to further attack, that repeated execution (2), (3) step to achieve the goal.

Simple example of an XSS attack.

Code: benwin.php File

Copy Code code as follows:

<title> Simple XSS Attack Example </title><meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<dody>
<form action= "phpben.com?user_name=<?php echo $user _name;?>" >
<input type= "Submit" value= "submitted" >
</form>
</body>



When username $user_name value is "Benwin" onsubmit= "alert (' This is an example of XSS attack ');" class= "(here)


Copy Code code as follows:

<form action= "Phpben.com?user_name=benwin" onsubmit= "alert (' This is an example of XSS attack ');" class= ">
<input type= "Submit" value= "submitted" >
</form>



The Prompt box pops up when you submit the form.

(1) It is obvious that $user_name did not filter the XSS characters when they were saved into the database (like the anti-injection, here is an example) ==> found the vulnerability

(2) Construct XSS code: Benwin "onsubmit=" alert (' This is an example of XSS attack '); "class=" "Incoming database

(3) Cheat related personnel come in and click "Submit" button

4.2 Common XSS attack places

(1) JS Place

Copy Code code as follows:

<script language= "JavaScript" >
var testname = "<?php echo $testname;? > ";
</script>



$testname value as long as the JS closed relationship is met: ""; Alert ("Test XSS"); " (same as the following)

(2) Form forms inside

Copy Code code as follows:

<input type= "Text" Name= "# #" value= "<?php echo $val;?>"/>






(3) a label
Copy Code code as follows:

<a href= "benwin.php?id= <?php echo $id?>" >a tag can hide XSS attacks </a>






(4) using a lot of IMG tags
Copy Code code as follows:




Even some text inserts the entire IMG tag and uses the width, the height, the CSS and so on hides very concealed

(5) Address bar

In short, where there is output data, or more accurately, where the data is submitted by the user, it could be a place for XSS attacks.

4.3 Anti-XSS method

Anti-XSS method in fact and anti-injection is very similar, are some filtering, substitution, manifested and other methods

(1) Filter or remove special HTML tags.

For example,:<, >,,, > ', ', <script>, <iframe>,

(2) Filter the tags that trigger JavaScript events. such as onload, OnClick, onfocus, onblur, onmouseover and so on.

(3) Some related functions of PHP, Strip_tags (), Htmlspecialchars (), htmlentities () and other functions can work

5, CSRF

CSRF Cross station request forgery cross site requests forgery.

5.1 Simple explanation CSRF principle

(1) A login Site1 (such as now netizens often on Taobao, Weibo, QQ, etc.), generate some information, session, cookies and so on, and has been maintained did not quit.

(2) A re-login Site2 (such as some adult nets, as for how to run to the Site2, most of the site through some means, mail spoofing, etc.), open the Site2 browser and open the site1 of the same, otherwise invalid

(3) Site2 Station forged the SITE1 HTTP request (such as modify password, buy things, transfer, etc.), Site1 server mistook A in site1 normal operation (because the same browser and a has not logged out), and then ran the request, then CSRF has successfully operated.

CSRF and XSS are very similar. XSS can also forge requests, and CSRF can also make scripts.

Fake requests can be used in many ways, such as sending emails, changing passwords, returning user information, trading, and so on, so the CSRF is more dangerous than an XSS attack.

5.2 Methods of prevention.

For Phper

(1) Strict control of the implementation of the entrance

Perform some sensitive operations such as password change before these operations to determine the source of the request, only the server sent the request can be executed. The method of judgment can judge the IP source. Non-native server IP does not execute.

(2) The site has outside the chain of words to do some necessary operation

General Site2 Hacker will be in site1 (such as the Forum) in the cheating connection, because in the SITE1 deception related personnel are generally logged site1, to meet CSRF gas conditions one.

If you click the QQ message inside the long outside chain time, jump back to a page hint "risky" and so on, so that not only can reduce the bounce rate, some people do not understand the hint, if not unnecessary but is in the curious click of the connection will not continue to click Visit There is the QQ message body in the picture when loading content is not loaded pictures, to click the "Show Picture" button to display pictures, here One reason is to avoid attacks.

Of course, this is not desirable for the user experience, can be optimized to determine some URLs (such as QQ itself) is safe to display directly (without prompting), and suspicious only hint or prohibit.

(3) To prevent CSRF can also use the anti-XSS method.

6, anti-theft chain

hotlinking problems increase the burden on the server. Hotlinking is the hotlinking website to steal hotlinking Web site resources to achieve some functions. Hotlinking are mainly pictures, videos, and other resources to download files.

Methods: To determine IP, only the local server can use site resources, otherwise can not be used.

Code:

(1) Add in Apache htaccess

Copy Code code as follows:

Rewriteengine on
Rewritecond%{http_referer}!^$ [NC]
Rewritecond%{http_referer}!phpben.com [NC]
Rewritecond%{http_referer}!google.com [NC]
Rewritecond%{http_referer}!baidu.com [NC]
Rewritecond%{http_referer}!zhuaxia.com [NC]
Rewriterule. (jpg|gif|png|bmp|swf|jpeg)/image/replace.gif [r,nc,l]
Rewriterule ^ (. *) $ http:\/\/phpben.com\/image\/$1 [L]



In this way, those who are not phpben.com google.com baidu.com zhuaxia.com domain name request return replace.gif instead of return


7. Anti-CC attack

CC attack: The purpose of creating a denial of service by continually sending a connection request to a Web site.

Detailed Baidu Encyclopedia: http://baike.baidu.com/view/662394.htm

Code:

Copy Code code as follows:

Session_Start ();
$ll _nowtime = $timestamp;
if (session_is_registered (' Ll_lasttime ')) {
$ll _lasttime = $_session[' ll_lasttime '];
$ll _times = $_session[' ll_times '] + 1;
$_session[' ll_times ' = $ll _times;
}else{
$ll _lasttime = $ll _nowtime;
$ll _times = 1;
$_session[' ll_times ' = $ll _times;
$_session[' ll_lasttime ' = $ll _lasttime;
}
if (($ll _nowtime-$ll _lasttime) <3) {
if ($ll _times>=5) {
Header (sprintf ("Location:%s", ' http://127.0.0.1 '));
Exit
}
}else{
$ll _times = 0;
$_session[' ll_lasttime ' = $ll _nowtime;
$_session[' ll_times ' = $ll _times;
}

Related Article

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.