Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT

Java IoT: Article

Strategies for Securing Java Code

Anticipate and protect every possible security vulnerability

Java security is an overwhelming issue. For a truly secure application, you need to prevent hackers from entering the system, and you need to ensure that code safeguards security if a hacker does break in. Moreover, there is no room for error. If you anticipate and prevent hundreds of security vulnerabilities but overlook just one, a hacker can still wreak havoc on your system.

This article introduces some fundamental strategies for writing Java code that remains secure if a hacker manages to enter the system. Essentially, writing secure code requires a shift in thinking. Instead of worrying about whether code works correctly, you need to anticipate all of the ways that it can be exploited, then ensure that security is maintained in every possible worst case scenario. This, of course, is a monumental task, and there is no silver bullet for security. Several strategies for developing Java code that resists many common attacks are:

  • Follow coding guidelines for preventing security attacks
  • Code defensively to prevent hackers from propagating through the code
  • Expose and correct as many bugs as possible
Follow Coding Guidelines to Prevent Security Attacks
Ensuring that your code complies with the following coding rules can make your code less vulnerable to security attacks.

Rule 1: Avoid using inner classes
Java bytecode has no concept of inner classes, so the compiler translates inner classes into ordinary classes that are accessible to any code in the same package. An inner class gets access to the fields of the enclosing outer class - even if these fields are declared private - and the inner class is translated into a separate class. To let this separate class access the fields of the outer class, the compiler silently changes these fields' scope from private to package. As a result, when you use inner classes, not only is the inner class exposed, but the compiler is silently overruling your decision to make some fields private.

Note: If you really need to use inner classes, be sure to make all inner classes private.

Here is sample code that violates this rule:

package examples.rules.security;

public class AUIC {

    private class AUIC2 {  // VIOLATION

To correct this code, make the class AUIC2 a top-level class as follows:

public class AUICF {


class AUIC2 {  // FIXED


Rule 2: Avoid comparing class objects by name
This rule prohibits comparing class objects with the getName() method. More than one class in a running JVM may have the same name. As a result, a hacker can create a class with malicious code and give it the same name as your class. When you compare classes by name, the comparison would not recognize this difference. When you compare classes by object equality, the difference would be detected.

Here is sample code that violates this rule:

package examples.rules.security;

public class CMP {
    public boolean sameClass (Object o) {
        Class thisClass = this.getClass();
        Class otherClass = o.getClass();
        return (thisClass.getName() == otherClass.getName());  //VIOLATION

To correct this code, modify it as follows to directly compare thisClass and otherClass for equality:

package examples.rules.security;
public class CMP {
    public boolean sameClass (Object o) {
        Class thisClass = this.getClass();
        Class otherClass = o.getClass();
        return (thisClass == otherClass);  // FIXED

Rule 3: Make your classes noncloneable
This rule requires that you make classes nonclone-able by defining a final method clone that will throw a java.lang.CloneNotSupportedException(). For example:

public final Object clone() throws java.lang.CloneNotSupportedException {
throw new java.lang.CloneNotSupportedException();

Java's object cloning mechanism can allow an attacker to manufacture new instances of classes that you define, without executing any of the class's constructors. Even if your class is not cloneable, the attacker can define a subclass of your class, make the subclass implement java.lang.Cloneable, then create new instances of your class by copying the memory images of existing objects. By defining the above clone method, you'll prevent such attacks.

Note: If you really need to make your classes cloneable, be sure to make your clone() method final.

Rule 4: Make your classes nonserializable
This rule requires that if you want to prevent access to the internal state of your objects, make your class nonserializable. If you don't, your objects can be serialized into readable byte arrays. As a result, hackers can view the objects' full internal state, including private fields and the internal states of referenced objects.

To make a class nonserializable, define the final method writeObject() that throws an IOException. For example:

private final void writeObject (ObjectInputStream in)
|| throws java.io.IOException {
throw new java.io.IOException ("Class cannot be serialized");

This method is declared final so that a subclass defined by a hacker adversary cannot override it.

Note: If you need to make a class serializable, follow these tips to safeguard security:

  • Use the Transient keyword for fields that contain direct handles to system resources and other sensitive information.
  • Do not pass an internal array to any DataInput/DataOutput method that takes an array when defining your own serializing method for a class.
The source for these tips is "Secure Programming for Linux and Unix HOWTO" by David Wheeler (www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/java.html).

Rule 5: Do not depend on package scope
This rule prohibits classes with public or package-private access. An attacker can simply add another class to your package and then access package-private fields that were supposed to be hidden.

To correct violations of this rule, modify code so that it does not rely on package-level access. Give your classes, methods, and fields the most restricted access possible. If this is not an option, you might want to use package sealing, which can prevent hackers from adding classes to a package that is in a "sealed" JAR file. Package sealing is discussed at http://java.sun.com/j2se/1.3/docs/guide/extensions/spec.html#sealing.

Rule 6: Avoid returning references to mutable objects and, if necessary, clone the mutable object before returning a reference to it
Mutable objects are objects whose states can be changed. When you return a reference to a mutable object, the caller can change the state of that object; if that object is used in the class later on, it will be using a different state of the object, which would affect the internals of the class.

Note that arrays are mutable (even if array contents are not mutable), so don't return a reference to an internal array with sensitive data.

Here is sample code that violates this rule:

         // fDate is a Date Field.

         // The caller of this method can change the Date object and
         // affect the internals of this class.
         public Date getDate() {
             return fDate;

To correct this code, modify it to return a defensive copy of the field as follows:

public Date getDate() {
    return new Date(fDate.getTime());

Now, the caller of this method can change the returned Date object without affecting the internals of this class.

Rule 7: Make methods, fields, and classes private; if there's a reason one should not be private, document that reason
If a class, method, or variable is not private, hackers could use it as a potential entry point. If there is a good reason why a method, field, or class should not be private, it does not need to be private, but that reason should be clearly documented.

Rule 8: Make all classes and methods final; if there is a reason one should not be final, document that reason
If a class or method is not final, hackers could try to extend it in an unsafe way. If there is a good reason why a method or class should not be final, it does not need to be final, but that reason should be clearly documented.

Coding Defensively to Prevent Hackers from Moving Through the Code
Another way to boost code security is to code defensively by implementing defensive software firewalls and validating user/external inputs.

Defensive software firewalls have many uses, one of which is to ensure that any hacker who manages to access your code cannot move through critical code sections. A defensive software firewall is a point in the logical flow of a program where the validity of logical constraints is checked. If a constraint specified in a firewall is satisfied, execution proceeds. If the constraint is violated, the firewall triggers, generates an appropriate error message, and possibly takes damage-control actions (such as stopping execution) or diagnostic actions (such as turning on debugging information). Firewalls should not alter the execution flow of a program unless they are triggered, and they should have either no effect or a negligible effect on the performance of the production version.

Note that these firewalls are not related to the firewalls placed around Internet connections. The concept discussed here relates solely to code construction. If designed carefully, these firewalls serve the same purpose as physical firewalls: they can contain a dangerous event and prevent it from causing a complete disaster.

In Java, firewalls can be implemented by adding assertions that say that if the program reaches a critical point without executing the expected operations, the program should throw exceptions, shut down, or perform another defensive action. Hackers often access code from a path that you didn't know existed or did not expect to be taken. By using firewalls to check whether critical program points were reached in unexpected ways, you can identify many attempted security breaches and stop hackers from entering and manipulating your most critical code.

To implement these firewalls with assertions, first determine the critical points in your code, then add assertions so that when each critical point is reached, the call stack is checked to verify that the program reached that critical point by executing the expected sequence of operations. When a critical point is reached through an unexpected sequence of operations, the program should throw an exception and terminate. Once this firewall is implemented, you will have a barrier that prevents hackers from using "backdoor paths" to gain entry into your most critical code.

For example, the code in Listing 1 could be added to verify the call stack before modifying a field in the database. In this case, the assertTrue method is assumed to accept an error message and a boolean. If the boolean is false, the message with an exception will be reported and the program will terminate.

Another defensive coding strategy is to validate all user/external input. When security is an issue, you should always worry about external inputs. If users manage to submit the "right" inputs, they could gain access to program details you hoped to keep private, prompt the application to crash or enter an unstable state, or access and modify the database. These inputs could be created by hackers trying to design inputs that cause a security breach (for example, by applying a technique known as SQL injection, where hackers submit inputs designed to create a strategic SQL string, such as a string that disables password checking, a string that adds a new account, etc.). Moreover, these inputs could also be submitted by well-meaning users who entered information incorrectly (as a result of a typo or a copy/paste error) or who simply misunderstood what type or format of information they were supposed to add.

By validating all external inputs, you can identify improper or malicious inputs as they are submitted and then prevent the program from using those inputs. The performance impact and user inconvenience will be minimal, especially if you consider the potential impact and inconvenience of having the application unavailable or functioning incorrectly because a hacker designed and successfully submitted the "perfect" input.

User input validation could be performed with assertions, Design by Contract, or if statements. For example, say you have the following method that accepts a filename as input from a user, but does not verify whether the filename represents a valid file.

void method (String filename) {
System.exec("more " + filename);

If the user passes filename = "joe; /bin/rm -rf /*", the execution of that method could delete files. If the application runs as a regular user, the spawned process (rm -rf) inherits its privileges, which means that the user can remove only the files for which he or she has modify permissions. If the application runs as root, the spawned process will inherit root privileges and all files on the hard drive can be removed.

To prevent hackers from performing such disastrous deletions, this method should verify whether the entered filename represents a valid file. This verification could be implemented as a simple check using an if statement as follows:

void method (String filename){
if (new File(filename).exists()){
System.exec("more " + filename);

Expose and Correct as Many Bugs as Possible
Every bug that you are not aware of could present hackers with an opportunity to exploit your system. Each bug represents unexpected program behavior; if the program is not behaving as you expect, how can you rest assured that it is not providing hackers with a way to manipulate your code?

Java code that throws unexpected, uncaught runtime exceptions is especially ripe for security breaches. Imagine that when one of your methods receives an input that you did not expect, it throws an uncaught runtime exception that's thrown up several layers in your call stack before it's handled, and the handling code exposes some critical Java code. If a hacker can produce this exception (for example, by flooding that method with a wide variety and range of inputs), he or she can then learn about the critical code.

The best way to expose these types of problems is to perform what is known as "white-box testing" or "construction testing." This testing involves designing inputs that thoroughly exercise a class's public methods, then examines how the code handles the test inputs.

For example, if you wanted to check whether uncaught runtime exceptions could cause a class to expose critical code in methods you think are protected, you would flood the class's exposed methods with a wide variety of inputs to try to flush out all possible exceptions, examine how the class responds to each exception, and modify the code so that it does not throw dangerous exceptions.

If you find errors during the testing phase, you have the opportunity to fix the problem before an actual security breach occurs. In fact, this type of testing is best performed at the unit level because testing each unit (each class) in isolation is the best way to expose the maximum number of errors. Because unit testing brings you much closer to the errors, it helps you detect errors that application-level testing does not always find. Take a closer look at Figures 1 and 2 to see how unit testing does this.

Figure 1 shows a model of testing an application containing many units. The application is represented by the large oval, and the units it contains are represented by the smaller ovals; external arrows indicate inputs; starred regions show potential errors.

To find errors in this model, you modify inputs so that interactions between units force some units to hit the potential errors. This is incredibly difficult. Imagine standing at a pool table with a set of billiard balls in a triangle at the middle of the table, and having to use a cue ball to move the triangle's center ball into a particular pocket - with one stroke. This is how difficult it can be to design an input that finds an error within an application. As a result, if you rely only on application testing, you might never reach many of your application's units, let alone uncover the errors they contain.

As Figure 2 illustrates, testing at the unit level offers a more effective way to find errors. When you test one unit apart from all other units, reaching potential errors is much easier because you are much closer to those errors. The difficulty of reaching the potential errors when the unit is tested independently is comparable to the difficulty of hitting one billiard ball into a particular pocket with a single stroke.

To expose the maximum number of errors that pose security threats, you need to exercise the code as fully as possible. Unit-level testing is the ideal mechanism for doing this.

Design by Contract
Design by Contract (DbC) can be used to validate user inputs as well as to implement firewall-like restrictions that prevent hackers from moving through the application. DbC was designed to express and enforce contracts between a piece of code and its caller; these contracts specify what the callee expects and what the caller can expect.

Typically, DbC is implemented by expressing the code's implicit contracts in terms of assertions. Three types of conditions commonly used to create contracts are:

  • Preconditions: To express conditions that must hold true before a method can execute
  • Postconditions: To express conditions that must hold true after a method completes
  • Invariants: To express conditions that must hold true any time a client can invoke an object's method
Java tools that support DbC generally have you incorporate specification information into comment tags and then instrument the code with a special compiler to create assert-like expressions out of the contract keywords. When the instrumented code is executed, contract violations are typically sent to a monitor or logged to a file. The degree of program interference varies. You can often choose between nonintrusive monitoring (problems are reported, but program execution is not affected), having the program throw an exception when a contract is violated, or hand-coding custom actions.

To learn more about DbC, see the following resources:

  • Plessel, T. "Design By Contract: A Missing Link In The Quest For Quality Software": www.cs.unc.edu/~smithja/MIMS/DataModel/research/DBC.html
  • Interactive Software Engineering. Building Bug-Free O-O Software: An Introduction to Design by Contract: www.eiffel.com/doc/manuals/technology/contract/page.html

    Following the strategies mentioned in this article will protect your Java code from many common security attacks. However, these strategies should be viewed as the beginning of a thorough security strategy, not as a security panacea. You need to anticipate and protect every possible security vulnerability because just one vulnerability can allow a skilled or lucky hacker to steal classified information or make your application unavailable. To ensure security, you need to learn how to identify and repair additional security vulnerabilities; some places to start are:

  • Compaq. Extended Static Checking for Java, SQL Injection Walkthrough: www.securiteam.com/securityreviews/5DP0N1P76E.html
  • Graff, M.G., and van Wyk, K.R. (2003). Secure Coding Principles and Practices. O'Reilly.
  • Howard, M., and LeBlanc, D. (2002). Writing Secure Code. Microsoft Press.
  • Kolawa, A., Hicken, W., and Dunlop, C. (2001). Bulletproofing Web Applications. John Wiley & Sons.
  • McGraw, G., and Felten, E. (1999). Securing Java. John Wiley & Sons: www.securingjava.com
  • Rao, R. (1999). Writing Secure Java Code. Macmillan Technical Publishing.
  • Sun Microsystems. Security Code Guidelines: http://java.sun.com/security/seccodeguide.html
  • Viega, J., McGraw, G., Mutdosch, T., and Felten, E. "Statically Scanning Java Code: Finding Security Vulnerabilities." IEEE Software (Sept./Oct. 2000).
  • More Stories By Adam Kolawa

    Adam Kolawa is the co-founder and CEO of Parasoft, leading provider of solutions and services that deliver quality as a continuous process throughout the SDLC. In 1983, he came to the United States from Poland to pursue his PhD. In 1987, he and a group of fellow graduate students founded Parasoft to create value-added products that could significantly improve the software development process. Adam's years of experience with various software development processes has resulted in his unique insight into the high-tech industry and the uncanny ability to successfully identify technology trends. As a result, he has orchestrated the development of numerous successful commercial software products to meet growing industry needs to improve software quality - often before the trends have been widely accepted. Adam has been granted 10 patents for the technologies behind these innovative products.

    Kolawa, co-author of Bulletproofing Web Applications (Hungry Minds 2001), has contributed to and written over 100 commentary pieces and technical articles for publications including The Wall Street Journal, Java Developer's Journal, SOA World Magazine, AJAXWorld Magazine; he has also authored numerous scientific papers on physics and parallel processing. His recent media engagements include CNN, CNBC, BBC, and NPR. Additionally he has presented on software quality, trends and development issues at various industry conferences. Kolawa holds a Ph.D. in theoretical physics from the California Institute of Technology. In 2001, Kolawa was awarded the Los Angeles Ernst & Young's Entrepreneur of the Year Award in the software category.

    More Stories By Gina Assaf

    Gina Assaf is a systems
    engineer at Parasoft.
    She has been developing, designing, testing, and
    implementing applications
    in Java for nearly six years.
    She has researched and
    developed many of the coding standards, many of which
    provide security for Java
    applications. Assaf has a
    BS in computer science.

    More Stories By Roberto Scaramuzzi

    Roberto Scaramuzzi is a software engineer at Parasoft. He grew up professionally as a Perl developer, but is now also adept at Java and PHP. Roberto holds a PhD in mathematics.

    Comments (3)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
    The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...