The cause analysis and precautionary method of PHP Program Vulnerability _php Tutorial

Source: Internet
Author: User
misuse of include

1. Cause of vulnerability:

Include is the most commonly used function for writing PHP sites, and supports relative paths. There are many PHP scripts that directly use an input variable as an include parameter, resulting in arbitrary reference scripts, absolute path leaks, and other vulnerabilities. Look at the following code:

...
$includepage =$_get["Includepage"];
Include ($includepage);
...

Obviously, we just need to submit a different includepage variable to get the desired page. If you submit a page that does not exist, you can make the PHP script error and reveal the actual absolute path (the solution to this problem is described in the following article).

2. Vulnerability Resolution:

The solution to this vulnerability is simply to determine if a page exists and then include. or more strictly, use an array to specify the files that can be include. Look at the following code:
Copy the Code code as follows:
$pagelist =array ("test1.php", "test2.php", "test3.php"); The file for include can be specified here
if (Isset ($_get["Includepage"))//Determine if there is $includepage
{
$includepage =$_get["Includepage"];
foreach ($pagelist as $prepage)
{
if ($includepage = = $prepage)//Check whether the file is in the Allow list
{
Include ($prepage);
$checkfind =true;
Break
}
}
if ($checkfind ==true) {unset ($checkfind);}
Else{die ("Invalid reference page! "); }
}

This will be a good solution to the problem.

Tip: There are functions for this problem: require (), require_once (), include_once (), ReadFile (), etc., and should be noted at the time of writing.

No filtering of input variables

1. Cause of vulnerability:

This vulnerability has occurred in the ASP, which caused countless injection vulnerabilities. But because of the small impact of PHP at the time, so not many people can pay attention to this. For PHP, this vulnerability is much more influential than ASP because there are more PHP scripts that use a text-based database. There are, of course, problems with the injection of SQL statements. To give a more classic example, the first is the database:
Copy the Code code as follows:
$id =$_get["id"];

$query = "SELECT * from my_table where id= '". $id. "'"; A classic SQL injection vulnerability
$result =mysql_query ($query);

It's clear that we can use injections to get the rest of the database. Here is no longer detailed description, and ASP injection, you can look at the previous black defense. Then we look at the problem with the text database:
Copy the Code code as follows:
$text 1=$_post["Text1"];
$text 2=$_post["Text2"];
$text 3=$_post["Text3"];

$FD =fopen ("test.php", "a");
Fwrite ($FD, "\r\n$text1&line; $text 2&line; $text 3");
Fclose ($FD);

The vulnerability of the text can be said to be more serious. If we insert a very small PHP code into our commit variable, we can turn the text database test.php into a PHP backdoor. Even insert the upload code so that we can upload a perfect php back door. Then elevate the permissions, the server is yours.

2. Vulnerability Resolution:

The solution to this vulnerability is simply to filter all committed variables Strictly. Replace some sensitive characters. We can replace the contents of HTML with the Htmlspecialchars () function provided by PHP. Here is an example:
Copy the Code code as follows:
Constructing filter functions
function Flt_tags ($text)
{
$badwords =array ("to", "fuck"); Glossary filter List
$text =rtrim ($text);
foreach ($badwords as $badword)//filter the words here
{
if (Stristr ($text, $badword) ==true) {die ("error: The content you submit contains sensitive words, please do not submit sensitive content.) "); }
}
$text =htmlspecialchars ($text); HTML substitution
These two lines replace the carriage return with the

$text =str_replace ("\ R", "", $text);
$text =str_replace ("\ n", "", $text);
$text =str_replace ("&line;", "│", $text); Text Database Separator "&line;" Replace with full-width "│"
$text =preg_replace ("/\s{2}/", "", $text); Space replaces China Network Management Alliance
$text =preg_replace ("/\t/", "", $text); or a space replacement
if (GET_MAGIC_QUOTES_GPC ()) {$text =stripslashes ($text);}//If Magic_quotes is turned on, replace with \ '
return $text;
}

$text 1=$_post["Text1"];
$text 2=$_post["Text2"];
$text 3=$_post["Text3"];

Filter all Inputs
$text 1=flt_tags ($text 1);
$text 2=flt_tags ($text 2);
$text 3=flt_tags ($text 3);

$FD =fopen ("test.php", "a");
Fwrite ($FD, "\r\n$text1&line; $text 2&line; $text 3");
Fclose ($FD);

After a few substitutions and filters, you can safely write data to a text or database.

The administrator does not judge completely

1. Cause of vulnerability:

We use PHP to write scripts, usually involving administrator permissions issues. While some scripts only make "yes" judgments about administrator privileges, they often ignore "no" judgments. In the case of register_globals open in the PHP configuration file (the 4.2.0 version is turned off by default, but many people open it for convenience, which is extremely risky behavior), a commit variable is presented as an administrator. Let's take a look at the example code:
Copy the Code code as follows:
$cookiesign = "Admincookiesign"; Determine if the admin cookie variable
$adminsign =$_cookie["sign"]; Get user's Cookie variable

if ($adminsign = = $cookiesign)
{
$admin =true;
}

if ($admin) {echo ' is now an administrator state. "; }

It looks like it's safe, huh? Now let's assume that the PHP configuration file is register_globals open. We submit such an address as "test.php?" Admin=true ", did you see it? We do not have the correct cookie, but because Register_globals is open, the admin variable we submit is automatically registered as true. And the script lacks the "no" judgment, it makes us smoothly through the admin=true to obtain the administrator's permission. This problem exists in most websites and forums.

2. Vulnerability Resolution:

To solve this problem, we only need to add the "no" in the script to the Administrator's judgment. We still assume that the PHP configuration file is register_globals in the open state. Look at the code:
Copy the Code code as follows:
$cookiesign = "Admincookiesign"; Determine if the admin cookie variable
$adminsign =$_cookie["sign"]; Get user's Cookie variable

if ($adminsign = = $cookiesign)
{
$admin =true;
}
Else
{
$admin =false;
}
if ($admin) {echo ' is now an administrator state. "; }

This way, even if an attacker submits a admin=true variable without the correct cookie, the script will set $admin to False in a later judgment. This solves some of the problems. However, since $admin is a variable, a new crisis will arise if a vulnerability in subsequent script references causes the $admin to be re-assigned. Therefore, we should use constants to hold the decision of administrator privileges. Use the Define () statement to define an admin constant to record the administrator's rights, after which a re-assignment will make an error, for protection purposes. Look at the following code:
Copy the Code code as follows:
$cookiesign = "Admincookiesign"; Determine if the admin cookie variable
$adminsign =$_cookie["sign"]; Get user's Cookie variable

if ($adminsign = = $cookiesign)
{
Define (admin,true);
}
Else
{
Define (ADMIN,FALSE);
}
if (admin) {echo ' is now an administrator state. "; }

It is important to note that we use the Define statement, so when calling the admin constant, do not precede the habitual variable symbol $, but should use the admin and!admin.

Text Database exposure

1. Cause of vulnerability:

As mentioned earlier, because the text database has great flexibility, no external support is required. In addition, PHP has a strong ability to handle files, so the text database is widely used in PHP scripts. There are even a few good forum programs that use a text database. But there will be lost, the security of the text database is also lower than other databases.

2. Vulnerability Resolution:

Text database as an ordinary file, it can be downloaded, just like an MDB. So we're going to protect the text database with the MDB protection method. Change the suffix name of the text database to. Php. And join in the first row of the database. The text database will act as a php file and exit execution on the first line. That is to return an empty page, so as to achieve the purpose of protecting the text database.

Error path Disclosure

1. Cause of vulnerability:

When PHP encounters an error, it gives the location of the error script, the number of rows, and the reason, for example:

Notice:use of undefined constant test-assumed ' test ' in D:\interpub\bigfly\test.php on line 3

A lot of people say it's not a big deal. But the consequences of revealing the actual path are disastrous, and for some intruders, this information is very important, and in fact there are a lot of servers that are having this problem.

Some network management simply set the PHP configuration file display_errors to off to solve, but I think this method is too negative. Sometimes, we really need PHP to return the wrong information for debugging. And in the case of errors may also need to give the user a confession, or even navigate to another page.

2. Vulnerability Resolution:

PHP provides the function Set_error_handler () of the custom error handling handle starting from 4.1.0, but very few script writers know. In many of the PHP forums, I've only seen a handful of them deal with this situation. Set_error_handler is used as follows:

String Set_error_handler (callback Error_Handler [, int error_types])

Now we are using custom error handling to filter out the actual path.
Copy the Code code as follows:
Admin is the administrator's identity, and true is administrator.
The custom error handler must have these 4 input variables $errno, $errstr, $errfile, $errline, otherwise invalid.
function My_error_handler ($errno, $errstr, $errfile, $errline)
{
Filter the actual path if it's not an administrator
if (!admin)
{
$errfile =str_replace (GETCWD (), "", $errfile);
$errstr =str_replace (GETCWD (), "", $errstr);
}

Switch ($errno)
{
Case E_ERROR:
echo "ERROR: [ID $errno] $errstr (line: $errline of $errfile)
\ n ";
echo "program has stopped running, please contact the administrator. ";
Exit script when error level errors are encountered
Exit
Break
Case e_warning:
echo "WARNING: [ID $errno] $errstr (line: $errline of $errfile)
\ n ";
Break
Default
Do not show errors at notice level
Break
}
}

Set the error handling to the My_error_handler function
Set_error_handler ("My_error_handler");
...

In this way, it can be a good solution to the security and debugging convenience contradictions. And you can also take a little thought to make the error message more beautiful to match the style of the website. But note that two points are:

(1) E_error, E_parse, E_core_error, e_core_warning, E_compile_error, e_compile_warning are not handled by this handle, that is, it will be displayed in the most primitive way. However, these errors are either compiled or the PHP kernel is faulty and will not normally occur.

(2) after using Set_error_handler (), the error_reporting () will be deactivated. That is, all errors (except for the above errors) will be given to the custom function processing.
For other information about Set_error_handler (), please refer to the official PHP manual.

Post vulnerability

1. Cause of vulnerability:

As already mentioned, it is a bad habit to rely on register_globals to register variables. In some of the message book and forum procedures, but also to strictly check the way to get the page and the time interval of submission. To prevent posting and external submissions. Let's take a look at one of the following messages the code of this program:
Copy the Code code as follows:
...
$text 1=flt_tags ($text 1);
$text 2=flt_tags ($text 2);
$text 3=flt_tags ($text 3);

$FD =fopen ("data.php", "a");
Fwrite ($FD, "\r\n$text1&line; $text 2&line; $text 3");
Fclose ($FD);

Obviously, if we submit the URL "post.php?text1=testhaha&text2=testhaha&text3= testhaha". The data is written to the file as expected. This program does not detect the source of the variable and how the browser obtains the page. If we repeatedly commit to this page, it will play a role in flooding. Now there are some software to use this loophole to send ads on the forum or message book, this is shameful behavior (my friend's message was in 1 weeks was filled 10 pages, helpless).

2. Vulnerability Resolution:

Before data processing and saving, first determine how the browser gets the page. Use the $_server["Request_method"] variable to get the browser's way to get the page. Check to see if it is "POST". Use the session in the script to record whether the user submits the data through a normal path (that is, the page that fills in the submission). or use $_server ["http_referer"] to detect, but this is not recommended. Because some browsers do not have Referer set up, some firewalls will also block referer. In addition, we want to check the content of submissions to see if there are duplicates in the database. Take the message book as an example, use the session to determine:
Fill in the content of the page, we added at the front end:

$_session["Allowgbookpost"]=time (); The time when the registration was completed

In the page that accepts the message data and saves, we also use the session to carry on the following processing before the data processing:
Copy the Code code as follows:
if (Strtoupper ($_server["Request_method"])! = "POST") {die ("error: do not commit externally. "); } Check if the page Get method is post
if (!isset ($_session["Allowgbookpost"]) or (Time ()-$_session["Allowgbookpost"] <) {Die ("error: do not commit externally.) "); } Check the time when the message was filled out
if (Isset ($_session["Gbookposttime"]) and (Time ()-$_session["Gbookposttime"] <) {Die ("error: Two submissions must not be less than 2 minutes apart. "); } Check the message interval

Unset ($_session["Allowgbookpost"]); Unregister the Allowgbookpost variable to prevent a single entry into the fill page for multiple commits
$_session["Gbookposttime"]=time (); Register time to send messages to prevent flooding or malicious attacks
...

Data processing and preservation

http://www.bkjia.com/PHPjc/736794.html www.bkjia.com true http://www.bkjia.com/PHPjc/736794.html techarticle abuse include 1. Vulnerability cause: Include is the most commonly used function in writing PHP sites, and supports relative paths. There are many PHP scripts that directly use an input variable as an include parameter, resulting in any ...

  • 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.