Threats and Vulnerabilities

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.

SQL Injection in Java and how to easily prevent it
Admir Dizdar
November 8, 2021
5 minutes

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 Our Customers Say About Us

"Empowering our developers with Bright Security's DAST has been pivotal at SentinelOne. It's not just about protecting systems; it's about instilling a culture where security is an integral part of development, driving innovation and efficiency."

Kunal Bhattacharya | Head of Application Security

"Bright DAST has transformed how we approach AST at SXI, Inc. Its seamless CI/CD
integration, advanced scanning, and actionable insights empower us to catch
vulnerabilities early, saving time and costs. It's a game-changer for organizations aiming to
enhance their security posture and reduce remediation costs."

Carlo M. Camerino | Chief Technology Officer

"Bright Security has helped us shift left by automating AppSec scans and regression testing early in development while also fostering better collaboration between R&D teams and raising overall security posture and awareness. Their support has been consistently fast and helpful."

Amit Blum | Security team lead

"Bright Security enabled us to significantly improve our application security coverage and remediate vulnerabilities much faster. Bright Security has reduced the amount of wall clock hours AND man hours we used to spend doing preliminary scans on applications by about 70%."

Alex Brown

"Duis aute irure dolor in reprehenderit in voluptate velit esse."

Bobby Kuzma | ProCircular

"Since implementing Bright's DAST scanner, we have markedly improved the efficiency of our runtime scanning. Despite increasing the cadence of application testing, we've noticed no impact to application stability using the tool. Additionally, the level of customer support has been second to none. They have been committed to ensuring our experience with the product has been valuable and have diligently worked with us to resolve any issues and questions."

AppSec Leader | Prominent Midwestern Bank

Book a Demo

See how Bright validates real risk inside your CI/CD pipeline and eliminates false positives before they reach developers.

Our clients:
SulAmerica Barracuda SentinelOne MetLife Nielsen Heritage Bank Versant Health