File upload vulnerability-upload range 3-4 (the most detailed interpretation on the entire network)

File upload vulnerability-upload shooting range 3-4 clearance notes (the most detailed interpretation on the entire network)

upload third level (special suffix)

image-20230829212826360

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
  1. isset(): Checks whether the variable is set and not null.
  2. file_exists(): Check whether the file or directory exists.
  3. trim(): Remove spaces at both ends of the string.
  4. $_FILES: A global variable containing uploaded file information.
  5. strrchr(): Returns the last occurrence of the specified character (or substring) in the string and all subsequent characters.
  6. strtolower(): Convert string to lowercase.
  7. str_ireplace(): Ignore the case of substrings in the replacement string.
  8. in_array(): Checks whether the given value exists in the array.
  9. move_uploaded_file(): Move the uploaded file to a new location.

The workflow of this source code is as follows:

  1. If the user sends a POST request through the form's "submit" button, the code will execute the file upload logic.
  2. First, check if the upload directory exists. If it exists, continue execution, otherwise an error message is returned.
  3. 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).
  4. 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.
  5. Use strrchrthe function to get the extension in the filename and convert it to lowercase.
  6. Use str_ireplacethe function to remove the string "::$DATA" from the file name.
  7. Use trimthe function to remove leading and trailing spaces from the file extension.
  8. 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.
  9. Get the temporary path of the uploaded file and generate a new file name based on the timestamp and a random number.
  10. Use move_uploaded_filethe function to move the temporary file to the specified upload directory and $is_uploadset the flag to true.
  11. If the file move fails, an error message is returned.
  12. 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, .php3used as a suffix for PHP scripts. Although less common now, some servers still support this suffix. (Starting from php5.3.0, .php3suffix parsing is disabled by default)

  • .php4: .php3Similar to , .php4it 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 .php3as, it is also disabled by default after php5.3.0 version)

  • .php5: .php5is 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: .phtmlfile 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)image-20230829223857179

As long as the suffix is ​​added after this field, it can parse the php file normally. For example, I added a .abcdsuffix here. After restarting the apache service, it can parse the php file normally.

image-20230829224155737

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.

image-20230829224817442

Upload a file with the suffix php and use burpsuite to capture the packets

image-20230829224911016

Send it to the Intruder module for blasting.

image-20230829225330735

In the Intruder module, we use the sniper mode and add the php suffix to a payload variable for brute force enumeration.

image-20230829225355160

This is the more commonly used PHP parsed name I collected, and I use it as the payload for enumeration.

image-20230829231939431

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.

image-20230829232702471

The path to find it from the response file is upload/202308291518502062.phtml.

image-20230829232802615

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
  • .htaccessfile 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.

  • .htaccessFiles 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.

  • .htaccessFiles 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.

    • .htaccessThe 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 .htaccessdo not have specific configuration rules, but the files in the website file directory have configuration rules, the configuration in the files .htaccessin the website file directory will be executed ..htaccess

Turn on and off the .htaccess configuration process

  1. Confirm that Apache has .htaccessoverrides enabled: In the main Apache configuration file (such as config httpd.conf), find <Directory>the section and make sure AllowOverridethe directive is set to All(or the corresponding override level) to allow .htaccessthe file's configuration rules to take effect.

  2. Create .htaccessa file: Create a new text file in the directory where you want to apply the configuration rules, and name it ( .htaccessnote that the file name starts .with , so there is no file name prefix in front of the file name).

  3. Edit .htaccessthe file: Open the file with a text editor .htaccessand 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.

  4. Save .htaccessfile: Save your changes and .htaccessupload the file to your website directory for it to take effect.

    image-20230829235456429

  5. Set AllowOverridethe directive Noneto disable files in this directory and its subdirectories .htaccess.

.htaccess configurable basic parameters

.htaccessFiles 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:

  1. URL rewriting rules: Use RewriteRulethe directive to define custom URL rewriting rules to convert complex URL paths into a more friendly and readable format.

    • Simple example:

      1. Simple path rewriting:
      RewriteEngine On
      RewriteRule ^about$ about-us.html [L]
      

      The above rule will /aboutredirect the to about-us.htmlpage, making it easier for visitors to access the About page.

      1. Overriding with parameters:
      RewriteEngine On
      RewriteRule ^products/([0-9]+)$ product.php?id=$1 [L]
      

      The above rules will /products/123rewrite URLs like product.php?id=123so that the backend can handle requests for specific products and the URLs are more friendly.

      1. 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-pageredirect requests from http://www.example.com/new-pageand return a permanently redirected status code 301. This can be used to keep old links available when updating your website.

  2. Access control: Use the Requireor Orderdirective to restrict access to specific directories, files, or IP addresses. Access control based on IP address, user authentication, etc. can be implemented.

    • Simple example:

      1. 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 ranges 10.0.0.0/24, access will be allowed. You can add/modify allowed or denied IP addresses or ranges as needed.

      1. 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 .htpasswdfiles. You can use htpasswdtools to create and manage this file.

      1. Access control by file type:
      <Files "sensitive-file.php">
          Order allow,deny
          Deny from all
      </Files>
      
  3. Custom error page: ErrorDocumentA custom error page can be defined via the directive to display a customized error message when a specific error occurs.

    • Simple example

      1. 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.

      1. 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.

  4. Compression and cache control: You can use mod_deflatethe and mod_expiresmodule's directives to enable and configure HTTP compression and cache control to improve website performance.

    • Simple example

      1. 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 AddOutputFilterByTypethe directive to compress files of the specified MIME type. You can add other MIME types as needed.

      1. 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>
      
  5. MIME type settings: Use the AddTypeand AddHandlerdirectives to associate specific MIME types and file extensions.

    • Simple example

      1. Set the MIME type of text files:
      AddType text/plain .txt
      AddType text/html .html .htm
      

      The above rules associate file extensions .txtto MIME types text/plainand file extensions .htmland .htmto MIME types text/html. This will tell the server how to handle these file types correctly.

      1. Set the MIME type of image files:
      AddType application/x-httpd-php .php
      

      The above rules associate file extensions .phpto MIME types application/x-httpd-php. This tells the server to use the PHP parser to handle .phpfiles with the extension.

      1. Set the handler for the script file:
      AddHandler php-script .php
      

      The above rules associate file extensions .phpto PHP handlers. .phpThis tells the server to use the PHP parser to process and execute scripts for files with extensions.

  6. Force HTTPS: Use the RewriteCondand RewriteRuledirectives to force HTTPS redirection of a website or specific page.

    • Simple example:

      1. 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).

      1. 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.htmlredirect pages containing in the URL. If the connection is non-HTTPS, redirect to the HTTPS version of the same page.

  7. Directory index: Use Optionsthe directive to control whether the list index is displayed in the website directory.

    • Simple example:

      1. 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.

      1. 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. .htaccessFiles have a wider range of functions and can customize and control almost every aspect of the Apache server. .htaccessFiles provide powerful configuration capabilities, allowing us to make various customizations to the Apache server. With proper usage and configuration .htaccessfiles, 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.

  1. Redirect attacks: Hackers can modify redirect rules to redirect legitimate users to malicious sites for phishing attacks or to distribute malware.
  2. Directory traversal attacks: Hackers can use .htaccessfiles to bypass server configuration, perform directory traversal attacks, and gain unauthorized access to files and directories.
  3. Authentication vulnerabilities: Hackers can modify authentication rules to bypass user authentication or weaken access controls to gain unauthorized access to restricted resources.
  4. 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.
  5. PHP parsing: hackers can modify the parsing suffix to execute malicious webshell Trojan files

Now that we know .htaccesshow powerful it is, let’s continue to try how to pass the fourth level. The fourth level allows .htaccessuploading without restrictions. We can create a new .htaccessfile .

image-20230830003115514

It means that .aaaafiles with the suffix can be parsed in the browser as php files.

image-20230830003217045

Uploading a .aaaawebshell Trojan with the suffix

image-20230830003306036

All have been uploaded successfully. Let's see .aaaaif the files with the suffix can be parsed normally.

image-20230830003400005

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.

Guess you like

Origin blog.csdn.net/weixin_44369049/article/details/132573361