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

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

Table of Content

  1. What is Code Injection?
  2. Code Injection in Real Life
  3. Code Injection Examples in Programming Languages
  4. How to Prevent Code Injection
  5. Conclusion

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!

SQL Injection in MongoDB: Examples and Prevention

Table of Content

  1. What is MongoDB?
  2. SQL Injection in Web Apps
  3. SQL Injection in MongoDB
  4. How to prevent MongoDB vulnerabilities
  5. Conclusion

What is MongoDB?

As web development evolves, we are  seeing more and more NoSQL databases being used due to the simplicity of creating, managing and storing data in these databases.

MongoDB is perhaps the most popular database, owing to its scalability, unlike some other NoSQL databases. However this comes at a price given MongoDB’s susceptibility to SQL injection attacks.

SQL Injection in Web Apps

SQL injection occurs when an attacker sends a malicious request through SQL queries to the database. The database recognizes the malicious query as if it’s any other, and returns the information that the attacker requested. This creates a vulnerability that can destroy your system from within. A typical example of SQL Injection looks something like this:

SELECT * FROM ITEMS WHERE ID=’

One would think that having a NoSQL database prevents any sort of SQL Injection. However, that’s not the case. 

Just like any other database, MongoDB uses commands to fetch and display data on the web application. 

SQL Injection in MongoDB

As we acknowledged earlier, MongoDB is vulnerable to SQL injection attacks. Even though it’s a NoSQL database. 

In combination with Node.js, MongoDB is a powerful tool. You can easily send requests with API queries. A typical example of a MongoDB request would look something like this:

Products.find({ price: { $gte: 10 } }, callback);

In the example above, we’ve used the find function to fetch the Products collection, Passing  the property price and a condition that the price is greater than 10 ($gte : 10). 

These requests are a big security concern for one main reason – the attacker is able to send an object to the query instead of an expected string or an integer, which could lead to considerable data leakage. In fact, there was a big scandal in 2018  when an attacker stole the data of 11 million users from Yahoo. Yahoo used MongoDB databases at the time, resulting in drastic changes to their approach afterwards. 

Additionally, MongoDB uses Binary JSON (BSON) data format and because the queries are actually BSON objects, a direct injection is impossible. However, an attacker can take advantage of the $where function that uses JavaScript. So, for example:

db.collection.find({ $where: function() {

return (this.product == “Milk”)

}});

This simple query would do exactly as expected – return a product name named ‘Milk’. However, with improper input sanitisation, an attacker can take advantage of this. The malicious code would be as follows:

db.collection.find({ $where: function() {

return (this.product == $productData)

}});

The example above could be used as a test for the attacker to see if the database returns valid results. If  it does, the possibilities are endless. So, the attacker could, for example, send a malicious code within the object. A good example would be:

db.collection.find({ $where: function() {

return (this.product == ‘m’; sleep (10000))

}});

If the server paused for five seconds after sending this command, it’s a confirmation for the attacker that he has the direct access and that he can perform an injection.

How to prevent MongoDB vulnerabilities

The first step to preventing SQL Injection with MongoDB is sanitizing the input. Although this may appear as  simple advice, many web applications using NoSQL products are quite new and perhaps undergoing comprehensive development, leaving room for mistakes. . Unvalidated input often leads to DDoS attacks or the attacker taking over the server, so you ought to be extremely careful with this. 

MongoDB has a series of built-in features for secure query building without JavaScript. However if the use of JavaScript in queries is required, ensure that best practices are followed, including validating and encoding all user inputs, applying the rule of least privilege, and avoiding the use of vulnerable constructs.

Conclusion

Rather counterintuitively NoSQL doesn’t mean that there’s no risk of injection. As we’ve seen in the examples above, JavaScript applications using MongoDB are very sensitive to injections that could lead to some serious vulnerabilities such as DDoS attacks. 

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

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

Scan your applications and prevent NoSQL injection vulnerabilities – try Bright by signing up for a FREE account

Directory Traversal Attack: Real-life Attacks and Code Examples

Table of Content

  1. What is a Directory Traversal attack?
  2. How does a Directory Traversal attack work?
  3. The impact of a Directory Traversal attack
  4. Examples of Directory Traversal attacks
  5. Detecting Directory Traversal Vulnerabilities
  6. Preventing Directory Traversal Attacks
  7. Check if your website is vulnerable with Bright

What is a Directory Traversal attack?

To run a secure web server, it is crucial to control access to the web content. A directory traversal attack (or file path traversal attack) allows attackers to read random files on the server that is running a web application. These files may include the application’s source code and data, credentials for backend systems, or sensitive OS files. The attacker might even be able to write to arbitrary files on the server, allowing them to modify the application’s data or behavior, or to even take full control of the server.

There are two main levels of security mechanisms web servers provide:

  • Access Control Lists (ACLs)
  • Root directory

Access control lists are used during the authorization process. A web administrator creates these lists to specify which users or user groups are able to access, modify or execute particular files on the server, as well as other access rights.

This is part of a series of articles about Security misconfiguration.

The root directory is a specific directory on the server’s file system and limits users from accessing anything above this root. The root directory limits users from accessing any files they are not meant to see or modify.

A directory traversal attack can be the result of a directory traversal vulnerability in the webserver software itself or in the application’s source code.

All an attacker needs to perform a directory traversal attack is a web browser and some knowledge on where to find any default files and directories on the system.

How does a Directory Traversal attack work?

If there are vulnerabilities in the web application’s code or the server’s configuration, it’s easy to execute a directory traversal attack. For example, let’s examine this PHP code snippet that is prone to directory traversal attacks:

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

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

In this case, attackers can use the command https://example-website.com/?file=../../../../etc/passwd and manipulate the web application to reveal hidden information of the /etc/passwd system file. 

Similar to our example, attackers can use directory traversal vulnerabilities to access credentials, modify files, or take control of the compromised web server.

The impact of a Directory Traversal attack

An attacker can leverage a directory traversal vulnerability in the system to step out of the root directory, allowing them to access other parts of the file system to view restricted files and gather more information required to further compromise the system.

Examples of Directory Traversal attacks

Real-life directory traversal attack examples

Back in September 2019, researchers discovered a “critical severity” directory traversal vulnerability in Atlassian’s Jira Service Desk Server and Jira Service Desk Data Center that allowed attackers to access information belonging to the company’s customers.

Atlassian wasn’t the only company to make news with such a vulnerability. In late September 2019, Adobe released a fix for three vulnerabilities in its ColdFusion platform, including a “critical” directory traversal vulnerability that could allow attackers to bypass access controls.

Another directory traversal disclosure took place in June 2019 and involved Kubecti. Kubecti is a command-line interface (CLI) for controlling Kubernetes clusters. The flaw was found in the cp command, which allows users to copy files from the Kubernetes pod to their local machine. The bug allowed malicious users to copy relative file paths and potentially use this to execute code or elevate privileges.

The target of a directory traversal attack doesn’t have to be a web application. Researchers found that 12 out of 13 routers and NAS devices from different manufacturers had security flaws that allowed remote-level access, and seven of those had directory traversal vulnerabilities.

Example of a directory traversal attack via web application code

Web applications that utilize dynamic pages receive input from the browser using GET or POST requests. Here is an example of an HTTP GET request URL:

GET http://example-shop.com/show.asp?view=oldarchive.html HTTP/1.1
Host: example-shop.com

Using this URL, the browser requests the dynamic page show.asp and sends a parameter with the value of oldarchive.html. Once the request is executed, show.asp retrieves the file oldarchive.html from the server, renders it, and sends it back to the browser which displays it to the user.

Now, if an attacker assumes that show.asp can retrieve files from the filesystem, he could send a custom URL, like this one:

GET http://example-shop.com/show.asp?view=../../../../../Windows/system.ini HTTP/1.1
Host: example.shop.com

The dynamic page would retrieve the file system.ini from the filesystem and display it to the user. The directive ../ shown in the URL above would tell the system to go one level up in the directory tree. The attacker would have to guess how many directories they have to go up to find the Windows folder, easily done with persistence and trial-and-error.

Example of a directory traversal attack via webserver

Directory traversal vulnerabilities are not limited to the code; the web server itself can be vulnerable to directory traversal attacks.

Vendors fixed directory traversal vulnerabilities in the latest versions of web server software, but there are servers online which still run older versions and may still be vulnerable to directory traversal attacks. Even running the latest version of the software won’t always help if some sensitive default script directories are exposed. 

Below is an example of a URL request which uses the IIS scripts directory to traverse directories and execute a command:

GET
http://example-server.com/scripts/..%5c../Windows/System32/cmd.exe?c+dir’c: HTTP/1.1
Host: example-server.com

The above-shown request would return a list of all files in the C: directory to the attacker. First, the request would execute the cmd.exe command shell file and then run the command dir c: in the shell. The %5c expression shown in the example represents a server escape code used to represent normal characters, in this case, the character .

Escape codes shouldn’t present a problem for newer versions of web server software, but some older versions don’t filter out these codes in the root directory enforcer and will let the attackers execute such commands.

Related content: Read our guide to misconfiguration attacks.

Detecting Directory Traversal Vulnerabilities

You should detect directory traversal vulnerabilities as early as possible. A best practice is to check the code while it’s being written, or before the software is deployed, using code analysis tools.

But code analysis tools typically miss about half of all vulnerabilities and come with a high rate of false positives. This makes the process of remediating directory traversal vulnerabilities lengthy and expensive.

Web vulnerability scanners (like Dynamic Application Security Testing scanners, or DAST) do a great job at detecting directory traversal vulnerabilities,l automatically crawling the website, and testing for vulnerabilities. They typically come with less false positives, or in the case of Bright, without any false positives at all. After the application is deployed you can opt for penetration testing, but this process is time-consuming. An alternative is to use fuzzing to experiment with different inputs and trying to cause problems with malformed data. 

Preventing Directory Traversal Attacks

To prevent directory traversal vulnerabilities, try to avoid passing user-supplied input to the filesystem APIs. Many of the functions that do that can be rewritten to deliver the same behavior, without exposing you to security risks.

If for any reason you can’t avoid passing user-supplied input, you should use two layers of defense:

  • Make the application validate the user input before processing it. Either compare the input against a whitelist of permitted values or verify that the input contains only permitted content – for example, alphanumeric characters
  • After validating the user-supplied input, make the application verify that the canonicalized path starts with the expected base directory.

Below is a simple Java code snippet that can be used to validate the canonical path of a file based on user input:

File file = new File (BASE_DIRECTORY, userInput);
if (file.getCanonicalPath().startsWith (BASE_DIRECTORY)) {
// process file
}

Check if your website is vulnerable with Bright

Bright automatically scans your web applications for directory traversal and other security vulnerabilities. Bright is false-positive free and easy to use for developers, so the remediation process will be less time-consuming without the need for manual validation.

The created reports come with clear remediation guidelines for your team, and the integration with ticketing tools like Jira makes it easy to assign findings to team members.
Register for a free account and start testing for directory traversal and hundreds of other vulnerabilities today – Try Bright today