Most Common Vulnerabilities in Java and How to Fix

It’s easy to think that our code is secure. Most Common Vulnerabilities in Java or potential exploits are often the things we think about last. Most of the time, our thoughts are preoccupied with sprints, scrums, meeting notes, and whatever the latest pivots marketing got approved are.

In a world where development speed takes precedence over code security, this can be a genuine issue. A breach or a hack can cost a business big dollars, if not kill it altogether. According to IBM’s 2020 Cost of Data Breach Report, the average total cost of a breach sits at 3.86 million US dollars.

The worst part of this is that it takes an average of 280 days to identify and contain the breach. Data is digital gold, and your code is the vessel that holds it.

While Java is considered relatively safe because it is a server-side language, there are still multiple ways to attack and access things you want to remain private.

Top Most Common Vulnerabilities in Java

To help you get a head start on the exploits your code may develop, we will list the top 10 Most Common Vulnerabilities in Java, and how you can prevent them.

XML External Entity Attacks

XML external entity attacks, or XXE, are when attackers exploit an XML parser to read arbitrary files on your server. Using an XXE, attackers might also be able to retrieve user information, configuration files, or other sensitive information like AWS credentials.

Java applications are particularly prone to XXE because most Java XML parsers have the requirements for XXE enabled by default. To prevent XXE attacks in a Java application, you need to explicitly disable these functionalities. You can read in detail about how to prevent XXE here.

When I do scan using fortify tool, I got some issues under "XML External Entity Injection".

TransformerFactory trfactory = TransformerFactory.newInstance();

This is the place where it is showing error. I have given the below fix as suggested by fortify

The safest way to prevent XXE is always to disable DTDs (External Entities) completely. Depending on the parser, the method should be similar to the following:

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

Connection String Injection

Connection strings are a set of definitions that will use to connect an application to a data source. It may connect to your relational databases, LDAP directories, and files.

For a database connection string injection, there are four parameters that a malicious user would need: the data source, the initial catalog, the user id, and the password.

Connection string attacks happen when a bad actor gains access by injecting parameters into the connection strings using semicolons as separators.

The issue here is that some database providers have no limit cap and run on a ‘last one wins’ algorithm. This means that an attacker can run multiple connection injection strings, pollute them with duplicate parameters and the database will accept the valid combination. 

As a result, the attacker ends up bypassing the normal authentication process without getting locked out.

For example, an injected connection string can look something like this:

Data Source = myDataSource; Initial Catalog = db; Integrated Security = no; User ID = myUsername; Password = XXX; Intergrated Security = true; Data Source = myDataSource; Initial Catalog = db; Integrated Security = no; User ID = myUsername; Password = XXX; Intergrated Security = no;

Once in, the malicious user can hijack the credentials and modify them to whatever they want.

Remote Code Execution

Remote code execution vulnerabilities, or RCE, are a class of vulnerabilities that happen when attackers can execute their code on your machine. One of the ways this can happen is through command injection vulnerabilities. They are a type of remote code execution that happens when the user inputs will concatenate directly into a system command. The application cannot distinguish between where the user input is and where the system command is, so the application executes the user input as code. The attacker will be able to execute arbitrary commands on the machine.

One of the easiest ways to prevent command injection is to implement robust input validation in the form of an allowlist. Read about how to implement allowlists to prevent RCE here.

Injection

Command injection is also a type of Common Vulnerabilities in Java. Injection happens when an application cannot properly distinguish between untrusted user data and code. When injection happens in system OS commands, it leads to command injection. But injection vulnerabilities manifest in other ways too.

SQL Injection

In an SQL injection attack, for example, the attacker injects data to manipulate SQL commands. When the application does not validate user input properly, attackers can insert characters special to the SQL language to mess with the query’s logic, thereby executing arbitrary SQL code. Learn more about how these SQL injection attacks work here.

SQL injections allow attacker code to change the structure of your application’s SQL queries to steal data, modify data, or potentially execute arbitrary commands in the underlying operating system. The best way to prevent SQL injections will use parameterize statements, which makes SQL injection virtually impossible. Learn about how to use parameterized statements in Java in this article.

String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");

// FIXME: do your own validation to detect attacks
String query = "SELECT id, firstname, lastname FROM authors WHERE firstname = ? and lastname = ?";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, firstname );
pstmt.setString( 2, lastname );
try
{
    ResultSet results = pstmt.execute( );
}

NoSQL Injection

Databases don’t always use SQL. NoSQL databases, or Not Only SQL databases, are those that don’t use the SQL language. This injection refers to attacks that inject data into the logic of these database languages. NoSQL injections can be just as serious as SQL injections: they can lead to authentication bypass and remote code execution.

Modern NoSQL databases, such as MongoDB, Couchbase, Cassandra, and HBase, are all vulnerable to injection attacks. NoSQL query syntax is database-specific, and queries are often written in the programming language of the application. For the same reason, methods of preventing NoSQL injection in each database are also database-specific. You can learn how to prevent NoSQL injection in MongoDB, Couchbase, Cassandra, and HBase here.

LDAP Injection

The Lightweight Directory Access Protocol (LDAP) is a way of querying a directory service about the system’s users and devices. For instance, it will use to query Microsoft’s Active Directory. When an application uses untrusted input in LDAP queries, attackers will submit craft inputs that cause malicious effects. Using LDAP injection, attackers can bypass authentication and mess with the data stored in the directory. You can use parameterized queries to prevent LDAP injection. Find out how LDAP injections work and how to prevent them.

• Take the following vulnerable JavaScript code that directly assembles a simple LDA 
  filter from user inputs stored in the variables enteredUser and enteredPwd:

• filterContent = "(&(userID=" + enteredUser + ")(password=" + 
enteredPwd + "))"

For non-malicious users, the resulting filter should be something like:

(&(userID=johndoe)(password=johnspwd))

If this query is true, the user and password combination exists in the directory, so the user is logged in. However, an attacker can enter LDAP filter code as the user ID (shown in red) to create a filter that is always true, for example:

(&(userID=*)(userID=*))(|(userID=*)(password=anything))

This can allow the attacker to gain access without a valid user name or password.

Log Injection

You probably conduct system logging to monitor for malicious activities going on in your network. But will you ever consider that your log file entries could be lying to you? Log files, like other system files, will be tamper with malicious actors. Attackers often modify log files to cover up their tracks during an attack. Log injection is one of the ways attackers can change your log files. It happens when the attacker tricks the application into writing fake entries in your log files.

log injection is Common Vulnerabilities in Java often happens when the application does not sanitize newline characters “\n” in input written to logs. Attackers can make use of the new line character to insert new entries into application logs. Another way attackers can exploit user input in logs is that they can inject malicious HTML into log entries to attempt to trigger an XSS on the browser of the admin who views the logs.

To prevent log injection attacks, you need a way to distinguish between real log entries, and fake log entries injected by the attacker. One way to do this is by prefixing each log entry with extra meta-data like a timestamp, process ID, and hostname. You will also treat the contents of log files as untrusted input and validate it before accessing or operating on it.

Mail Injection

Many web applications send emails to users based on their actions. For instance, if you subscribe to a feed on a news outlet, the website might send you a confirmation with the name of the feed.

Mail injection happens when the application employs user input to determine which addresses to send emails to. This can allow spammers to use your server to send bulk emails to users or enable scammers to conduct social engineering campaigns via your email address. Learn how attackers can achieve mail injection and how you can prevent it here.

Template Injection

Template engines are a type of software that will use to determine the appearance of a web page. These web templates, written in template languages such as Jinja, provide developers with a way to specify how a page will render by combining application data with web templates. Together, web templates and template engines allow developers to separate server-side application logic from client-side presentation code during web development.

Template injection refers to injection into web templates. Depending on the permissions of the compromised application, attackers might be able to use the template injection vulnerability to read sensitive files, execute code, or escalate their privileges on the system.

 

Expression Language Injection

Expression Language (EL) refers to program expressions written into Java Server Pages (JSP) that are executed as code. When untrusted user input will pass into these expressions, attackers might be able to insert malicious code which is then executed by the expression language interpreter. This leads to remote code execution. Learn about how this attack works here.

To prevent EL injection, you will avoid passing untrusted user input into expressions evaluated by the EL interpreter. If you do need to pass data into EL expressions, validate the data using an allowlist or encode the data to make sure that it is not interpreted as code.

Second-Order SQL Injection

Second-order SQL injection is a two-step process. First, the attacker adds something to your application but doesn’t immediately execute it. They might be waiting for more data or waiting for a trigger activity.

This is where second-order SQL injection differs from normal SQL injections.

The attacker injects code into the table row, which is deemed as a trusted source. That table row is then called, causing the attack to move from its dormant state to active execution.

Testing for second-order SQL is harder because of its often covert nature.

For example, the malicious user signs up with the username ‘ or ‘hacker’=’hacker

This means that ‘ or ‘hacker’=’hacker gets stored in the database. The database may use the following query to verify a user’s identity:

SELECT * from creditcards WHERE username = '<usernamehere>';

So when the username is ‘ or ‘hacker’=’hacker, the final query looks something like this:

SELECT * from creditcards WHERE username = '' or 'hacker'='hacker';

Then when you go to log in, the user name completes the validation query, giving access to other users and their account details.

XPath Injection

Another one of the common vulnerabilities in Java XPATH is a query language for XML documents. Think SQL for XML. XPATH will use to query and perform operations on data stored in XML documents. For example, XPATH can use to retrieve the salary information of employees stored in an XML document. It can also use to perform numeric operations or comparisons on that data.

XPATH injection is an attack that injects into XPATH expressions to alter the outcome of the query. Like SQL injection, it can use to bypass business logic, escalate user privilege, and leak sensitive data. Since applications often use XML to communicate sensitive data across systems and web services. These are the places that are the most vulnerable to XPATH injections. Similar to SQL injection, you can prevent XPath injection by using parameterized queries.

Header Injection

Header injection happens when HTTP response headers are dynamically constructed from untrusted input. Depending on which response header the vulnerability affects, header injection can lead to cross-site scripting, open redirect, and session fixation.

For instance, if the Location header can control by a URL parameter, attackers can cause an open redirect by specifying their malicious site in the parameter. Attackers might even be able to execute malicious scripts on the victim’s browser, or force victims to download malware by sending completely controlled HTTP responses to the victim via header injection. More about how these attacks work here.

You can prevent header injections by avoiding writing user input into response headers, stripping new-line characters from user input (newline characters will use to create new HTTP response headers), and using an allowlist to validate header values.

Why Offensive360

To fix the above most Common Vulnerabilities in Java, you will need to identify which of these technologies are used in your environment and visit the respective vendor/project's website for update/patch information. Offensive360 can find all of these items automatically with a few mouse clicks. Furthermore, our editable Java vulnerability policy can grow to accommodate any custom checks for additional Java tooling.

Discover more from O360

Subscribe now to keep reading and get access to the full archive.

Continue reading