Resource Center  >  Blog

SQL Injection in Java and how to easily prevent it

November 8, 2021
Admir Dizdar

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.

What Is Domain Hijacking?  Domain hijacking refers to the unauthorized acquisition of a domain name by a third party, effectively

See more

Modern day organizations face a constant barrage of cyber threats, making it imperative to implement robust vulnerability management processes. Vulnerability

See more

A vulnerability scanner is a specialized software tool designed to assess the security of computers, networks, or applications by automatically detecting and analyzing weaknesses. These scanners proactively search for security vulnerabilities, such as unpatched software, misconfigurations, and other security gaps that could be exploited by attackers. Some scanners can simulate the actions of an attacker to help identify exploitable vulnerabilities.

See more
Get Started
Read Bright Security reviews on G2