PHP Security Basics Chapter 6 files and commands

Source: Internet
Author: User

This chapter mainly discusses the risks arising from the use of files and shell commands. PHP has a large number of file system functions, which are only a small difference from directly executing shell commands. In this chapter, I will emphasize the mistakes that developers often make when using these features.

In general, the risks that come with these features are similar to those mentioned in many books-using contaminated data has catastrophic side effects. Although the vulnerabilities are different, the methods used to deal with them are all methods you have learned.

6.1. File System overlay

No matter how you use a file, you must specify a file name somewhere. In many cases, the file name is used as a parameter of the fopen () function, and other functions call the handle returned by it:

<? PHP

 

$ Handle = fopen ('/path/to/myfile.txt', 'R ');

 

?>

 

When you use contaminated data as part of a file name, the vulnerability occurs:

 

<? PHP

 

$ Handle = fopen ("/path/to $_get['filename'{}.txt", 'R ');

 

?>

 

In this example, the first and second parts of the path and file name cannot be manipulated by attackers, and the possibility of attacks is limited. However, it should be noted that some attacks will use null (expressed as % 00 in the URL) to terminate the string, so that any file extension restrictions can be bypassed. In this case, the most dangerous attack means is to use multiple ../to ask the upper-level directory to achieve the goal of crossing the file system. For example, imagine that the value of filename is specified as follows:

 

Http://example.org/file.php? File... nother/path/to/File

 

Like many attacks, if contaminated data is used when constructing a string, attackers are given the opportunity to change the string, this will cause your application to run in a way you don't want. If you develop the habit of using only filtered data to create dynamic strings, you can prevent the emergence of many types of vulnerabilities that you are not familiar.

Because the static part leading to the name of the file called by fopen () is/path/to, the number of times the above attacks crossed the directory upwards is more than required. Because the attacker cannot view the source code before initiating an attack, the typical strategy is to repeat the.../string multiple times... The usage of the/string is too many times and does not damage the above attack effect. Therefore, attackers do not have to guess the depth of the directory.

 

In the above attack, the fopen () call is run in a way you don't want. It is simplified and equivalent:

<? PHP

 

$ Handle = fopen ('/Another/path/to/file.txt', 'R ');

 

?>

 

After realizing this problem or encountering an attack, many developers attempt to correct Potential Malicious data errors, and sometimes do not check the data first. As described in chapter 1, it is best to take filtering as a check process and force users to follow your rules. For example, if a valid file name only contains lettersCodeThis restriction can be enhanced:

 

<? PHP

 

$ Clean = array ();

 

If (ctype_alpha ($ _ Get ['filename'])

{

$ Clean ['filename'] = $ _ Get ['filename'];

}

Else

{

/*...*/

}

 

$ Handle = fopen ("/path/to/{$clean['filename'{}.txt", 'R ');

 

?>

 

There is no need to escape the filename value because the data is only transmitted to the remote system in the PHP function.

 

The basename () function is useful when checking for unnecessary paths:

<? PHP

 

$ Clean = array ();

 

If (basename ($ _ Get ['filename']) =$ _ Get ['filename'])

{

$ Clean ['filename'] = $ _ Get ['filename'];

}

Else

{

/*...*/

}

 

$ Handle = fopen ("/path/to/{$clean['filename'{}.txt", 'R ');

 

?>

 

This process is a little less secure than only allowing file names to be letters, but it is unlikely that you want to be that strict. A better deep defense process is to combine the above two methods, especially when you use a regular expression to check the validity of the Code (instead of using the ctype_alpha () function ()).

When the end of a file name is composed of unfiltered data, a high-risk vulnerability occurs:

<? PHP

 

$ Handle = fopen ("/path/to/{$ _ Get ['filename']}", 'R ');

 

?>

 

Giving attackers more flexibility means more vulnerabilities. In this example, attackers can manipulate the filename parameter to point to any file in the file system, regardless of the path and file extension, this is because the file extension is part of $ _ Get ['filename. Once the Web server has the permission to read the file, the processing will be directed to the file specified by the attacker.

If the leading part of the PATH uses Contaminated Data, this type of vulnerability will become even larger. This is also the topic of the next section.

 

6.2. Remote File risks

PHP has a configuration option named allow_url_fopen, which is valid by default. It allows you to point to many types of resources and process them like local files. For example, by reading a URL, you can obtain the content of a page (HTML ):

<? PHP

 

$ Contents = file_get_contents ('HTTP: // example.org /');

 

?>

 

As discussed in chapter 5, serious vulnerabilities may occur when contaminated data is directed to include and require files. In fact, I think this vulnerability is one of the most dangerous vulnerabilities in PHP applications because it allows attackers to execute arbitrary code.

Although the severity level is worse, a similar vulnerability may occur if contaminated data is used in a standard file system function:

 

<? PHP

 

$ Contents = file_get_contents ($ _ Get ['filename']);

 

?>

 

In this example, you can manipulate the behavior of file_get_contents () to obtain the content of remote resources. Consider the following request:

Http://example.org/file.php? File... mple.org3162fxss.html

This causes the value of $ content to be contaminated. As this value is obtained indirectly, it is likely to ignore this fact. This is also the principle of in-depth prevention. It will regard the file system as a remote data source and the value of $ content as the input, so that your filtering mechanism will potentially turn around.

Because the $ content value is contaminated, it may lead to multiple security vulnerabilities, including cross-site scripting and SQL injection vulnerabilities. For example, the following is an example of a cross-site scripting vulnerability:

<? PHP

 

$ Contents = file_get_contents ($ _ Get ['filename']);

 

Echo $ contents;

 

?>

 

The solution is never to point to a file name with contaminated data. You must always filter the input, and be sure to be filtered before the data points to a file name:

 

<? PHP

 

$ Clean = array ();

 

/* Filter input ($ _ Get ['filename']) */

 

$ Contents = file_get_contents ($ clean ['filename']);

 

?>

 

Although the data in $ content cannot be completely correct, it provides a reasonable guarantee that the file you read is exactly the file you want to read, not specified by the attacker. To enhance the security of this process, you also need to regard $ content as input and filter it before use.

 

<? PHP

 

$ Clean = array ();

$ Html = array ();

 

/* Filter input ($ _ Get ['filename']) */

 

$ Contents = file_get_contents ($ clean ['filename']);

 

/* Filter input ($ contents )*/

 

$ HTML ['contents'] = htmlentities ($ clean ['contents'], ent_quotes, 'utf-8 ');

 

Echo $ HTML ['tents'];

 

?>

 

The above process provides a powerful way to prevent multiple attacks, and is recommended in actual programming.

 

 

6.3. Command Injection

Using system commands is a dangerous operation, especially when you try to use remote data to construct the command to be executed. If contaminated data is used, the command injection vulnerability is generated.

Exec () is a function used to execute shell commands. It returns the last line of command output after execution, but you can specify an array as the second parameter, so that each line of output will be saved as an element in the array. The usage is as follows:

 

<? PHP

 

$ Last = exec ('Ls', $ output, $ return );

 

Print_r ($ output );

Echo "return [$ return]";

 

?>

 

If the LS command is manually run in shell, the following output is generated:

 

$ Ls

Total 0

-RW-r -- 1 Chris 0 May 21 12:34 PHP-Security

-RW-r -- 1 Chris 0 May 21 :34 Chris-shiflett

 

When running in Exec () through the above example, the output result is as follows:

Array

(

[0] => total 0

[1] =>-RW-r -- 1 Chris 0 May 21 12:34 PHP-Security

[2] =>-RW-r -- 1 Chris 0 May 21 12:34 Chris-shiflett

)

Return [0]

 

This method is convenient and useful for running shell commands, but it brings significant risks to you. If contaminated data is used to construct command strings, attackers can execute arbitrary commands.

I suggest you avoid using shell commands if possible. If you want to use it, make sure to filter the data that constructs the command string and escape the output:

 

<? PHP

 

$ Clean = array ();

$ Shell = array ();

 

/* Filter input ($ command, $ argument )*/

 

$ Shell ['command'] = escapeshellcmd ($ clean ['command']);

$ Shell ['argument'] = escapeshellarg ($ clean ['argument']);

 

$ Last = exec ("{$ shell ['command']} {$ shell ['argument']}", $ output, $ return );

 

?>

 

Although there are multiple methods to execute shell commands, you must stick to one point. When constructing a running string, only filtered and escaped data can be used. Other similar functions that need attention include passthru (), popen (), shell_exec (), and system (). I reiterate that if possible, we recommend that you avoid using all shell commands.

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.