Learn common PHP vulnerabilities and solutions in DVWA

Source: Internet
Author: User
Tags how to fix sql injection

"Security is a whole. to ensure security, it is not how powerful it is, but where it is actually weak." -- Jianxin

From the perspective of many cases of penetration into the intranet of large enterprises, most intruders find vulnerabilities on the Web, so as to exploit the vulnerabilities to further escalate permissions and infiltrate the intrusion.

Netease a system of unauthorized access can cause Intranet penetration: http://www.bkjia.com/Article/201208/151524.html

Netease a system unauthorized access continued-Intranet penetration: http://www.bkjia.com/Article/201208/151741.html

 

Script Security is like your home anti-theft door. Your home door is not closed. Can your home be safe?

The most common scripting vulnerabilities on wooyun are SQL injection and XSS.

The essence of Script Security is that the script accepts insecure variable input without being effectively filtered. Finally, some sensitive functions pose security threats.

For example, the mysql_query () function may cause an SQL injection vulnerability and may cause code execution in eval () and preg_replace.

Here I use DVWA to demonstrate how SQL, XSS, and arbitrary code execution vulnerabilities work.

Then you can use various repair methods to fix the problem.

DVWA: https://github.com/RandomStorm/DVWA/archive/v1.0.8.zip

The file/vulnerabilities/sqli/directory called by DVWA SQL is divided into three levels: low, medium, and high.

SQL Injection principles
// Low. php if (isset ($ _ GET ['submit ']) {// Retrieve data $ id = $ _ GET ['id']; $ getid = "SELECT first_name, last_name FROM users WHERE user_id = '$ id' "; // here, the $ id variable has not been filtered and is directly passed into the SQL statement, cause injection of struct type $ result = mysql_query ($ getid) or die ('<pre> '. mysql_error (). '</pre>'); // Execute SQL


In the original SQL

SELECT first_name, last_name FROM users WHERE user_id = '$id'

$ Id in can be controlled by users. When a hacker changes $ id

' union select user,password from users#

Then this statement will become

SELECT first_name, last_name FROM users WHERE user_id = '' union select user,password from users#

This causes other data in the database to be queried by hackers. Bytes

 
// Medium. if (isset ($ _ GET ['submit ']) in php) {// Retrieve data $ id = $ _ GET ['id']; $ id = mysql_real_escape_string ($ id); $ getid = "SELECT first_name, last_name FROM users WHERE user_id = $ id"; $ result = mysql_query ($ getid) or die ('<pre> '. mysql_error (). '</pre>'); $ num = mysql_numrows ($ result );

 

Although $ id has been escaped by mysql_real_escape_string ', because the SQL statement $ id is not protected by single quotation marks, it will be considered as a numeric type, resulting in numeric injection.

Construct SQL Injection statements

1 union select user,password from users

The SQL statement becomes

SELECT first_name, last_name FROM users WHERE user_id = 1 union select user,password from users 

How to fix SQL Injection

Vulnerability fix for injection:

Php. ini

magic_quotes_gpc=On; 

Magic_quotes_quotes_gpc will escape the passed $ _ POST, $ _ GET, ', ", \ in $ _ SERVER.

However, after PHP5.4, magic_quotes_quotes_gpc was abolished.

Use mysql_real_escape_string () or addslashes () to filter input parameters, or use str_replace () to replace some keywords.

Example:

 
if(isset($_GET['Submit'])){ // Retrieve data $id = addslashes($_GET['id']); $getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id'"; $result = mysql_query($getid) or die('<pre>' . mysql_error() . '</pre>' );  $num = mysql_numrows($result);

 

SQL Injection After patching

However, addslashes () and mysql_real_escape_string () may be bypassed when the database character set is set to GBK.

PHP character encoding Bypass Vulnerability reference article http://www.bkjia.com/Article/201012/79778.html

If the database character set is GBK

$mysqli->query('SET NAMES gbk'); 

To:

$mysqli->set_charset('gbk');

Numeric injection:

Numeric injection is better repaired. You only need to determine whether the input variable is Numeric (or forcibly change it to numeric)

Example:

 
$id = $_GET['id'];$id = intval ($id); $getid = "SELECT first_name, last_name FROM users WHERE user_id = $id"; $result = mysql_query($getid) or die('<pre>' . mysql_error() . '</pre>' );  $num = mysql_numrows($result);

 

Effect after patching

XSS vulnerability Principle

A hacker inserts malicious html code into a Web page. When a user browses this page, the html code embedded in the Web is executed to achieve the Special Purpose of the hacker, for example, user cookies are stolen. or perform other operations. In

 
// Low. php <? Phpif (isset ($ _ POST ['btnsign']) {$ message = trim ($ _ POST ['mtxmessage']); $ name = trim ($ _ POST ['txtname']); // Sanitize message input $ message = stripslashes ($ message); // The stripslashes () function deletes a value from addslashes () the backslash added to the function. $ Message = mysql_real_escape_string ($ message); // use the mysql_real_escape_string () function to escape special characters in strings used in SQL statements. // Sanitize name input $ name = mysql_real_escape_string ($ name); $ query = "insert into guestbook (comment, name) VALUES ('$ message',' $ name '); "; $ result = mysql_query ($ query) or die ('<pre> '. mysql_error (). '</pre>') ;}?>

 

From the above code, we can see that the $ message and $ name variables are passed in from $ _ POST, but only after some special characters. The angle brackets are not escaped, so XSS is still generated.

Insert XSS statement directly

<script>alert(1)<script>

Then

In medium. php, although $ message is escaped by Angle brackets<script>But $ name is not escaped, and cross-site scripts can use multiple tags, such, Etc .... Name<input />The length of maxlength = '10' is restricted, but our defense targets are technically proficient hackers. The length limit in this type of html is that it can be directly modified in the browser .. then, str_replace () can be successfully bypassed through case sensitivity, and XSS can be inserted.

 

<SCript>alert(1)</SCript>

Bytes

 
<? Php if (isset ($ _ POST ['btnsign']) {$ message = trim ($ _ POST ['mtxmessage']); $ name = trim ($ _ POST ['txtname']); // Sanitize message input $ message = trim (strip_tags (addslashes ($ message ))); $ message = mysql_real_escape_string ($ message); $ message = htmlspecialchars ($ message); // Sanitize name input $ name = str_replace ('<script> ','', $ name); // It can be bypassed with a single case, or  $ name = mysql_real_escape_string ($ name); $ Query = "insert into guestbook (comment, name) VALUES ('$ message',' $ name');"; $ result = mysql_query ($ query) or die ('<pre> '. mysql_error (). '</pre>') ;}?>

 

How to fix XSS vulnerabilities

Use htmlspecialchars () to escape the output content during output.

Sleep long said: it is better to escape data in the output than to escape data in the input, because it can ensure that the data is complete in the input .... Otherwise, data is lost.

Example:



<?php if(isset($_POST['btnSign'])){    $message = trim($_POST['mtxMessage']);   $name    = trim($_POST['txtName']);    // Sanitize message input   $message = stripslashes($message);   $message = mysql_real_escape_string($message);   $message = htmlspecialchars($message);    // Sanitize name input   $name = stripslashes($name);   $name = mysql_real_escape_string($name);    $name = htmlspecialchars($name);    $query = "INSERT INTO guestbook (comment,name) VALUES ('$message','$name');";     $result = mysql_query($query) or die('<pre>' . mysql_error() . '</pre>' ); } ?>
 

After the patch, you can see that the angle brackets have been escaped and the html code has not been executed.

Principle of Arbitrary Command Execution Vulnerability

Arbitrary Command Execution is the most dangerous vulnerability in the web. You may be able to directly write down the shell or add users directly.

Most of the arbitrary command execution vulnerabilities are generated because variables can be controlled by user input. Without any judgment or filtering, they enter high-risk functions.

 
<?php if( isset( $_POST[ 'submit' ] ) ) {     $target = $_REQUEST[ 'ip' ];     // Determine OS and execute the ping command.    if (stristr(php_uname('s'), 'Windows NT')) {          $cmd = shell_exec( 'ping  ' . $target );        $html .= '<pre>'.$cmd.'</pre>';     } else {          $cmd = shell_exec( 'ping  -c 3 ' . $target );         $html .= '   <pre>'.$cmd.'</pre>';     } }?>

 

Because $ target enters the shell_exec function without processing it, hackers can construct special variables to execute batch processing commands.

I can enter 0 | dir

The command to run is ping-c 0 | dir

If the hacker inputs

0|net user hacker/add

The consequences will be unimaginable.

The following are functions that may cause arbitrary command execution:

system|passthru|exec|popen|proc_open|move_uploaded_file|eval|copy|shell_exec|assert
Arbitrary command execution vulnerability fix

When writing a program, try to prevent the variable from being controlled by the user! Pay attention to variable initialization issues.

Use str_replace to replace "%", "|", and ">"

Determine whether the variable is valid before entering the function.

Brute force cracking

Is this a vulnerability? That's right...

Sacrifice the artifact Burp Suite. After the Burp suite is run, the default port 8080 is enabled for the Burp suite and Proxy as the local Proxy interface.

Use Burp suite to use its proxy server by setting up a web browser. For details, refer

Then open the background where you want to crack the brute-force attack, enter an account and password at will... Send the captured package to intruder into failed

Start attack ~~~

Then, the returned package size is displayed, and the password is displayed.

How to fix brute-force cracking

Add a google Verification Code to ensure that no program can recognize it...

File Inclusion Vulnerability

There are two types of File Inclusion vulnerabilities: Remote inclusion and local inclusion.

When the server uses php features (functions) to include arbitrary files, the file source to be included is not strictly filtered, so you can call and execute a file (Trojan ), and we can construct this article (wood) (Horse) to achieve evil purpose.

Dangerous functions involved: include (), require (), include_once (), require_once ()

Currently, there are not many remote vulnerabilities, but the greatest danger of remote inclusion is that it is equivalent to executing a command.

The local inclusion, sometimes with the parsing vulnerability, can often be getshell.

Example:

 
<?php      $file = $_GET['page']; //The page we wish to display    ?>

 

Include. php content:

 
<?php echo "hello world\n"; ?>

 

Summary

When writing a program, you should have good code habits, such as initialization before using variables.

Perform Security filtering globally or write it in the class.

Do not trust data. All input data is untrusted before it is proved. All input data from users should be judged.

Does not return the cause of too many errors, such as a hacker performing SQL injection.


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.