Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Free Subscription to Java Pro

email article
printer friendly
more resources

Rule 8: Don't Return References to Mutable Objects
Ensure your Java code is secure
by Adam Kolawa, Ph.D., Gina Assaf, and Roberto Scaramuzzi

Posted April 28, 2004

Editor's Note: Java Pro Online presents a weekly rule for ensuring the security of Java systems. Here's Rule 8 for beginning your strategy for ensuring your Java applications are secure. See the entire index of Java code security rules.

This rule prohibits you from returning references to mutable objects and requires you to clone each mutable object before returning a reference to it. Mutable objects are objects with states that 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:

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 sources:
Secure Programming for Linux and Unix HOWTO David A. Wheeler

About the Authors
Adam Kolawa, Ph.D, is the chairman and CEO of Parasoft. He is a writer and speaker on industry issues and in 2001 was awarded the Los Angeles Ernst & Young Entrepreneur of the Year Award in the software category. Gina Assaf has been developing, designing, testing, and implementing applications in Java for over six years, and has researched and developed coding standards for Parasoft, many of which provide security for Java applications. Roberto Scaramuzzi, Ph.D., is a Java and Perl Developer for Parasoft in San Diego, California. Born in Italy, he later moved to the United States to obtain his doctorate in Mathematics from Yale University. Contact the authors at .




Back to top













Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home