DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Binary Code Verification in Open Source World
  • How to Secure Apache Ignite From Scratch
  • How to Use Java to Build Single Sign-on
  • Buildpacks: An Open-Source Alternative to Chainguard

Trending

  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  1. DZone
  2. Coding
  3. Java
  4. Fixing Common Java Security Code Violations in Sonar

Fixing Common Java Security Code Violations in Sonar

By 
Patroklos Papapetrou user avatar
Patroklos Papapetrou
·
Sep. 26, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
26.7K Views

Join the DZone community and get the full member experience.

Join For Free
This article aims to show you how to quickly fix the most common java security code violations. It assumes that you are familiar with the concept of code rules and violations and how Sonar reports on them. However, if you haven’t heard these terms before then you might take a look at Sonar Concepts or the forthcoming book about Sonar for a more detailed explanation.

To get an idea, during Sonar analysis, your project is scanned by many tools to ensure that the source code conforms  with the rules you’ve created in your quality profile. Whenever a rule is violated… well a violation is raised. With Sonar you can track these violations with violations drilldown view or in the source code editor. There are hundreds of rules, categorized based on their importance. Ill try, in future posts, to cover as many as I can but for now let’s take a look at some common security rules / violations. There are two pairs of rules (all of them are ranked as critical in Sonar ) we are going to examine right now.

1. Array is Stored Directly ( PMD ) and Method returns internal array ( PMD )

These violations appear in the cases when an internal Array is stored or returned directly from a method. The following example illustrates a simple class that violates these rules.

public class CalendarYear {
 private String[] months;
 public String[] getMonths() {
    return months;    
 }
 public void setMonths(String[] months) {
    this.months = months;
 }
}

To eliminate them you have to clone the Array before storing / returning it as shown in the following class implementation, so noone can modify or get the original data of your class but only a copy of them.

public class CalendarYear {
 private String[] months;
 public String[] getMonths() {
    return months.clone();    
 }
 public void setMonths(String[] months) {
    this.months = months.clone();
 }
}

2. Nonconstant string passed to execute method on an SQL statement (findbugs) and A prepared statement is generated from a nonconstant String (findbugs)

Both rules are related to database access when using JDBC libraries. Generally there are two ways to execute an SQL Commants via JDBC connection : Statement and PreparedStatement. There is a lot of discussion about pros and cons but it’s out of the scope of this post. Let’s see how the first violation is raised based on the following source code snippet.

Statement stmt = conn.createStatement();
String sqlCommand = "Select * FROM customers WHERE name = '" + custName + "'";
stmt.execute(sqlCommand);

You’ve already noticed that the sqlcommand parameter passed to execute method is dynamically created during run-time which is not acceptable by this rule. Similar situations causes the second violation.

String sqlCommand = "insert into customers (id, name)  values (?, ?)";
Statement stmt = conn.prepareStatement(sqlCommand);

You can overcome this problems with three different ways. You can either use StringBuilder or String.format method to create the values of the string variables. If applicable you can define the SQL Commands as Constant in class declaration, but it’s only for the case where the SQL command is not required to be changed in runtime. Let’s re-write the first code snippet using StringBuilder

Statement stmt = conn.createStatement();
stmt.execute(new StringBuilder("Select FROM customers WHERE name = '").
                         append(custName).
                         append("'").toString());

and using String.format

Statement stmt = conn.createStatement();
String sqlCommand = String.format("Select * from customers where name = '%s'", custName);
stmt.execute(sqlCommand);

For the second example you can just declare the sqlCommand as following

private static final SQLCOMMAND = insert into customers (id, name)  values (?, ?)";

There are more security rules such as the blocker Hardcoded constant database password but I assume that nobody is still hardcodes passwords in source code files…

In following articles I’m going to show you how to adhere to performance and bad practice rules. Until then I’m waiting for your comments or suggestions.

code style security Java (programming language)

Published at DZone with permission of Patroklos Papapetrou, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Binary Code Verification in Open Source World
  • How to Secure Apache Ignite From Scratch
  • How to Use Java to Build Single Sign-on
  • Buildpacks: An Open-Source Alternative to Chainguard

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!