preamble
Today, we're going to dive into the Upload File Vulnerability attack, which is part of the EdgeOne Specialized Practices chapter. In this chapter, we won't cover basic tutorials on the meaning, principles, or site configuration of file vulnerabilities, so if you're interested in those, you can refer to this article:Exploring Network Security: Analyzing File Upload Vulnerabilities
Basic applications such as how to buy a package or configure a site will not be detailed after this paragraph. And when we're done explaining attacks, I'll also share some precautions to protect your server from attacks. Therefore, the focus of this article remains on Tencent Cloud's EdgeOne.
Range Building
When we consider that attacking other people's servers is illegal, we need to think about how to better protect our own servers. To test and learn, we can build a specialized range to simulate file upload vulnerability attacks. Below is the environment and some references for me to build the range for your learning and reference, or you can explore the content on your own.
When using the Linux version of the Tencent Cloud Lightweight Application Server, there may be many errors in building it on your own, given the more stringent environmental requirements. It can be deployed quickly by simply pulling docker images packaged by others.
docker pull c0ny1/upload-labs
docker run -d -p 8289:80 c0ny1/upload-labs
After startup, please make sure to go to the Tencent Cloud console to configure firewall rules, otherwise you may not be able to access it normally. You can replace the access address with your own configured IP address and port number:http://ip:8289。
The system can start normally. However, when trying to upload files, the system prompts that the required upload directory cannot be found. To resolve this issue, you need to manually add a new upload directory via the docker container console.
Go in and execute the following command:
mkdir upload
chmod 777 upload
Everything is running fine at the moment and the range has been successfully set up! Please keep in mind that you should not attack other people's servers after the study is complete. This is vital to remember, remember, remember.
File Upload Vulnerability
There are 20 levels in the range, and each level represents a different vulnerability case. Here, I will choose a few typical cases to share and learn from. So, let's start now!
upload-labs shooting range cheats
In order to avoid distracting you with long texts, I have prepared a concise flowchart to help you understand it quickly. Please take a look at this diagram first and I am sure you will find everything very simple. Now we are ready to go, please fasten your seat belts.
Next, all of our tasks rely on uploading one or more files to access the server configuration information. The design of the attack script is also extremely simple, and its goal is equally clear: simply access our attack script through other means and execute it successfully.
<?php
phpinfo();
?>
When we talk about the usefulness of obtaining information, can it be used for attacks? Actually, our main purpose is to execute the script. It doesn't matter about the content of the script, the key is to be able to execute it smoothly. You can replace the script's statements as you like, for example, like AntSword's one-sentence script to get the shell. this is just to demonstrate the purpose of the attack.
Let's start explaining how to use the range, please note that each page is equipped with the ability to view the source code and view hints. If you are still not sure how to perform an attack after viewing the source code, you can follow the tips to break in step by step. So, let's get started.
Front-end Page Validation Vulnerability
Let's look at the source code first:
When we look at this code, we can note that there is just a basic postfix check on the front end here.
Then, we have the option of uploading without relying on the tool by modifying the front-end code to remove this validation step, or manually modifying the request to change the file extension to .php. We can start with the simple method.
Next, perform a delete operation and save the file, followed by uploading our script file again.
Please make sure to refresh the page after saving the changes so that the interface recognizes our uploaded files ending in .php.
Since this is not an image, it cannot be displayed. Therefore, please right-click and copy the image path to view it. The operation has been executed successfully.
Backend Checksum File Type Vulnerability
Of course, even the worst companies can't rely solely on the front-end for checksums, so the second stage begins to involve back-end operations. Now let's move on to the source code;
The main function of the backend is to get the type of the uploaded file. To change the file type, we need to intercept it using the Burp Suite tool. Simply changing the file suffix is not enough, because the file type transferred here is passed via the Content-Type header, specificallyapplication/octet-stream
。
When the system background judgment based on the file type, we only need to adjust the file type to meet the requirements of the background checksum, as shown below:
Unsurprisingly, we still find successful uploads.
The remaining step is to right-click on the address that opens the image file. In the next level, we no longer need the demo to view the PHP information, we just need to pass the validation to make sure our code runs successfully.
Older versions of file extensions
At this hurdle, if it turns out that you can't effectively perform checksums anyway, then the best practice is to simply restrict the suffixes of uploadable files. However, relying solely on file extensions for restriction also has potential security risks. Let's analyze this issue in depth.
In the early days of web development, PHP files often ended with a .php3 extension. This is because older versions of PHP only supported the .php3 extension and not .php directly, and although modern PHP versions no longer enforce specific file extensions, there are still some websites that still use the .php3 extension for historical or compatibility reasons. To support these older sites, Apache is configured by default to support parsing of PHP files with the .php3 extension.
Now the problem becomes very simple, we just need to upload those files that are not in the suffix restriction array and then everything is done.
Utilizing Apache configuration files
When it comes to the above, some may have recognized that it is no longer acceptable to use simple file extensions at will. I need to fully review and tighten up the restrictions in this area so that we are at stage four. Now let's take a closer look at the source code.
Of course, we don't have to limit ourselves to uploading PHP files. This time, we can exploit another configuration file vulnerability.
.htaccess
is a configuration file used to configure the Apache web server, whose name is an acronym for "hypertext access". It allows webmasters to configure the Apache web server without modifying the main configuration file (such as the) case, by creating a web site root directory or a specific directory under the
.htaccess
file to configure and control the behavior of the site.
.htaccess
Files can contain a variety of directives and rules for controlling access to your website, redirecting URLs, setting custom error pages, enabling compression, disabling directory listings, limiting access rates, and more. This can be accomplished by using the.htaccess
file, site administrators can achieve flexible configuration and management of the site without the need for server-level access.
It is important to note that.htaccess
file is only valid for Apache Web servers and its configuration may affect the performance of the site, especially if it contains complex rules or requires frequent file reads.
Then we'll write the script first and then transfer the file.
<FilesMatch "">
SetHandler application/x-httpd-php
</FilesMatch>
This means that when a file named is accessed, the Apache web server treats it as a PHP script, rather than simply returning it to the user as a static file.
Go ahead and upload the jpg image, even though the file is actually an attack script masquerading as an image.
case-hole (computing)
When the personnel discovered the vulnerability, a simple addition of a restriction solved the problem. Therefore, the solution for the fifth level is to simply disable the uploading of .htaccess files.
Of course, he failed to notice another problem. Check the source code again.
The filenames are all lowercase, but we need to check if PHP supports uppercase filenames. We can try to test this by intercepting the request directly and modifying the filename.
gap loophole
After detecting case, and after a detailed review of the source code, it was found that there was no space restriction. If indeed there is no space restriction, then the file suffix restriction will also be invalidated.
We use Burp Suite to intercept the request for sending. I've added a space after the filename itself, as there is no filename by default.
The file is eventually uploaded successfully. There are many other ways to bypass the file suffix check, so we won't list them all. The problem lies mainly in the laxity in parsing the code, and by exploiting one of these vulnerabilities it is possible to upload our script file directly.
File Inclusion Vulnerability
When this image is no longer just a simple visual element, it may look quite unusual on the front, however it actually contains a piece of code on the back half.
Look at the source code for this level
When we read only the first two bytes, it is usually to obtain the header information of the image file, which contains important data about the file type and format. Next, we can open all three image files and edit them using Notepad to explore whether they share any common features or attributes.
Another thing to look out for in this section is file inclusion vulnerabilities. Do you know what a file inclusion vulnerability refers to?
<?php
/*
This page has a file inclusion vulnerability and is used to test if the image horse works!
*/
header("Content-Type:text/html;charset=utf-8");
$file = $_GET['file'];
if(isset($file)){
include $file;
}else{
show_source(__file__);
}
? >
By using the include function directly and not filtering or validating the $file parameter sufficiently, an attacker could construct a malicious request to include any file, even a remote malicious file. So let's upload a file, get the file address, and try this file inclusion vulnerability, which shows that there is indeed such a risk.
Secondary rendering bypass
There is a lot of source code for this level, so I decided to just copy and share the key code for your reference.
// Generate a new image using the uploaded image
$im = imagecreatefromjpeg($target_path);
// Generate a new image using the uploaded image
$im = imagecreatefrompng($target_path);
//Generate a new image using the uploaded image
$im = imagecreatefromgif($target_path);
The main purpose of this step is to determine the format of the image uploaded by the user and regenerate the new image. Particular attention is paid to the handling of GIF images in this process.GIF images change very little after re-rendering, mainly due to the optimization of their compression algorithms and the fixed limitations of the format, so that most of the modifications affect only a small portion of the data, without causing substantial changes to the entire image file.
We need to improve the process: first of all, please make sure that you do not modify the image file randomly, but upload and download the image first, and then compare it with the local image. Identify the unchanged parts, then copy and paste the code one by one, and adjust the position if there is any error.
We ended up changing it here:
Continue to use the file inclusion vulnerability after uploading:
conditional concurrent competition
At this stage, the uploaded file is simply saved, then verified, renamed and the file moved. If the checksum fails, the file is deleted. On the surface this may seem fine, but in reality there are many potential vulnerabilities.
First, the save operation is performed without file type validation, and only later is it validated and deleted. This vulnerability provides us with an entry point to attack the server. We can use Burp Suite to intercept the request and launch a focused attack. As long as I have access to the file I uploaded before the delete operation is performed, I can execute the script. Now it's time to get started.
Once we have successfully intercepted the request, the next step is to configure the concurrent requests for exploitation. We plan to start the attack with a default of 10 concurrency.
Observe the effects of the attack here, and although they are usually removed in time, the attack can be considered successful as long as we manage to access one of them. Let's get started.
After explaining how file uploads can be used to attack servers, the next focus is on understanding how to effectively defend against these attacks. It is crucial to implement good protection measures on the server side because defense is better than offense. Next, we will look at how to strengthen server security based on the classic examples mentioned above.
EdgeOne Protection
Assuming that we are not able to check the code written by programmers, or that we do not have the ability to perform code audits ourselves, then we have to rely on external protection measures. In this case, EdgeOne is still recommended today to solve these problems. In order to make it clearer for you to understand, I have also drawn a simple diagram as a reference, after looking at the diagram the problem becomes very simple, just apply it as easily as using a pluggable middleware in your architecture.
File Vulnerability Protections
We have discussed in detail the various methods of attack earlier, so let us now summarize what should be done to protect against them:
- Unrestricted file types: allows uploading of any type of file, including executables.
- No file content checking: The file content was not checked for malicious code.
- Unrestricted file upload frequency: When we demonstrated just now, we could see that the conditional competition state was reached by uploading files frequently.
In addition to the previously mentioned measures, there is one more thing to keep in mind, namely the file size limit. Considering that we have our own server resources, we can avoid unnecessary traffic consumption. Therefore, we need to have proper control in this area as well.
Next, we'll implement each of these protections one by one, and you'll see that with minimal tweaking, we're able to achieve optimal security.
File Sensitive Suffix Checking
If you intend to upload a webshell, the file content must contain scripted content. Therefore, we need to make sure that EdgeOne provides the relevant checking and validation features. Once you have purchased the standard version of EdgeOne, you can immediately upload files and check if they can be effectively intercepted without any modifications.
In general, EdgeOne should intercept such requests, but we need to look at the sample logs again to confirm that there are indeed requests that are not being intercepted.
When we noticed this, we realized that the request was not only captured, but also recognized as a guard rule, but was actually in the observe state rather than the direct intercept state. This is important because by default, EdgeOne only observes and does not directly intercept requests. We need to look further into the ID of this rule to understand its exact function.
First of all, after entering your configured site, find Security - >Web Protection - >Managed Rules - >Filter Rule ids
This is quite tedious because the specific limitations of the current rule id are not directly shown in the sample logs, and we need to look them up ourselves. However, eventually we do find this information. In this way, we can recognize file suffixes, which eliminates the need to write a lot of restriction code on the front-end and back-end when dealing with file suffixes.
In fact, the file upload vulnerabilities in the previous cases were mainly due to file suffix issues.EdgeOne technology can solve the problem of sloppy programmer code in a simple way.
When it comes to related guard requests, remember to turn off global watch mode, which allows you to configure how each rule is intercepted individually. So, for now, let's turn global watch mode off.
So let's launch the requests again to make sure we can effectively intercept them.
Have we flipped the show? Why are we still in observe mode, I would have thought we would be in intercept request state, not just in observe mode. There's a level of protection involved that we need to review, and the default settings may be a bit on the loose side.
Then we need to adjust the level of protection to ensure that it blocks requests that should not directly access the backend. Note, however, that we can't set up a rule on its own, and if we need to do so, it must be set up in the same way as the parent rule. Let's take a closer look:
Certainly! So we can now try to upload a file in order to see how it turns out.
The effect is very significant in practical applications. No more demonstrating the remaining various oddball sensitive suffixes, as the final blocking results are all consistent. For businesses or individuals, the experience is also excellent with two simple button switches.
Pseudo-file code injection checking
When we tried to circumvent the suffix check, we made a file with a .jpg suffix, but it was actually a disguised image file. Let's first verify that this simple disguised file works.
When the content of the file is actually a PHP script, even though our file extension is set to .jpg is not a sensitive extension file and therefore may be able to circumvent EdgeOne's suffix rule checking. Therefore, we can try to upload it and see if we can execute it successfully.
The attempt was not successful. So let's see if he's blocked by that security protection rule.
Once we have successfully bypassed the protection check for the sensitive suffix, then what needs to be further analyzed now is which specific rule this is being circumvented.
The protection is really quite good, php scripts have been blocked.
So, when we test more advanced camouflaged files, such as embedding code scripts in a normal-looking image file, will the protection rules be able to detect them? As we explored ways to bypass secondary rendering of images, we experimented and tested injecting PHP code into a GIF file, as shown below:
Of course, we can see if there is a way to bypass the guard? But it seems that the guard is still effective in stopping it.
Taking a look at these sample logs, since they all belong to the same protection rule ID, we won't repeat the view and will continue to explore other means of testing.
In addition to the above code injection to prevent image rendering, another way to prevent image rendering if no secondary rendering is performed is to add content directly to the end of the image. This is simple to do, and we'll see if it provides additional protection next.
The demo has gone a little wrong, but that's okay. If the protection doesn't work, it doesn't matter, we can still contact Tencent customer service and get feedback on the situation in a hurry. I'll give them all the test files and links to the site so they can test it and find out what's wrong.
After a long period of in-depth communication and analysis, we finally succeeded in helping them identify a problem and left the rest to them to solve on their own.
Why is there no demonstration of conditional competition protection here? Shouldn't an upload frequency rule be added? I'm not sure everyone remembers that conditional contention attacks are launched by uploading a PHP script and then launching the attack within a short window of time when the inspection passes. First, the PHP script must be successfully uploaded, but EdgeOne already intercepts such scripts, so how can this effectively enforce subsequent upload rate limits?
File Upload Rate Limit
We previously discussed avoiding demo conditional contention attacks, but now why is there an upload rate limit? This limit is to prevent frequent file uploads from causing abnormal IO congestion on the server network. This actually involves two issues: on the one hand, we're not talking about attacking the server via scripts, but rather the possibility that users may hog server resources by uploading files frequently. As soon as the uploads are frequent enough, there is a possibility that the server will not be able to respond to other users' accesses, which in turn will lead to a website downtime situation. This is a very serious situation and the impact can be quite severe.
Without further ado, let's run the demo and set some limits. Since uploading a script file will be blocked, we will upload a normal image for the demo. Also, we will use Burp Suite to frequently test file uploads against the server as shown in the image:
Then, we launch concurrent requests directly. We plan to follow the following rules for testing concurrency: 5, 10, 15, 30, and 100 times per second. First, we will test with 10 concurrencies per second and then try 100 concurrencies per second.
After we've sent the request multiple times, check out what's going on with the server resources.
Here the server's traffic encapsulation rises, and although the site is still accessible, our purpose has been accomplished by consuming a significant amount of the site's traffic.
You can view the statistical analysis of EdgeOne, this time not limited to Web security analysis, but focusing on metrics analysis. We can observe anomalous traffic requesting the server in large numbers, what measures should we take in the face of this situation?
You can see the request analysis again below. As shown in the figure:
First, by analyzing the graph, we can determine the IP addresses of the requests and which URLs they make frequent requests to, and this information will provide us with a basis for developing an effective policy.
Although this method is not optimal, we can blacklist the IP addresses of our customers to restrict their access to our site. This method is clunky because customer IPs can change, causing us to constantly update our configuration, but it is at least a viable measure.
Then, the next thing we need to do is to add IP addresses to the blacklist, which will simply add security. Of course, you can add IP address segments to suit your personal needs. In this example, I have only added one IP address for demonstration purposes.
Okay, saved. Next, let's try sending the request and see if it has been successfully intercepted.
Once all requests have been successfully intercepted, we can take another look at the sample log.
Yes, this rule ID is the unique identifier that was just generated by us.
When this is taken into account, the second approach is to limit the frequency of requests.
The limits here are too loose, we need to tighten them up a bit. One can't request that fast.
As we continue to send concurrent requests for testing, we can observe that EdgeOne has been able to recognize subsequent requests and has used JavaScript challenge scripts rather than responding directly from the server.
The same can be observed when we review the sample logs.
This is a simple global restriction. Of course, some business users may have websites that require allowing customers to make a large number of clicks, and this needs to be considered. But there's no need to rush, we can control this process precisely. Next we discuss how to set request limits for specific URLs. We analyze where unusual requests are being made based on metrics to set control policies accordingly. You can set your own limits based on your individual needs.
I've set all restrictions involving file upload paths here. We need to double check that all these paths have been completely blocked. For example./Pass-10/
。
It does seem to successfully block potential attacks. As for the upload rate, let's discuss it here.
File Size Limit
There is a limit to the speed, and customers should not be allowed to upload files that are too large. We only need to upload pictures, not videos, so it is reasonable to set an upper limit, for example, no more than 2M, this range should be adapted to most needs. Now let's do it. Note that this operation is not performed in the Web Protection layer, but is set in the Site Acceleration layer.
For better demonstration, I won't use global configuration but differentiated configuration. This means that we will individually configure file uploads under specific paths based on business requirements, as shown in the figure.
When we try to upload a very large file in order to test the upload process.
The result is that the site is blocked, which makes me feel as if my site is inaccessible. It looks like I need to set up a custom response page so that visitors don't get the wrong impression that the site is unstable.
We need to set up the responsive page here, the content is very concise and clear, completely following the example provided by the official website for display.
The above page has been created, but has not yet been bound to the 413 status code. Next, we will further refine the rules just mentioned. Please refer to the figure below:
When we revisit the effect, we can make it look more stable, and here we can embellish it a little to make sure that while it meets our needs, the appearance can also be more elegant, as shown in the following figure.
Up to now, all potential vulnerability attacks against file uploads have been effectively prevented, but the road is long, the practice needs to be persistent, and teenagers still need to make unremitting efforts.
summarize
With this article, we delve into multiple cases of file upload vulnerability attacks and preventive measures, as well as practical operations when building an attack range. From front-end and back-end checksum vulnerabilities to attacks that utilize Apache configuration file and file inclusion vulnerabilities, each step demonstrates the importance of security protection.
As we learn and practice, we focus not only on how to carry out the attack, but also on how to protect your own servers from such attacks. We used EdgeOne as an example solution to show how the protection rules it provides can be used to effectively defend against file upload vulnerabilities.
Whether it is the detailed operation during the range building process or the analysis of the attack cases, the implementation of security awareness and protection measures is crucial. Through this paper, it is hoped that readers will be able to understand and apply these security principles more deeply in order to protect their networks and servers from the threat of attacks.
On the road of network security, learning never ends. Let's work together to continuously improve our skills and safeguard the security and stability of the network environment.
I'm Rain, a Java server-side coder, studying the mysteries of AI technology. I love technical communication and sharing, and I am passionate about open source community. I am an excellent author of Nuggets, a content co-creator of Tencent Cloud, an expert blogger of Ali Cloud, and an expert of Huawei Cloud.
💡 I won't be shy about sharing my personal explorations and experiences on the path of technology, in the hope that I can bring some inspiration and help to your learning and growth.
🌟 Welcome to the effortless drizzle! 🌟