[Label] [Php-security] PHP Security Program

Source: Internet
Author: User
Tags html form naming convention trims

This article is made by reading PHP security in http://www.nowamagic.net/into a topic, combined with a little bit of personal development experience.

If you need to see the original text, you can directly visit http://www.nowamagic.net/to see the original text, written very well, the first time you do not understand the words, suggest you see the second time, the quality of the article is very high.

PHP clearly represents the source of user data through super-global arrays such as $_get, $_post, and $_cookie. A strict naming system ensures that you know the source of all the data in any part of the program code, which I have been demonstrating and emphasizing.

1. Register_globals, public variables are automatically established, and when Register_globals is turned on, any use of uninitialized variables almost means a security breach. This is a setting in the PHP.ini configuration file, which is not recommended for use in the PHP5.3.0 version and has been removed in the PHP5.4.0 version;

After setting Register_globals to on in php.ini, you can inject (inject) various variables into your PHP script, such as the various variables-get from the HTML form form and the post parameters.

In summary (this couple and the fact that ...), PHP does not require the initialization of a variable to make it easier to write code that is less secure.

This is a tough choice, but the PHP community has decided to set register_globals default to non-open (disable). When you open a variable, you can't determine where they came from, but guess what they're supposed to be.

The variables defined inside the script will be confused with the request data sent by the user, but we can change the problem by disabling (disable) register_globals.

Let's show through an abusive register_globals example:

<? PHP // Example #1 Example misuse with register_globals = On//define $authorized = True if user is authenticated  If$authorizedtrue;}
Because we didn ' t first initialize $authorized as false, this might is
Defined through register_globals, like for GET auth.php?authorized=1
So, anyone can seen as authenticated!
if ($authorized) {
Include "hightly/sensitive/data.php";
}?>

The best code is that before we use a variable, we have to declare that in the above code, we should first put $authorized = False, which would have affected our code regardless of whether register_globals on or off.

Because even through get auth.php?authorized=1 does not affect our default setting $authorized = False.

<? PHP // Example #2 Example use of sessions with register_globals on or off//we wouldn ' t Knoe where $username came from and to Know $_session//is to SESSION data, so We can use $_sessionif(isset($_session[' Usernam E ']) {    echo ' Hello <b>{$_session[' username ']}</b> ';} Else {    echo ' Hello Guest ';     Echo ' Would to login? ' ;   }? >

2. Do not expose database access rights

Assuming that Db.inc is the user name and password profile for the database, the solution is:

1) Use Apache's rewrite module to reject requests for. Inc Resources.

<files ~ "\.inc$" >

Order Allow,deny

Deny from all

</Files>

2) You can rename the Db.inc to db.inc.php, which will not produce output even if the script is accessed, so it will not be seen.

3) Save the profile directly in the included directory at the root of the Web site, and note that the server should have read access to the file, so there is no URL to access the file.

Note: All resources located at the root of the Web site have a corresponding URL, and if Apache does not define the type of processing for the. inc suffix file, then access to this type of file is returned (the default type) in the form of a normal file, which exposes the contents of the file.

3. Error display configuration

<?PHP//set error level, turn off incorrect display, error logging on, error log record save path    Ini_set(' error_reporting ',E_all|e_strict); Ini_set(' display_errors ', ' off '); Ini_set(' Log_errors ', ' on ');//Start Error Logging    Ini_set(' Error_log ', '/usr/local/apache/logs/error_log ');//Saving path//uses the Set_error_handler () function to set its own error handling function, mixed Set_error_handler (callable $error _handler [, int $error _ types = E_all | E_strict])   Set_error_handler(' My_error_handler '); functionMy_error_handler (...) {......}?>

4. Filter user input: Identify input, filter input, distinguish filtered and contaminated data

Input refers to all data originating from outside. For example, all from the client is input, but the client is not the only external data source, others such as databases and RSS feeds are also external data sources.

In PHP, you use two super-common arrays of $_get and $_post to hold user input data.

Many elements of the $_sever array are manipulated by the client, and it is difficult to confirm which elements make up the input, and the best way is to treat the entire array as input. It is also better to take $_session and database as input to handle.

<?PHP//Prevent cross-catalog//example #1$file _name=$_post[' Name '];Str_replace( ‘..‘  , ‘.‘ ,$file _name);//This practice is caused by other vulnerabilities, when the input has more than 3 points, then the same will happen to the directory jump $file _name_2 = ' .../.../etc/passwd '; Echo Str_replace( ‘..‘ , ‘.‘ ,$file _name_2);//the output results are:.. /.. /etc/passwd//to eliminate this cross-Directory access scenario, you should use loops until you have '.. '$file _name_3=$_post[' Name ']; while(Strpos($file _name_3, ‘..‘) !==false){//as long as there is a jump directory, it has been replaced   $file _name_3=Str_replace(‘..‘ , ‘.‘ ,$file _name_3); }?>
<?PHP//The problem with good intentions is that any attempt to correct illegal data can be a potential error and allow illegal data to pass through//to try to correct illegal data is wrong, only a more secure check is a more secure choice//Example: Customers want to have a space before and after the user name can not log in, As a result of the modification, the user login program was changed//with the trim () function to remove the space before and after the user name entered (this is to correct the illegal data behavior), and//At the time of registration or allow a space before and after, this is a very obvious problem//register if(Strpos($_post[' Register_name '], '){//strpos (), if there is a lookup character, then returns the position of the character, no then returns false Echo' username can not have space! '; }Else{   Echo' Register success. '; }//Loginif(Strpost ($_post[' login_name '], ')){       Echo' Invalid username. ';}Else{   Echo' Login success. ';}?>

1. Trim ()

Note: Possible gotcha:removing Middle characters

Because trim () trims characters from the beginning and end of a string, it could be confusing W Hen characters is (or is) removed from the middle. Trim (' abc ', ' Bad ') removes both ' a ' and ' B ' because it trims ' a ' thus moving ' B ' to the beginning to also be trimmed. So, this is what it "works" whereas trim (' abc ', ' B ') seemingly does not.

http://hk2.php.net/manual/en/function.trim.php

2. Ctype_alnum ()

< Span class= "Apple-converted-space" > bool  Ctype_alnum   (  string  $text  )

Checks if all of the characters in the provided string, text is alphanumeric.

http://hk2.php.net/manual/en/function.ctype-alnum.php

In addition to filtering as an inspection process, you can also use the whitelist method-assuming that the checked data is illegal unless it proves to be legal.

The final step is to use a naming convention or other method to differentiate between filtered and contaminated data.

An easy way to do this is to put all the filtered data into a variable called $clean, and use two steps to prevent the injection of contaminated data:

1) often initialize $clean as an empty array;

2) Add a check and block the variable named clean from the external data source.

As an example:

<form action= "process.php" method= "POST" >Please select a color: <select name= "Color" > <option value= "Red" >red</option> <option value= "Green" >green</ option> <option value= "Blue" >nlue</option> </select><input type= "Submit" name= "Submit"/> </form> <?PHP//Filter Data//Initialize to an empty array to prevent the inclusion of contaminated data, once proof $_post[' color ' is one of the Red,green,blue, save to $clean[' color '] variable. $clean=Array();Switch($_post[' Color ']){  Case' Red ': Case' Green ': Case' Blue ':$clean[' color '] =$_post[' Color '];  Break;}?>

The above example is useful for coming up with data for a set of known legal values , but it doesn't help to filter a set of data that consists of some known legal characters .

For example, you need a user name that can only be made up of letters and numbers

<? PHP $clean Array (); if (ctype_alnum($_post[' username '$clean$_post[' username '];}? >

5. Escape, for both sides: on the one hand, the output of the client must be escaped; On the one hand, data must be escaped for participating database operations

5.1 Escaping the output of the client

<?  $htmlarray// initialized to an empty array to prevent the inclusion of contaminated data $htmlhtmlentities ($clean[' username '], ent_quotes, ' UTF-8 '); // htmlspecialchars ()//quote Escape method (second parameter), should be specified as Ent_quotes, escape single and double quotation marks
Character set (third parameter), character set parameters must be matched to the character set used by the page to match Echo$html[' username ']; >

5.2 Escaping data that participates in database operations

<? PHP $mysql Array (); $mysql mysql_real_escape_string ($clean[' username ']); $sql = "select * from profile           WHERE username = ' {$mysql[' username ']} '"; $result mysql_query ($sql);? >

6. How the user transmits the data:

6.1 via URLs (such as Get Transfer data mode)

If you try to use a request string in an action in a form that is submitted by the Get method, it is replaced with the data in the form.

If you specify a very request method, or if the request method is not written, the browser defaults to the Get method to submit the data.

6.2 Through the content of a request (such as the post data mode)

6.3 Via HTTP header information (such as cookies)

7.URL Semantic attack

8.

[Label] [Php-security] PHP Security Program

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.