Datasets:
language large_string | page_id int64 | page_url large_string | chapter int64 | section int64 | rule_id large_string | title large_string | intro large_string | noncompliant_code large_string | compliant_solution large_string | risk_assessment large_string | breadcrumb large_string |
|---|---|---|---|---|---|---|---|---|---|---|---|
java | 88,487,763 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487763 | 3 | 18 | CON50-J | Do not assume that declaring a reference volatile guarantees safe publication of the members of the referenced object | According to the
Java Language Specification
,
§8.3.1.4, "
volatile
Fields"
[
JLS 2013
],
A field may be declared
volatile
, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (
§17.4
).
This safe publication guarantee applies only to primitive fields and object references. Programmers commonly use imprecise terminology and speak about "member objects." For the purposes of this visibility guarantee, the actual member is the object reference; the objects referred to (aka
referents
) by volatile object references are beyond the scope of the safe publication guarantee. Consequently, declaring an object reference to be volatile is insufficient to guarantee that changes to the members of the referent are published to other threads. A thread may fail to observe a recent write from another thread to a member field of such an object referent.
Furthermore, when the referent is mutable and lacks thread safety, other threads might see a partially constructed object or an object in a (temporarily) inconsistent state [
Goetz 2007
]. However, when the referent is
immutable
, declaring the reference volatile suffices to guarantee safe publication of the members of the referent. Programmers cannot use the
volatile
keyword to guarantee safe publication of mutable objects. Use of the
volatile
keyword can only guarantee safe publication of primitive fields, object references, or fields of immutable object referents.
Confusing a volatile object with the volatility of its member objects is a similar error to the one described in
. | final class Foo {
private volatile int[] arr = new int[20];
public int getFirst() {
return arr[0];
}
public void setFirst(int n) {
arr[0] = n;
}
// ...
}
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
final class DateHandler {
private static volatile DateFormat format =
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str)
throws ParseException {
return format.parse(str);
}
}
## Noncompliant Code Example (Arrays)
## This noncompliant code example declares a volatile reference to an array object.
#FFcccc
final class Foo {
private volatile int[] arr = new int[20];
public int getFirst() {
return arr[0];
}
public void setFirst(int n) {
arr[0] = n;
}
// ...
}
Values assigned to an array element by one thread—for example, by calling
setFirst()
—might not be visible to another thread calling
getFirst()
because the
volatile
keyword guarantees safe publication only for the array reference; it makes no guarantee regarding the actual data contained within the array.
This problem arises when the thread that calls
setFirst()
and the thread that calls
getFirst()
lack a
happens-before
relationship
. A happens-before relationship exists between a thread that
writes
to a volatile variable and a thread that
subsequently reads
it. However,
setFirst()
and
getFirst()
read only from a volatile variable—the volatile reference to the array. Neither method writes to the volatile variable.
## Noncompliant Code Example (Mutable Object)
This noncompliant code example declares the
Map
instance field volatile. The instance of the
Map
object is mutable because of its
put()
method.
#FFcccc
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
Interleaved calls to
get()
and
put()
may result in the retrieval of internally inconsistent values from the
Map
object because
put()
modifies its state. Declaring the object reference volatile is insufficient to eliminate this data race.
## Noncompliant Code Example (Volatile-Read, Synchronized-Write)
This noncompliant code example attempts to use the volatile-read, synchronized-write technique described in
Java Theory and Practice
[
Goetz 2007
]. The
map
field is declared volatile to synchronize its reads and writes. The
put()
method is also synchronized to ensure that its statements are executed atomically.
#ffcccc
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
The volatile-read, synchronized-write technique uses synchronization to preserve atomicity of compound operations, such as increment, and provides faster access times for atomic reads. However, it fails for mutable objects because the safe publication guarantee provided by
volatile
extends only to the field itself (the primitive value or object reference); the referent is excluded from the guarantee, as are the referent's members. In effect, the write and a subsequent read of the
map
lack a
happens-before
relationship.
This technique is also discussed in
VNA02-J. Ensure that compound operations on shared variables are atomic
.
## Noncompliant Code Example (Mutable Subobject)
## In this noncompliant code example, the volatileformatfield stores a reference to a mutable object,java.text.DateFormat:
#FFcccc
final class DateHandler {
private static volatile DateFormat format =
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str)
throws ParseException {
return format.parse(str);
}
}
Because
DateFormat
is not thread-safe [
API 2013
], the value for
Date
returned by the
parse()
method may not correspond to the
str
argument: | final class Foo {
private final AtomicIntegerArray atomicArray =
new AtomicIntegerArray(20);
public int getFirst() {
return atomicArray.get(0);
}
public void setFirst(int n) {
atomicArray.set(0, 10);
}
// ...
}
final class Foo {
private int[] arr = new int[20];
public synchronized int getFirst() {
return arr[0];
}
public synchronized void setFirst(int n) {
arr[0] = n;
}
}
final class Foo {
private final Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public synchronized String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
final class DateHandler {
public static java.util.Date parse(String str)
throws ParseException {
return DateFormat.getDateInstance(
DateFormat.MEDIUM).parse(str);
}
}
final class DateHandler {
private static DateFormat format =
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str)
throws ParseException {
synchronized (format) {
return format.parse(str);
}
}
}
final class DateHandler {
private static final ThreadLocal<DateFormat> format =
new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateInstance(DateFormat.MEDIUM);
}
};
// ...
}
## Compliant Solution (AtomicIntegerArray)
To ensure that the writes to array elements are atomic and that the resulting values are visible to other threads, this compliant solution uses the
AtomicIntegerArray
class defined in
java.util.concurrent.atomic
.
#ccccff
final class Foo {
private final AtomicIntegerArray atomicArray =
new AtomicIntegerArray(20);
public int getFirst() {
return atomicArray.get(0);
}
public void setFirst(int n) {
atomicArray.set(0, 10);
}
// ...
}
AtomicIntegerArray
guarantees a
happens-before
relationship between a thread that calls
atomicArray.set()
and a thread that subsequently calls
atomicArray.get()
.
## Compliant Solution (Synchronization)
To ensure visibility, accessor methods may synchronize access while performing operations on nonvolatile elements of an array, whether the array is referred to by a volatile or a nonvolatile reference. Note that the code is thread-safe even though the array reference is not volatile.
#ccccff
final class Foo {
private int[] arr = new int[20];
public synchronized int getFirst() {
return arr[0];
}
public synchronized void setFirst(int n) {
arr[0] = n;
}
}
Synchronization establishes a
happens-before
relationship between threads that synchronize on the same lock. In this case, the thread that calls
setFirst()
and the thread that subsequently calls
getFirst()
on the same object instance both synchronize on that instance, so safe publication is guaranteed.
## Compliant Solution (Synchronized)
## This compliant solution uses method synchronization to guarantee visibility:
#ccccff
final class Foo {
private final Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public synchronized String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
It is unnecessary to declare the
map
field volatile because the accessor methods are synchronized. The field is declared
final
to prevent publication of its reference when the referent is in a partially initialized state (see
TSM03-J. Do not publish partially initialized objects
for more information).
## Compliant Solution (Instance per Call/Defensive Copying)
## This compliant solution creates and returns a newDateFormatinstance for each invocation of theparse()method [API 2013]:
#ccccff
final class DateHandler {
public static java.util.Date parse(String str)
throws ParseException {
return DateFormat.getDateInstance(
DateFormat.MEDIUM).parse(str);
}
}
## Compliant Solution (Synchronization)
## This compliant solution makesDateHandlerthread-safe by synchronizing statements within theparse()method [API 2013]:
#ccccff
final class DateHandler {
private static DateFormat format =
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str)
throws ParseException {
synchronized (format) {
return format.parse(str);
}
}
}
## Compliant Solution (ThreadLocalStorage)
## This compliant solution uses aThreadLocalobject to create a separateDateFormatinstance per thread:
#ccccff
final class DateHandler {
private static final ThreadLocal<DateFormat> format =
new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateInstance(DateFormat.MEDIUM);
}
};
// ...
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,832 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487832 | 3 | 18 | CON51-J | Do not assume that the sleep(), yield(), or getState() methods provide synchronization semantics | According to the
Java Language Specification
,
§17.3, "Sleep and Yield"
[
JLS 2013
],
It is important to note that neither
Thread.sleep
nor
Thread.yield
have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to
Thread.sleep
or
Thread.yield
, nor does the compiler have to reload values cached in registers after a call to
Thread.sleep
or
Thread.yield
.
Code that bases its concurrency safety on thread suspension or yields to processes that
Flush cached registers,
Reload any values,
Or provide any
happens-before
relationships when execution resumes,
is incorrect and is consequently disallowed. Programs must ensure that communication between threads has proper synchronization, happens-before, and safe publication semantics. | final class ControlledStop implements Runnable {
private boolean done = false;
@Override public void run() {
while (!done) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Reset interrupted status
Thread.currentThread().interrupt(); }
}
}
public void shutdown() {
this.done = true;
}
}
public class Waiter {
private Thread thread;
private boolean flag;
private final Object lock = new Object();
public void doSomething() {
thread = new Thread(new Runnable() {
@Override public void run() {
synchronized(lock) {
while (!flag) {
try {
lock.wait();
// ...
} catch (InterruptedException e) {
// Forward to handler
}
}
}
}
});
thread.start();
}
public boolean stop() {
if (thread != null) {
if (thread.getState() == Thread.State.WAITING) {
synchronized (lock) {
flag = true;
lock.notifyAll();
}
return true;
}
}
return false;
}
}
## Noncompliant Code Example (sleep())
This noncompliant code attempts to use the nonvolatile primitive Boolean member
done
as a flag to terminate execution of a thread. A separate thread sets
done
to
true
by calling the
shutdown()
method.
#FFCCCC
final class ControlledStop implements Runnable {
private boolean done = false;
@Override public void run() {
while (!done) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Reset interrupted status
Thread.currentThread().interrupt(); }
}
}
public void shutdown() {
this.done = true;
}
}
The compiler, in this case, is free to read the field
this.done
once and to reuse the cached value in each execution of the loop. Consequently, the
while
loop might never terminate, even when another thread calls the
shutdown()
method to change the value of
this.done
[
JLS 2013
]. This error could have resulted from the programmer incorrectly assuming that the call to
Thread.sleep()
causes cached values to be reloaded.
## Noncompliant Code Example (getState())
This noncompliant code example contains a
doSomething()
method that starts a thread. The thread supports interruption by checking a flag and waits until notified. The
stop()
method checks to see whether the thread is blocked on the wait; if so, it sets the flag to true and notifies the thread so that the thread can terminate.
#FFCCCC
public class Waiter {
private Thread thread;
private boolean flag;
private final Object lock = new Object();
public void doSomething() {
thread = new Thread(new Runnable() {
@Override public void run() {
synchronized(lock) {
while (!flag) {
try {
lock.wait();
// ...
} catch (InterruptedException e) {
// Forward to handler
}
}
}
}
});
thread.start();
}
public boolean stop() {
if (thread != null) {
if (thread.getState() == Thread.State.WAITING) {
synchronized (lock) {
flag = true;
lock.notifyAll();
}
return true;
}
}
return false;
}
}
Unfortunately, the
stop()
method incorrectly uses the
Thread.getState()
method to check whether the thread is blocked and has not terminated before delivering the notification. Using the
Thread.getState()
method for synchronization control, such as checking whether a thread is blocked on a wait, is inappropriate. Java Virtual Machines (JVMs) are permitted to implement blocking using spin-waiting; consequently, a thread can be blocked without entering the
WAITING
or
TIMED_WAITING
state [
Goetz 2006
]. Because the thread may never enter the
WAITING
state, the
stop()
method might fail to terminate the thread.
If
doSomething()
and
stop()
are called from different threads, the
stop()
method could fail to see the initialized
thread
, even though
doSomething()
was called earlier, unless there is a happens-before relationship between the two calls. If the two methods are invoked by the same thread, they automatically have a happens-before relationship and consequently cannot encounter this problem. | final class ControlledStop implements Runnable {
private volatile boolean done = false;
@Override public void run() {
//...
}
// ...
}
final class ControlledStop implements Runnable {
@Override public void run() {
// Record current thread, so others can interrupt it
myThread = currentThread();
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void shutdown(Thread th) {
th.interrupt();
}
}
public class Waiter {
// ...
private Thread thread;
private volatile boolean flag;
private final Object lock = new Object();
public boolean stop() {
if (thread != null) {
synchronized (lock) {
flag = true;
lock.notifyAll();
}
return true;
}
return false;
}
}
## Compliant Solution (Volatile Flag)
This compliant solution declares the flag field
volatile
to ensure that updates to its value are made visible across multiple threads:
#ccccff
final class ControlledStop implements Runnable {
private volatile boolean done = false;
@Override public void run() {
//...
}
// ...
}
The volatile keyword establishes a
happens-before
relationship between this thread and any other thread that sets
done
.
## Compliant Solution (Thread.interrupt())
A better solution for methods that call
sleep()
is to use thread interruption, which causes the sleeping thread to wake immediately and handle the interruption.
#ccccff
final class ControlledStop implements Runnable {
@Override public void run() {
// Record current thread, so others can interrupt it
myThread = currentThread();
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void shutdown(Thread th) {
th.interrupt();
}
}
Note that the interrupting thread must know which thread to interrupt; logic for tracking this relationship has been omitted from this solution.
## Compliant Solution
This compliant solution removes the check for determining whether the thread is in the
WAITING
state. This check is unnecessary because invoking
notifyAll()
affects only threads that are blocked on an invocation of
wait()
:
#ccccff
public class Waiter {
// ...
private Thread thread;
private volatile boolean flag;
private final Object lock = new Object();
public boolean stop() {
if (thread != null) {
synchronized (lock) {
flag = true;
lock.notifyAll();
}
return true;
}
return false;
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,842 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487842 | 3 | 18 | CON52-J | Document thread-safety and use annotations where applicable | The Java language annotation facility is useful for documenting design intent. Source code annotation is a mechanism for associating metadata with a program element and making it available to the compiler, analyzers, debuggers, or Java Virtual Machine (JVM) for examination. Several annotations are available for documenting thread-safety or the lack thereof.
## Obtaining Concurrency Annotations
Two sets of concurrency annotations are freely available and licensed for use in any code. The first set consists of four annotations described in
Java Concurrency in Practice
(JCIP) [
Goetz 2006
], which can be downloaded from
jcip.net
(
jar
,
javadoc
,
source
). The JCIP annotations are released under the
Creative Commons Attribution License
.
The second, larger set of concurrency annotations is available from and supported by
SureLogic
. These annotations are released under the
Apache Software License, Version 2.0
and can be downloaded via the
Internet Archive
at
surelogic.com
(
jar
,
javadoc
,
source
). The annotations can be verified by the
SureLogic
JSure
tool, and they remain useful for documenting code even when the tool is unavailable. These annotations include the JCIP annotations because they are supported by the JSure tool. (JSure also supports use of the JCIP JAR file.)
To use the annotations, download and add one or both of the aforementioned JAR files to the code's build path. The use of these annotations to document thread-safety is descr
Deprecated Examples
These examples are based on
SureLogic
, as of 2010. The intent is still useful but the implementation is no longer supported. We recommend using an annotation package that still enjoys active support.
## Documenting Intended Thread-Safety
JCIP provides three class-level annotations to describe the programmer's design intent with respect to thread-safety.
The
@ThreadSafe
annotation is applied to a class to indicate that it is
thread-safe
. This means that no sequences of accesses (reads and writes to public fields, calls to public methods) can leave the object in an inconsistent state, regardless of the interleaving of these accesses by the runtime or any external synchronization or coordination on the part of the caller.
For example, the following
Aircraft
class specifies that it is thread-safe as part of its locking policy documentation. This class protects the
x
and
y
fields using a reentrant lock.
#ccccff
@ThreadSafe
@Region("private AircraftState")
@RegionLock("StateLock is stateLock protects AircraftState")
public final class Aircraft {
private final Lock stateLock = new ReentrantLock();
// ...
@InRegion("AircraftState")
private long x, y;
// ...
public void setPosition(long x, long y) {
stateLock.lock();
try {
this.x = x;
this.y = y;
} finally {
stateLock.unlock();
}
}
// ...
}
The
@Region
and
@RegionLock
annotations document the locking policy upon which the promise of thread-safety is predicated.
Even when one or more
@RegionLock
or
@GuardedBy
annotations have been used to document the locking policy of a class, the
@ThreadSafe
annotation provides an intuitive way for reviewers to learn that the class is thread-safe.
The
@Immutable
annotation is applied to
immutable
classes. Immutable objects are inherently thread-safe; once they are fully constructed, they may be published via a reference and shared safely among multiple threads.
The following example shows an immutable
Point
class:
#ccccff
@Immutable
public final class Point {
private final int f_x;
private final int f_y;
public Point(int x, int y) {
f_x = x;
f_y = y;
}
public int getX() {
return f_x;
}
public int getY() {
return f_y;
}
}
According to Joshua Bloch [
Bloch 2008
],
It is not necessary to document the immutability of
enum
types. Unless it is obvious from the return type, static factories must document the thread safety of the returned object, as demonstrated by
Collections.synchronizedMap
.
The
@NotThreadSafe
annotation is applied to classes that are not thread-safe. Many classes fail to document whether they are safe for multithreaded use. Consequently, a programmer has no easy way to determine whether the class is thread-safe. This annotation provides clear indication of the class's lack of thread-safety.
For example, most of the collection implementations provided in
java.util
are not thread-safe. The class
java.util.ArrayList
could document this as follows:
#ccccff
package java.util.ArrayList;
@NotThreadSafe
public class ArrayList<E> extends ... {
// ...
}
## Documenting Locking Policies
It is important to document all the locks that are being used to protect shared state. According to Brian Goetz and colleagues [
Goetz 2006
],
For each mutable state variable that may be accessed by more than one thread,
all
accesses to that variable must be performed with the
same
lock held. In this case, we say that the variable is
guarded by
that lock. (p. 28)
JCIP provides the
@GuardedBy
annotation for this purpose, and SureLogic provides the
@RegionLock
annotation. The field or method to which the
@GuardedBy
annotation is applied can be accessed only when holding a particular lock. It may be an intrinsic lock or a dynamic lock such as
java.util.concurrent.Lock
.
For example, the following
MovablePoint
class implements a movable point that can remember its past locations using the
memo
array list:
#ccccff
@ThreadSafe
public final class MovablePoint {
@GuardedBy("this")
double xPos = 1.0;
@GuardedBy("this")
double yPos = 1.0;
@GuardedBy("itself")
static final List<MovablePoint> memo
= new ArrayList<MovablePoint>();
public void move(double slope, double distance) {
synchronized (this) {
rememberPoint(this);
xPos += (1 / slope) * distance;
yPos += slope * distance;
}
}
public static void rememberPoint(MovablePoint value) {
synchronized (memo) {
memo.add(value);
}
}
}
The
@GuardedBy
annotations on the
xPos
and
yPos
fields indicate that access to these fields is protected by holding a lock on
this
. The
move()
method also synchronizes on
this
, which modifies these fields. The
@GuardedBy
annotation on the
memo
list indicates that a lock on the
ArrayList
object protects its contents. The
rememberPoint()
method also synchronizes on the
memo
list.
One issue with the
@GuardedBy
annotation is that it fails to indicate when there is a relationship between the fields of a class. This limitation can be overcome by using the SureLogic
@RegionLock
annotation, which declares a new region lock for the class to which this annotation is applied. This declaration creates a new named lock that associates a particular lock object with a region of the class. The region may be accessed only when the lock is held. For example, the
SimpleLock
locking policy indicates that synchronizing on the instance protects all of its state:
#ccccff
@RegionLock("SimpleLock is this protects Instance")
class Simple { ... }
Unlike
@GuardedBy
, the
@RegionLock
annotation allows the programmer to give an explicit, and hopefully meaningful, name to the locking policy.
In addition to naming the locking policy, the
@Region
annotation allows a name to be given to the region of the state that is being protected. That name makes it clear that the state and locking policy belong together, as demonstrated in the following example:
#ccccff
@Region("private AircraftPosition")
@RegionLock("StateLock is stateLock protects AircraftPosition")
public final class Aircraft {
private final Lock stateLock = new ReentrantLock();
@InRegion("AircraftPosition")
private long x, y;
@InRegion("AircraftPosition")
private long altitude;
// ...
public void setPosition(long x, long y) {
stateLock.lock();
try {
this.x = x;
this.y = y;
} finally {
stateLock.unlock();
}
}
// ...
}
In this example, a locking policy named
StateLock
is used to indicate that locking on
stateLock
protects the named
AircraftPosition
region, which includes the mutable state used to represent the position of the aircraft.
Construction of Mutable Objects
Typically, object construction is considered an exception to the locking policy because objects are thread-confined when they are created. An object is confined to the thread that uses the
new
operator to create its instance. After creation, the object can be published to other threads safely. However, the object is not shared until the thread that created the instance allows it to be shared. Safe publication approaches discussed in
TSM01-J. Do not let the this reference escape during object construction
can be expressed succinctly with the
@Unique("return")
annotation.
For example, in the following code, the
@Unique("return")
annotation documents that the object returned from the constructor is a unique reference:
#ccccff
@RegionLock("Lock is this protects Instance")
public final class Example {
private int x = 1;
private int y;
@Unique("return")
public Example(int y) {
this.y = y;
}
// ...
}
## Documenting Thread-Confinement Policies
Dean Sutherland and William Scherlis propose annotations that can document thread-confinement policies. Their approach allows verification of the annotations against as-written code [
Sutherland 2010
].
For example, the following annotations express the design intent that a program has, at most, one Abstract Window Toolkit (AWT) event dispatch thread and several compute threads, and that the compute threads are forbidden to handle AWT data structures or events:
#ccccff
@ThreadRole AWT, Compute
@IncompatibleThreadRoles AWT, Compute
@MaxRoleCount AWT 1
## Documenting Wait-Notify Protocols
According to Goetz and colleagues [
Goetz 2006
],
A state-dependent class should either fully expose (and document) its waiting and notification protocols to subclasses, or prevent subclasses from participating in them at all. (This is an extension of "design and document for inheritance, or else prohibit it" [EJ Item 15].) At the very least, designing a state-dependent class for inheritance requires exposing the condition queues and locks and documenting the condition predicates and synchronization policy; it may also require exposing the underlying state variables. (The worst thing a state-dependent class can do is expose its state to subclasses but not document its protocols for waiting and notification; this is like a class exposing its state variables but not documenting its invariants.) (p. 395)
Wait-notify protocols should be documented adequately. Currently, we are not aware of any annotations for this purpose.
## Applicability
Annotating concurrent code helps document the design intent and can be used to automate the detection and prevention of race conditions and data races.
## Automated Detection
Tool
Version
Checker
Description
2.1.3
GUI Effect Checker
Ensure that non-GUI threads do not access the UI which would crash the application (see Chapter 14)
## Bibliography
[
Bloch 2008
]
Item 70, "Document Thread Safety"
[
Goetz 2006
]
Java Concurrency in Practice
[
Sutherland 2010
]
Composable Thread Coloring | null | null | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,756 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487756 | 2 | 1 | DCL00-J | Prevent class initialization cycles | According to
The Java Language Specification
(JLS),
§12.4, "Initialization of Classes and Interfaces"
[
JLS 2005
]:
Initialization of a class consists of executing its
static
initializers and the initializers for
static
fields (class variables) declared in the class.
Therefore, the presence of a static field triggers the initialization of a class. However, the initializer of a static field could depend on the initialization of another class, possibly creating an initialization cycle.
The JLS also states in
§8.3.2.1, "Initializers for Class Variables"
[
JLS 2005
]:
At run time,
static
variables that are
final
and that are initialized with compile-time constant values are initialized first.
This statement does not apply to instances that use values of static final fields that are initialized at a later stage. Declaring a field to be static final is insufficient to guarantee that it is fully initialized before being read.
Programs in general should—and security-sensitive programs must—eliminate all class initialization cycles. | public class Cycle {
private final int balance;
private static final Cycle c = new Cycle();
private static final int deposit = (int) (Math.random() * 100); // Random deposit
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
class A {
public static final int a = B.b + 1;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
}
class A {
public static int a = B.b();
public static int c() { return 1; }
}
class B {
public static int b() { return A.c(); }
}
## Noncompliant Code Example (Intraclass Cycle)
## This noncompliant code example contains an intraclass initialization cycle:
#FFcccc
public class Cycle {
private final int balance;
private static final Cycle c = new Cycle();
private static final int deposit = (int) (Math.random() * 100); // Random deposit
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
The
Cycle
class declares a
private static final
class variable, which is initialized to a new instance of the
Cycle
class. Static initializers are guaranteed to be invoked once before the first use of a static class member or the first invocation of a constructor.
The programmer's intent is to calculate the account balance by subtracting the processing fee from the deposited amount. However, the initialization of the
c
class variable happens before the runtime initialization of the
deposit
field because it appears lexically before the initialization of the
deposit
field. Consequently, the value of
deposit
seen by the constructor, when invoked during the static initialization of
c
, is the initial value of
deposit
(0) rather than the random value. As a result, the balance is always computed to be
-10
.
Step 3 of the detailed initialized procedure described in JLS
§12.4.2
[
JLS 2014
] permits implementations to ignore the possibility of such recursive initialization cycles.
## Noncompliant Code Example (Interclass Cycle)
This noncompliant code example declares two classes with static variables whose values depend on each other. The cycle is obvious when the classes are seen together (as here) but is easy to miss when viewing the classes separately.
#FFcccc
class A {
public static final int a = B.b + 1;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
}
The initialization order of the classes can vary, causing computation of different values for
A.a
and
B.b
. When class
A
is initialized first,
A.a
will have the value 2, and
B.b
will have the value 1. These values will be reversed when class
B
is initialized first.
## Noncompliant Code Example
The programmer in this noncompliant code example attempts to initialize a static variable in one class using a static method in a second class, but that method in turn relies on a static method in the first class:
#ffcccc
java
class A {
public static int a = B.b();
public static int c() { return 1; }
}
class B {
public static int b() { return A.c(); }
}
This code correctly initializes
A.a
to 1, using the Oracle JVM, regardless of whether
A
or
B
is loaded first. However, the JLS does not guarantee
A.a
to be properly initialized. Furthermore, the initialization cycle makes this system harder to maintain and more likely to break in surprising ways when modified. | public class Cycle {
private final int balance;
private static final int deposit = (int) (Math.random() * 100); // Random deposit
private static final Cycle c = new Cycle(); // Inserted after initialization of required fields
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
class A {
public static final int a = 2;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
}
class A {
public static int a = B.b();
}
class B {
public static int b() { return B.c(); }
public static int c() { return 1; }
}
## Compliant Solution (Intraclass Cycle)
This compliant solution changes the initialization order of the class
Cycle
so that the fields are initialized without creating any dependency cycles. Specifically, the initialization of
c
is placed lexically
after
the initialization of
deposit
so that it occurs temporally after
deposit
is fully initialized.
#ccccff
public class Cycle {
private final int balance;
private static final int deposit = (int) (Math.random() * 100); // Random deposit
private static final Cycle c = new Cycle(); // Inserted after initialization of required fields
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
Such initialization cycles become insidious when many fields are involved, so it is important to ensure that the control flow lacks such cycles.
Although this compliant solution prevents the initialization cycle, it depends on declaration order and is consequently fragile; later maintainers of the software may be unaware that the declaration order must be maintained to preserve correctness. Consequently, such dependencies must be clearly documented in the code.
## Compliant Solution (Interclass Cycle)
## This compliant solution breaks the interclass cycle by eliminating the dependency ofAonB:
#ccccff
class A {
public static final int a = 2;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
}
With the cycle broken, the initial values will always be
A.a = 2
and
B.b = 3
regardless of initialization order.
## Compliant Solution
## This compliant solution moves thec()method into classB, breaking the cycle:
#ccccff
java
class A {
public static int a = B.b();
}
class B {
public static int b() { return B.c(); }
public static int c() { return 1; }
} | ## Risk Assessment
Initialization cycles may lead to unexpected results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL00-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,448 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487448 | 2 | 1 | DCL01-J | Do not reuse public identifiers from the Java Standard Library | Do not reuse the names of publicly visible identifiers, public utility classes, interfaces, or packages in the Java Standard Library.
When a developer uses an identifier that has the same name as a public class, such as
Vector
, a subsequent maintainer might be unaware that this identifier does not actually refer to
java.util.Vector
and might unintentionally use the custom
Vector
rather than the original
java.util.Vector
class. The custom type
Vector
can
shadow
a class name from
java.util.Vector
, as specified by
The Java Language Specification
(JLS),
§6.3.2, "Obscured Declarations"
[
JLS 2005
], and unexpected program behavior can occur.
Well-defined import statements can resolve these issues. However, when reused name definitions are imported from other packages, use of the
type-import-on-demand declaration
(see
§7.5.2, "Type-Import-on-Demand Declaration"
[
JLS 2005
]) can complicate a programmer's attempt to determine which specific definition was intended to be used. Additionally, a common practice that can lead to errors is to produce the import statements
after
writing the code, often via automatic inclusion of import statements by an IDE, which creates further ambiguity with respect to the names. When a custom type is found earlier than the intended type in the Java include path, no further searches are conducted. Consequently, the wrong type is silently adopted. | class Vector {
private int val = 1;
public boolean isEmpty() {
if (val == 1) { // Compares with 1 instead of 0
return true;
} else {
return false;
}
}
// Other functionality is same as java.util.Vector
}
// import java.util.Vector; omitted
public class VectorUser {
public static void main(String[] args) {
Vector v = new Vector();
if (v.isEmpty()) {
System.out.println("Vector is empty");
}
}
}
## Noncompliant Code Example (Class Name)
This noncompliant code example implements a class that reuses the name of the class
java.util.Vector
. It attempts to introduce a different condition for the
isEmpty()
method for interfacing with native legacy code by
overriding
the corresponding method in
java.util.Vector
. Unexpected behavior can arise if a maintainer confuses the
isEmpty()
method with the
java.util.Vector.isEmpty()
method.
#FFcccc
class Vector {
private int val = 1;
public boolean isEmpty() {
if (val == 1) { // Compares with 1 instead of 0
return true;
} else {
return false;
}
}
// Other functionality is same as java.util.Vector
}
// import java.util.Vector; omitted
public class VectorUser {
public static void main(String[] args) {
Vector v = new Vector();
if (v.isEmpty()) {
System.out.println("Vector is empty");
}
}
} | class MyVector {
//Other code
}
## Compliant Solution (Class Name)
This compliant solution uses a different name for the class, preventing any potential
shadowing
of the class from the Java Standard Library:
#ccccff
class MyVector {
//Other code
}
When the developer and organization control the original shadowed class, it may be preferable to change the design strategy of the original in accordance with Bloch's
Effective Java
[
Bloch 2008
], Item 16, "Prefer Interfaces to Abstract Classes." Changing the original class into an interface would permit class
MyVector
to declare that it implements the hypothetical
Vector
interface. With this technique, client code that intended to use
MyVector
would remain compatible with code that uses the original implementation of
Vector
. | ## Risk Assessment
Public identifier reuse decreases the readability and maintainability of code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL01-J
Low
Unlikely
Yes
No
P2
L3
Automated Detection
An automated tool can easily detect reuse of the set of names representing public classes or interfaces from the Java Standard Library. | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,681 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487681 | 2 | 1 | DCL02-J | Do not modify the collection's elements during an enhanced for statement | The enhanced
for
statement is designed for iteration through
Collections
and
arrays
.
The Java Language Specification
(JLS) provides the following example of the enhanced
for
statement in
§14.14.2, "The Enhanced
for
Statement"
[
JLS 2014
]:
The enhanced for statement is equivalent to a basic for statement of the form:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
{VariableModifier} TargetType Identifier =
(TargetType) #i.next();
Statement
}
#i is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope...at the point where the enhanced for statement occurs.
Unlike the basic
for
statement, assignments to the loop variable fail to affect the loop's iteration order or the iterated collection or array. Consequently, an assignment to the loop variable is equivalent to modifying a variable local to the loop body whose initial value is the object referenced by the loop iterator. This modification is not necessarily erroneous but can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced
for
statement.
Declare all enhanced
for
statement loop variables final. The
final
declaration causes Java compilers to flag and reject any assignments made to the loop variable. | List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15});
boolean first = true;
System.out.println("Processing list...");
for (Integer i: list) {
if (first) {
first = false;
i = new Integer(99);
}
System.out.println(" New item: " + i);
// Process i
}
System.out.println("Modified list?");
for (Integer i: list) {
System.out.println("List item: " + i);
}
## Noncompliant Code Example
This noncompliant code example attempts to process a collection of integers using an enhanced
for
loop. It further intends to modify one item in the collection for processing:
#ffcccc
java
List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15});
boolean first = true;
System.out.println("Processing list...");
for (Integer i: list) {
if (first) {
first = false;
i = new Integer(99);
}
System.out.println(" New item: " + i);
// Process i
}
System.out.println("Modified list?");
for (Integer i: list) {
System.out.println("List item: " + i);
}
However, this code does not actually modify the list, as shown by the program's output:
Processing list...
New item: 99
New item: 14
New item: 15
Modified list?
List item: 13
List item: 14
List item: 15 | // ...
for (final Integer i: list) {
if (first) {
first = false;
i = new Integer(99); // compiler error: variable i might already have been assigned
}
// ...
// ...
for (final Integer i: list) {
Integer item = i;
if (first) {
first = false;
item = new Integer(99);
}
System.out.println(" New item: " + item);
// Process item
}
// ...
## Compliant Solution
Declaring
i
to be final mitigates this problem by causing the compiler to fail to permit
i
to be assigned a new value:
#ffcccc
java
// ...
for (final Integer i: list) {
if (first) {
first = false;
i = new Integer(99); // compiler error: variable i might already have been assigned
}
// ...
## Compliant Solution
## This compliant solution processes the "modified" list but leaves the actual list unchanged:
#ccccff
java
// ...
for (final Integer i: list) {
Integer item = i;
if (first) {
first = false;
item = new Integer(99);
}
System.out.println(" New item: " + item);
// Process item
}
// ... | ## Risk Assessment
Assignments to the loop variable of an enhanced
for
loop (
for-each
idiom) fail to affect the overall iteration order or the iterated collection or array. This can lead to programmer confusion, and can leave data in a fragile or inconsistent state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL02-J
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
JD.UNMOD
Parasoft Jtest
CERT.DCL02.ITMOD
Do not modify collection while iterating over it | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,660 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487660 | 3 | 1 | DCL50-J | Use visually distinct identifiers | Use visually distinct identifiers that are unlikely to be misread during development and review of code. Depending on the fonts used, certain characters are visually similar or even identical and can be misinterpreted. Consider the examples in the following table.
Misleading characters
Intended Character
Could Be Mistaken for This Character, and Vice Versa
0 (zero)
O (capital
o
)
D (capital
d
)
1 (one)
I (capital
i
)
l (lowercase
L
)
2 (two)
Z (capital
z
)
5 (five)
S (capital
s
)
8 (eight)
B (capital
b
)
n (lowercase
N
)
h (lowercase
H
)
rn (lowercase
R
, lowercase
N
)
m (lowercase
M
)
The
Java Language Specification
(JLS) mandates that program source code be written using the Unicode character encoding [
Unicode 2013
]. Some distinct Unicode characters share identical glyph representation when displayed in many common fonts. For example, the Greek and Coptic characters (Unicode Range 0370–03FF) are frequently indistinguishable from the Greek-character subset of the Mathematical Alphanumeric Symbols (Unicode Range 1D400–1D7FF).
Avoid defining identifiers that include Unicode characters with overloaded glyphs. One straightforward approach is to use only ASCII or Latin-1 characters in identifiers. Note that the ASCII character set is a subset of Unicode.
Do not use multiple identifiers that vary by only one or more visually similar characters. Also, make the initial portions of long identifiers distinct to aid recognition. | int stem; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111l);
}
}
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2] = 0042;
// ...
}
## Noncompliant Code Example
This noncompliant code example has two variables,
stem
and
stern
, within the same scope that can be easily confused and accidentally interchanged:
#ffcccc
int stem; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
## Noncompliant Code Example
This noncompliant example prints the result of adding an
int
and a
long
value even though it appears that two integers
11111
are being added. According to the JLS,
§3.10.1, "Integer Literals"
[
JLS 2013
],
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise, it is of type int. The suffix L is preferred because the letter l (ell) is often hard to distinguish from the digit 1 (one).
Consequently, use
L
, not
l
, to clarify programmer intent when indicating that an integer literal is of type
long
.
#FFCCCC
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111l);
}
}
## Noncompliant Code Example
This noncompliant example mixes decimal values and octal values while storing them in an array. Integer literals with leading zeros denote octal values–not decimal values. According to
§3.10.1, "Integer Literals"
of the JLS [
JLS 2013
],
An octal numeral consists of an ASCII digit
0
followed by one or more of the ASCII digits
0
through
7
interspersed with underscores, and can represent a positive, zero, or negative integer.
This misinterpretation may result in programming errors and is more likely to occur while declaring multiple constants and trying to enhance the formatting with zero padding.
#FFCCCC
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2] = 0042;
// ...
}
The third element in
array
was likely intended to hold the decimal value 42. However, the decimal value 34 (corresponding to the octal value 42) is assigned. | int bow; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111L);
}
}
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2] = 42;
// ...
}
## Compliant Solution
## This compliant solution eliminates the confusion by assigning visually distinct identifiers to the variables:
#ccccff
int bow; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
## Compliant Solution
This compliant solution uses an uppercase
L
(
long
) instead of lowercase
l
to disambiguate the visual appearance of the second integer. Its behavior is the same as that of the noncompliant code example, but the programmer's intent is clear:
#ccccff
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111L);
}
}
## Compliant Solution
When integer literals are intended to represent a decimal value, avoid padding with leading zeros. Use another technique instead, such as padding with whitespace, to preserve digit alignment.
#CCCCFF
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2] = 42;
// ...
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,396 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487396 | 3 | 1 | DCL51-J | Do not shadow or obscure identifiers in subscopes | Reuse of identifier names in subscopes leads to obscuration or shadowing. Reused identifiers in the current scope can render those defined elsewhere inaccessible. Although the
Java Language Specification
(JLS) [
JLS 2013
] clearly resolves any syntactic ambiguity arising from obscuring or shadowing, such ambiguity burdens code maintainers and auditors, especially when code requires access to both the original named entity and the inaccessible one. The problem is exacerbated when the reused name is defined in a different package.
According to
§6.4.2, "Obscuring,"
of the JLS [
JLS 2013
],
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
This implies that a variable can
obscure
a type or a package, and a type can obscure a package name.
Shadowing
, on the other hand, refers to one variable rendering another variable inaccessible in a containing scope. One type can also shadow another type.
No identifier should obscure or shadow another identifier in a containing scope. For example, a local variable should not reuse the name of a class field or method or a class name or package name. Similarly, an inner class name should not reuse the name of an outer class or package.
Both overriding and shadowing differ from
hiding
, in which an accessible member (typically nonprivate) that should have been inherited by a subclass is replaced by a locally declared subclass member that assumes the same name but has a different, incompatible method signature. | class MyVector {
private int val = 1;
private void doLogic() {
int val;
//...
}
}
class MyVector {
private int i = 0;
private void doLogic() {
for (i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
}
## Noncompliant Code Example (Field Shadowing)
## This noncompliant code example reuses the name of thevalinstance field in the scope of an instance method.
#FFcccc
class MyVector {
private int val = 1;
private void doLogic() {
int val;
//...
}
}
The resulting behavior can be classified as shadowing; the method variable renders the instance variable inaccessible within the scope of the method. For example, assigning to
val
from within the method does not affect the value of the instance variable, although assigning to
this.val
from within the method does.
## Noncompliant Code Example (Variable Shadowing)
This example is noncompliant because the variable
i
defined in the scope of the second
for
loop block shadows the definition of the instance variable
i
defined in the
MyVector
class:
#FFcccc
class MyVector {
private int i = 0;
private void doLogic() {
for (i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
} | class MyVector {
private int val = 1;
private void doLogic() {
int newValue;
//...
}
}
class MyVector {
private void doLogic() {
for (int i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
}
## Compliant Solution (Field Shadowing)
This compliant solution eliminates shadowing by changing the name of the variable defined in the method scope from
val
to
newValue
:
#ccccff
class MyVector {
private int val = 1;
private void doLogic() {
int newValue;
//...
}
}
## Compliant Solution (Variable Shadowing)
## In this compliant solution, the loop counteriis defined in the scope of eachforloop block:
#ccccff
class MyVector {
private void doLogic() {
for (int i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,521 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487521 | 3 | 1 | DCL52-J | Do not declare more than one variable per declaration | Declaring multiple variables in a single declaration could cause confusion about the types of variables and their initial values. In particular, do not declare any of the following in a single declaration:
Variables of different types
A mixture of initialized and uninitialized variables
In general, you should declare each variable on its own line with an explanatory comment regarding its role. While not required for conformance with this guideline, this practice is also recommended in the Code Conventions for the Java Programming Language, §6.1, "Number Per Line" [
Conventions 2009
].
This guideline applies to
Local variable declaration statements [
JLS 2013
,
§14.4
]
Field declarations [
JLS 2013
,
§8.3
]
Field (constant) declarations [
JLS 2013
,
§9.3
] | int i, j = 1;
public class Example<T> {
private T a, b, c[], d;
public Example(T in) {
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
}
public String toString() {
return a.toString() + b.toString() +
c.toString() + d.toString();
}
// Correct functional implementation
public String toString(){
String s = a.toString() + b.toString();
for (int i = 0; i < c.length; i++){
s += c[i].toString();
}
s += d.toString();
return s;
}
## Noncompliant Code Example (Initialization)
This noncompliant code example might lead a programmer or reviewer to mistakenly believe that both
i
and
j
are initialized to 1. In fact, only
j
is initialized, while
i
remains uninitialized:
#FFcccc
int i, j = 1;
## Noncompliant Code Example (Different Types)
In this noncompliant code example, the programmer declares multiple variables, including an array, on the same line. All instances of the type
T
have access to methods of the
Object
class. However, it is easy to forget that arrays require special treatment when some of these methods are overridden.
#FFcccc
public class Example<T> {
private T a, b, c[], d;
public Example(T in) {
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
}
When an
Object
method, such as
toString()
, is overridden, a programmer could accidentally provide an implementation for type
T
that fails to consider that
c
is an array of
T
rather than a reference to an object of type
T
.
public String toString() {
return a.toString() + b.toString() +
c.toString() + d.toString();
}
However, the programmer's intent could have been to invoke
toString()
on each individual element of the array
c
.
// Correct functional implementation
public String toString(){
String s = a.toString() + b.toString();
for (int i = 0; i < c.length; i++){
s += c[i].toString();
}
s += d.toString();
return s;
} | int i = 1; // Purpose of i...
int j = 1; // Purpose of j...
int i = 1, j = 1;
public class Example<T> {
private T a; // Purpose of a...
private T b; // Purpose of b...
private T[] c; // Purpose of c[]...
private T d; // Purpose of d...
public Example(T in){
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
}
## Compliant Solution (Initialization)
## In this compliant solution, it is readily apparent that bothiandjare initialized to 1:
#ccccff
int i = 1; // Purpose of i...
int j = 1; // Purpose of j...
## Compliant Solution (Initialization)
## In this compliant solution, it is readily apparent that bothiandjare initialized to 1:
#ccccff
int i = 1, j = 1;
Declaring each variable on a separate line is the preferred method. However, multiple variables on one line are acceptable when they are trivial temporary variables such as array indices.
## Compliant Solution (Different Types)
## This compliant solution places each declaration on its own line and uses the preferred notation for array declaration:
#ccccFF
public class Example<T> {
private T a; // Purpose of a...
private T b; // Purpose of b...
private T[] c; // Purpose of c[]...
private T d; // Purpose of d...
public Example(T in){
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,517 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487517 | 3 | 1 | DCL53-J | Minimize the scope of variables | Scope minimization helps developers avoid common programming errors, improves code readability by connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed. It may also allow objects to be recovered by the garbage collector more quickly, and it prevents violations of
. | public class Scope {
public static void main(String[] args) {
int i = 0;
for (i = 0; i < 10; i++) {
// Do operations
}
}
}
public class Foo {
private int count;
private static final int MAX_COUNT = 10;
public void counter() {
count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
}
}
}
private boolean condition() {/* ... *}
// No other method references count
// but several other methods reference MAX_COUNT
}
## Noncompliant Code Example
## This noncompliant code example shows a variable that is declared outside theforloop.
#FFcccc
public class Scope {
public static void main(String[] args) {
int i = 0;
for (i = 0; i < 10; i++) {
// Do operations
}
}
}
This code is noncompliant because, even though variable
i
is not intentionally used outside the
for
loop, it is declared in method scope. One of the few scenarios where variable
i
would need to be declared in method scope is when the loop contains a break statement and the value of
i
must be inspected after conclusion of the loop.
## Noncompliant Code Example
This noncompliant code example shows a variable
count
that is declared outside the
counter
method, although the variable is not used outside the
counter
method.
#FFcccc
public class Foo {
private int count;
private static final int MAX_COUNT = 10;
public void counter() {
count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
}
}
}
private boolean condition() {/* ... *}
// No other method references count
// but several other methods reference MAX_COUNT
} | public class Scope {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) { // Contains declaration
// Do operations
}
}
}
public class Foo {
private static final int MAX_COUNT = 10;
public void counter() {
int count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
}
}
}
private boolean condition() {/* ... */}
// No other method references count
// but several other methods reference MAX_COUNT
}
## Compliant Solution
Minimize the scope of variables where possible. For example, declare loop indices within the
for
statement:
#ccccff
public class Scope {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) { // Contains declaration
// Do operations
}
}
}
## Compliant Solution
## In this compliant solution, thecountfield is declared local to thecounter()method:
#ccccff
public class Foo {
private static final int MAX_COUNT = 10;
public void counter() {
int count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
}
}
}
private boolean condition() {/* ... */}
// No other method references count
// but several other methods reference MAX_COUNT
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,464 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487464 | 3 | 1 | DCL54-J | Use meaningful symbolic constants to represent literal values in program logic | Java supports the use of various types of literals, such as integers (5, 2), floating-point numbers (2.5, 6.022e+23), characters (
'a'
,
'\n'
), Booleans (
true
,
false
), and strings (
"Hello\n"
). Extensive use of literals in a program can lead to two problems. First, the meaning of the literal is often obscured or unclear from the context. Second, changing a frequently used literal requires searching the entire program source for that literal and distinguishing the uses that must be modified from those that should remain unmodified.
Avoid these problems by declaring class variables with meaningfully named constants, setting their values to the desired literals, and referencing the constants instead of the literals throughout the program. This approach clearly indicates the meaning or intended use of each literal. Furthermore, should the constant require modification, the change is limited to the declaration; searching the code is unnecessary.
Constants should be declared as
static
and
final
. However, constants should not be declared public and final if their values might change (see
for more details). For example,
private static final int SIZE = 25;
Although
final
can be used to specify immutable constants, there is a caveat when dealing with composite objects. See
for more details. | double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
return 4.19 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 6.28 * radius;
}
double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
return 4.0 / 3.0 * 3.14 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * 3.14 * radius;
}
private static final int BUFSIZE = 512;
// ...
public void shiftBlock() {
int nblocks = 1 + ((nbytes - 1) >> 9); // BUFSIZE = 512 = 2^9
// ...
}
## Noncompliant Code Example
## This noncompliant code example calculates approximate dimensions of a sphere, given its radius:
#ffcccc
double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
return 4.19 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 6.28 * radius;
}
The methods use the seemingly arbitrary literals
3.14
,
4.19
, and
6.28
to represent various scaling factors used to calculate these dimensions. A developer or maintainer reading this code would have little idea about how they were generated or what they mean and consequently would not understand the function of this code.
## Noncompliant Code Example
## This noncompliant code example attempts to avoid the problem by explicitly calculating the required constants:
#ffcccc
double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
return 4.0 / 3.0 * 3.14 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * 3.14 * radius;
}
The code uses the literal
3.14
to represent the value π. Although it removes some of the ambiguity from the literals, it complicates code maintenance. If the programmer were to decide that a more precise value of π is desired, all occurrences of
3.14
in the code would have to be found and replaced.
## Noncompliant Code Example
This noncompliant code example defines a constant
BUFSIZE
but then defeats the purpose of defining
BUFSIZE
as a constant by assuming a specific value for
BUFSIZE
in the following expression:
#FFcccc
private static final int BUFSIZE = 512;
// ...
public void shiftBlock() {
int nblocks = 1 + ((nbytes - 1) >> 9); // BUFSIZE = 512 = 2^9
// ...
}
The programmer has assumed that
BUFSIZE
is 512, and right-shifting 9 bits is the same (for positive numbers) as dividing by 512. However, if
BUFSIZE
changes to 1024 in the future, modifications will be difficult and error prone.
This code also fails to conform to
. Replacing a division operation with a right shift is considered a premature optimization. Normally, the compiler will do a better job of determining when this optimization should be performed. | private static final double PI = 3.14;
double area(double radius) {
return PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * PI * radius;
}
double area(double radius) {
return Math.PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * Math.PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * Math.PI * radius;
}
private static final int BUFSIZE = 512;
// ...
public void shiftBlock(int nbytes) {
int nblocks = 1 + (nbytes - 1) / BUFSIZE;
// ...
}
## Compliant Solution (Constants)
In this compliant solution, a constant
PI
is declared and initialized to
3.14
. Thereafter, it is referenced in the code whenever the value of π is needed.
#ccccff
private static final double PI = 3.14;
double area(double radius) {
return PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * PI * radius;
}
This technique reduces clutter and promotes maintainability. If a more precise approximation of the value of π is required, the programmer can simply redefine the constant. The use of the literals
4.0
,
3.0
, and
2
does not violate this guideline, for reasons explained in the "Applicability" section of this guideline.
## Compliant Solution (Predefined Constants)
Use predefined constants when they are available. The class
java.lang.Math
defines a large group of numeric constants, including
PI
and the exponential constant
E
.
#ccccff
double area(double radius) {
return Math.PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * Math.PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * Math.PI * radius;
}
## Compliant Solution
## This compliant solution uses the identifier assigned to the constant value in the expression:
#ccccff
private static final int BUFSIZE = 512;
// ...
public void shiftBlock(int nbytes) {
int nblocks = 1 + (nbytes - 1) / BUFSIZE;
// ...
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,528 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487528 | 3 | 1 | DCL55-J | Properly encode relationships in constant definitions | The definitions of constant expressions should be related
exactly
when the values they express are also related. | public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = 20;
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = VOTING_AGE + 3;
## Noncompliant Code Example
In this noncompliant code example,
OUT_STR_LEN
must always be exactly two greater than
IN_STR_LEN
. These definitions fail to reflect this requirement:
#FFcccc
public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = 20;
## Noncompliant Code Example
In this noncompliant code example, there appears to be an underlying relationship between the two constants where none exists:
#FFcccc
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = VOTING_AGE + 3;
A programmer performing routine maintenance may modify the definition for
VOTING_AGE
but fail to recognize the resulting change in the definition for
ALCOHOL_AGE
. | public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = IN_STR_LEN + 2;
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = 21;
## Compliant Solution
## In this compliant solution, the relationship between the two values is represented in the definitions:
#ccccff
public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = IN_STR_LEN + 2;
## Compliant Solution
## In this compliant solution, the definitions reflect the independence of the two constants:
#ccccff
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = 21; | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,623 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487623 | 3 | 1 | DCL56-J | Do not attach significance to the ordinal associated with an enum | Java language enumeration types have an
ordinal()
method that returns the numerical position of each enumeration constant in its class declaration.
According to the Java API,
Class Enum<E extends Enum<E>>
[
API 2011
],
public final int ordinal()
returns the ordinal of the enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as
EnumSet
and
EnumMap
.
The
Java Language Specification,
§8.9, "Enums"
[
JLS 2013
], does not specify the use of
ordinal()
in programs. However, attaching external significance to the
ordinal()
value of an
enum
constant is error prone and should be avoided for defensive programming. | enum Hydrocarbon {
METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
HEXANE, HEPTANE, OCTANE, NONANE, DECANE;
public int getNumberOfCarbons() {
return ordinal() + 1;
}
}
## Noncompliant Code Example
This noncompliant code example declares
enum Hydrocarbon
and uses its
ordinal()
method to provide the result of the
getNumberOfCarbons()
method:
#FFcccc
enum Hydrocarbon {
METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
HEXANE, HEPTANE, OCTANE, NONANE, DECANE;
public int getNumberOfCarbons() {
return ordinal() + 1;
}
}
Although this noncompliant code example behaves as expected, its maintenance is likely to be problematic. If the
enum
constants were reordered, the
getNumberOfCarbons()
method would return incorrect values. Furthermore, adding an additional
BENZENE
constant to the model would break the invariant assumed by the
getNumberOfCarbons()
method because benzene has six carbons, but the ordinal value 6 is already taken by
HEXANE
. | enum Hydrocarbon {
METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5),
HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9),
DECANE(10);
private final int numberOfCarbons;
Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; }
public int getNumberOfCarbons() {
return numberOfCarbons;
}
}
## Compliant Solution
In this compliant solution,
enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain:
#ccccff
enum Hydrocarbon {
METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5),
HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9),
DECANE(10);
private final int numberOfCarbons;
Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; }
public int getNumberOfCarbons() {
return numberOfCarbons;
}
}
The
getNumberOfCarbons()
method no longer uses the
ordinal()
to discover the number of carbon atoms for each value. Different
enum
constants may be associated with the same value, as shown for
HEXANE
and
BENZENE
. Furthermore, this solution lacks any dependence on the order of the enumeration; the
getNumberOfCarbons()
method would continue to work even if the enumeration were reordered. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,795 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487795 | 3 | 1 | DCL57-J | Avoid ambiguous overloading of variable arity methods | The
variable arity (varargs)
feature was introduced in JDK v1.5.0 to support methods that accept a variable numbers of arguments.
According to the Java SE 6 documentation [
Oracle 2011b
],
As an API designer, you should use [variable arity methods] sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. | class Varargs {
private static void displayBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayBooleans(boolean bool1, boolean bool2) {
System.out.println("Overloaded method invoked");
}
public static void main(String[] args) {
displayBooleans(true, false);
}
}
Overloaded method invoked
## Noncompliant Code Example
In this noncompliant code example, overloading variable arity methods makes it unclear which definition of
displayBooleans()
is invoked:
#FFCCCC
class Varargs {
private static void displayBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayBooleans(boolean bool1, boolean bool2) {
System.out.println("Overloaded method invoked");
}
public static void main(String[] args) {
displayBooleans(true, false);
}
}
When run, this program outputs
Overloaded method invoked
because the nonvariable arity definition is more specific and consequently a better fit for the provided arguments. However, this complexity is best avoided. | class Varargs {
private static void displayManyBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayTwoBooleans(boolean bool1, boolean bool2) {
System.out.println("Overloaded method invoked");
System.out.println("Contents: [" + bool1 + "], [" + bool2 + "]");
}
public static void main(String[] args) {
displayManyBooleans(true, false);
}
}
## Compliant Solution
To avoid overloading variable arity methods, use distinct method names to ensure that the intended method is invoked, as shown in this compliant solution:
#ccccff
class Varargs {
private static void displayManyBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayTwoBooleans(boolean bool1, boolean bool2) {
System.out.println("Overloaded method invoked");
System.out.println("Contents: [" + bool1 + "], [" + bool2 + "]");
}
public static void main(String[] args) {
displayManyBooleans(true, false);
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,794 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487794 | 3 | 1 | DCL58-J | Enable compile-time type checking of variable arity parameter types | A variable arity (aka
varargs
) method is a method that can take a variable number of arguments. The method must contain at least one fixed argument. When processing a variable arity method call, the Java compiler checks the types of all arguments, and all of the variable actual arguments must match the variable formal argument type. However, compile-time type checking is ineffective when
Object
or generic parameter types are used [
Bloch 2008
]. The presence of initial parameters of specific types is irrelevant; the compiler will remain unable to check
Object
or generic variable parameter types. Enable strong compile-time type checking of variable arity methods by using the most specific type possible for the method parameter. | double sum(Object... args) {
double result = 0.0;
for (Object arg : args) {
if (arg instanceof Byte) {
result += ((Byte) arg).byteValue();
} else if (arg instanceof Short) {
result += ((Short) arg).shortValue();
} else if (arg instanceof Integer) {
result += ((Integer) arg).intValue();
} else if (arg instanceof Long) {
result += ((Long) arg).longValue();
} else if (arg instanceof Float) {
result += ((Float) arg).floatValue();
} else if (arg instanceof Double) {
result += ((Double) arg).doubleValue();
} else {
throw new ClassCastException();
}
}
return result;
}
<T> double sum(T... args) {
// ...
}
## Noncompliant Code Example (Object)
This noncompliant code example sums a set of numbers using a variable arity method that uses
Object
as the variable arity type. Consequently, this method accepts an arbitrary mix of parameters of any object type. Legitimate uses of such declarations are rare (but see the "Applicability" section of this guideline).
#FFCCCC
double sum(Object... args) {
double result = 0.0;
for (Object arg : args) {
if (arg instanceof Byte) {
result += ((Byte) arg).byteValue();
} else if (arg instanceof Short) {
result += ((Short) arg).shortValue();
} else if (arg instanceof Integer) {
result += ((Integer) arg).intValue();
} else if (arg instanceof Long) {
result += ((Long) arg).longValue();
} else if (arg instanceof Float) {
result += ((Float) arg).floatValue();
} else if (arg instanceof Double) {
result += ((Double) arg).doubleValue();
} else {
throw new ClassCastException();
}
}
return result;
}
## Noncompliant Code Example (Generic Type)
This noncompliant code example declares the same variable arity method using a generic type parameter. It accepts a variable number of parameters that are all of the
same
object type; however, it may be any object type. Again, legitimate uses of such declarations are rare.
#FFCCCC
<T> double sum(T... args) {
// ...
} | double sum(Number... args) {
// ...
}
<T extends Number> double sum(T... args) {
// ...
}
## Compliant Solution (Number)
This compliant solution defines the same method but uses the
Number
type. This abstract class is general enough to encompass all numeric types, yet specific enough to exclude nonnumeric types.
#ccccff
double sum(Number... args) {
// ...
}
## Compliant Solution (Generic Type)
## This compliant solution defines the same generic method using theNumbertype.
#ccccff
<T extends Number> double sum(T... args) {
// ...
}
Be as specific as possible when declaring parameter types; avoid
Object
and imprecise generic types in variable arity methods. Retrofitting old methods containing final array parameters with generically typed variable arity parameters is not always a good idea. For example, given a method that does not accept an argument of a particular type, it could be possible to override the compile-time checking—through the use of generic variable arity parameters—so that the method would compile cleanly rather than correctly, causing a runtime error [
Bloch 2008
].
Also, note that autoboxing prevents strong compile-time type checking of primitive types and their corresponding wrapper classes. For instance, this compliant solution produces the following warning but works as expected:
Java.java:10: warning: [unchecked] Possible heap pollution from parameterized vararg type T
<T extends Number> double sum(T... args) { | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,460 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487460 | 3 | 1 | DCL59-J | Do not apply public final to constants whose value might change in later releases | The
final
keyword can be used to specify constant values (that is, values that cannot change during program execution). However, constants that can change over the lifetime of a program should not be declared public final.
The Java Language Specification
(JLS) [
JLS 2013
] allows implementations to insert the value of any public final field inline in any compilation unit that reads the field. Consequently, if the declaring class is edited so that the new version gives a different value for the field, compilation units that read the public final field could still see the old value until they are recompiled. This problem may occur, for example, when a third-party library is updated to the latest version but the referencing code is not recompiled.
A related error can arise when a programmer declares a
static final
reference to a mutable object (see
for additional information). | class Foo {
public static final int VERSION = 1;
// ...
}
class Bar {
public static void main(String[] args) {
System.out.println("You are using version " + Foo.VERSION);
}
}
You are using version 1
You are using version 1
## Noncompliant Code Example
In this noncompliant code example, class
Foo
in
Foo.java
declares a field whose value represents the version of the software:
#ffcccc
class Foo {
public static final int VERSION = 1;
// ...
}
The field is subsequently accessed by class
Bar
from a separate compilation unit (
Bar.java
):
#ffcccc
class Bar {
public static void main(String[] args) {
System.out.println("You are using version " + Foo.VERSION);
}
}
When compiled and run, the software correctly prints
You are using version 1
But if a developer were to change the value of
VERSION
to 2 by modifying
Foo.java
and subsequently recompile
Foo.java
while failing to recompile
Bar.java
, the software would incorrectly print
You are using version 1
Although recompiling
Bar.java
solves this problem, a better solution is available. | class Foo {
private static int version = 1;
public static final int getVersion() {
return version;
}
// ...
}
class Bar {
public static void main(String[] args) {
System.out.println(
"You are using version " + Foo.getVersion());
}
}
## Compliant Solution
According to
§13.4.9, "
final
Fields and Constants,"
of the JLS [
JLS 2013
],
Other than for true mathematical constants, we recommend that source code make very sparing use of class variables that are declared
static
and
final
. If the read-only nature of
final
is required, a better choice is to declare a
private static
variable and a suitable accessor method to get its value.
In this compliant solution, the version field in
Foo.java
is declared private static and accessed by the
getVersion()
method:
#ccccff
class Foo {
private static int version = 1;
public static final int getVersion() {
return version;
}
// ...
}
The
Bar
class in
Bar.java
is modified to invoke the
getVersion()
accessor method to retrieve the
version
field from
Foo.java
:
#ccccff
class Bar {
public static void main(String[] args) {
System.out.println(
"You are using version " + Foo.getVersion());
}
}
In this solution, the private version value cannot be copied into the
Bar
class when it is compiled, consequently preventing the bug. Note that this transformation imposes little or no performance penalty because most just-in-time (JIT) code generators can inline the
getVersion()
method at runtime. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,472 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487472 | 3 | 1 | DCL60-J | Avoid cyclic dependencies between packages | Both
The Elements of Java Style
[
Vermeulen 2000
] and the JPL Java Coding Standard [
Havelund 2010
] require that the dependency structure of a package must never contain cycles; that is, it must be representable as a directed acyclic graph (DAG).
Eliminating cycles between packages has several advantages:
Testing and maintainability.
Cyclic dependencies magnify the repercussions of changes or patches to source code. Reducing the repercussions of changes simplifies testing and improves maintainability. Inability to perform adequate testing because of cyclic dependencies is a frequent source of security vulnerabilities.
Reusability.
Cyclic dependencies between packages require that the packages be released and upgraded in lockstep. This requirement reduces reusability.
Releases and builds.
Avoiding cycles also helps to steer the development toward an environment that fosters modularization.
Deployment.
Avoiding cyclic dependencies between packages reduces coupling between packages. Reduced coupling reduces the frequency of runtime errors such as
ClassNotFoundError
. This, in turn, simplifies deployment. | package account;
import user.User;
public class AccountHolder {
private User user;
public void setUser(User newUser) {user = newUser;}
synchronized void depositFunds(String username, double amount) {
// Use a utility method of User to check whether username exists
if (user.exists(username)) {
// Deposit the amount
}
}
protected double getBalance(String accountNumber) {
// Return the account balance
return 1.0;
}
}
package user;
import account.AccountHolder;
public class UserDetails extends AccountHolder {
public synchronized double getUserBalance(String accountNumber) {
// Use a method of AccountHolder to get the account balance
return getBalance(accountNumber);
}
}
public class User {
public boolean exists(String username) {
// Check whether user exists
return true; // Exists
}
}
## Noncompliant Code Example
This noncompliant code example contains packages named
account
and
user
that consist of the classes
AccountHolder
,
User
, and
UserDetails
respectively. The class
UserDetails
extends from
AccountHolder
because a user is a kind of account holder. The class
AccountHolder
depends on a nonstatic utility method defined in the
User
class. Likewise, the
UserDetails
depends on
AccountHolder
by extending it.
#ffcccc
package account;
import user.User;
public class AccountHolder {
private User user;
public void setUser(User newUser) {user = newUser;}
synchronized void depositFunds(String username, double amount) {
// Use a utility method of User to check whether username exists
if (user.exists(username)) {
// Deposit the amount
}
}
protected double getBalance(String accountNumber) {
// Return the account balance
return 1.0;
}
}
package user;
import account.AccountHolder;
public class UserDetails extends AccountHolder {
public synchronized double getUserBalance(String accountNumber) {
// Use a method of AccountHolder to get the account balance
return getBalance(accountNumber);
}
}
public class User {
public boolean exists(String username) {
// Check whether user exists
return true; // Exists
}
} | package bank;
public interface BankApplication {
void depositFunds(BankApplication ba, String username, double amount);
double getBalance(String accountNumber);
double getUserBalance(String accountNumber);
boolean exists(String username);
}
package account;
import bank.BankApplication; // Import from a third package
class AccountHolder {
private BankApplication ba;
public void setBankApplication(BankApplication newBA) {
ba = newBA;
}
public synchronized void depositFunds(BankApplication ba,
String username, double amount) {
// Use a utility method of UserDetails
// to check whether username exists
if (ba.exists(username)) {
// Deposit the amount
}
}
public double getBalance(String accountNumber) {
// Return the account balance
return 1.0;
}
}
package user;
import account.AccountHolder; // One-way dependency
import bank.BankApplication; // Import from a third package
public class UserDetails extends AccountHolder
implements BankApplication {
public synchronized double getUserBalance(
String accountNumber) {
// Use a method of AccountHolder to get the account balance
return getBalance(accountNumber);
}
public boolean exists(String username) {
// Check whether user exists
return true;
}
}
## Compliant Solution
The tight coupling between the classes in the two packages can be weakened by introducing an interface called
BankApplication
in a third package,
bank
. The cyclic package dependency is eliminated by ensuring that the
AccountHolder
does not depend on
User
but instead relies on the interface by importing the
bank
package (and not by implementing the interface).
In this compliant solution, such functionality is achieved by adding a parameter of the interface type
BankApplication
to the
depositFunds()
method. This solution gives the
AccountHolder
a solid contract to bank on. Additionally,
UserDetails
implements the interface and provides concrete implementations of the methods while at the same time inheriting the other methods from
AccountHolder
.
#ccccff
package bank;
public interface BankApplication {
void depositFunds(BankApplication ba, String username, double amount);
double getBalance(String accountNumber);
double getUserBalance(String accountNumber);
boolean exists(String username);
}
package account;
import bank.BankApplication; // Import from a third package
class AccountHolder {
private BankApplication ba;
public void setBankApplication(BankApplication newBA) {
ba = newBA;
}
public synchronized void depositFunds(BankApplication ba,
String username, double amount) {
// Use a utility method of UserDetails
// to check whether username exists
if (ba.exists(username)) {
// Deposit the amount
}
}
public double getBalance(String accountNumber) {
// Return the account balance
return 1.0;
}
}
package user;
import account.AccountHolder; // One-way dependency
import bank.BankApplication; // Import from a third package
public class UserDetails extends AccountHolder
implements BankApplication {
public synchronized double getUserBalance(
String accountNumber) {
// Use a method of AccountHolder to get the account balance
return getBalance(accountNumber);
}
public boolean exists(String username) {
// Check whether user exists
return true;
}
}
The interface
BankApplication
appears to contain superfluous methods such as
depositFunds()
and
getBalance()
. These methods are present so that if the subclass overrides them, the superclass retains the capability of internally invoking the subclass's methods polymorphically (for example, calling
ba.getBalance()
with an overridden implementation of the method in
UserDetails
). One consequence of this solution is that methods declared in the interface are required to be public in the classes that define them. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,369 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487369 | 3 | 1 | DCL61-J | Do not use raw types | Under Construction
This guideline is under construction.
Mixing generically typed code with raw typed code is one common source of heap pollution. Prior to Java 5, all code used raw types. Allowing mixing enabled developers to preserve compatibility between non-generic legacy code and newer generic code. Using raw types with generic code causes most Java compilers to issue "unchecked" warnings but still compile the code. When generic and nongeneric types are used together correctly, these warnings can be ignored; at other times, these warnings can denote potentially unsafe operations.
According to the
Java Language Specification
,
§4.8, "Raw Types,"
[
JLS 2005
]:
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types. | class ListUtility {
private static void addToList(List list, Object obj) {
list.add(obj); // unchecked warning
}
public static void main(String[] args) {
List<String> list = new ArrayList<String> ();
addToList(list, 42);
System.out.println(list.get(0)); // throws ClassCastException
}
}
## Noncompliant Code Example
This noncompliant code example compiles but results in heap pollution. The compiler produces an unchecked warning because a raw argument (the
obj
parameter in the
addToList()
method) is passed to the
List.add()
method.
#FFCCCC
class ListUtility {
private static void addToList(List list, Object obj) {
list.add(obj); // unchecked warning
}
public static void main(String[] args) {
List<String> list = new ArrayList<String> ();
addToList(list, 42);
System.out.println(list.get(0)); // throws ClassCastException
}
}
Heap pollution is possible in this case because the parameterized type information is discarded prior to execution. The call to
addToList(list, 42)
succeeds in adding an integer to
list
although it is of type
List<String>
. This Java runtime does not throw a
ClassCastException
until the value is read and has an invalid type (an
int
rather than a
String
). In other words, the code throws an exception some time after the execution of the operation that actually caused the error, complicating debugging.
Even when heap pollution occurs, the variable is still guaranteed to refer to a subclass or subinterface of the declared type, but is not guaranteed to always refer to a subtype of its declared type. In this example,
list
does not
refer
to a subtype of its declared
type (
List<String>)
, but only
to the
subinterface
of the declared
type (
List
). | class ListUtility {
private static void addToList(List<String> list, String str) {
list.add(str); // No warning generated
}
public static void main(String[] args) {
List<String> list = new ArrayList<String> ();
addToList(list, "42");
System.out.println(list.get(0));
}
}
## Compliant Solution (Parameterized Collection)
## This compliant solution enforces type safety by changing theaddToList()method signature to enforce proper type checking.
#ccccff
class ListUtility {
private static void addToList(List<String> list, String str) {
list.add(str); // No warning generated
}
public static void main(String[] args) {
List<String> list = new ArrayList<String> ();
addToList(list, "42");
System.out.println(list.get(0));
}
}
The compiler prevents insertion of an
Object
to the parameterized
list
because
addToList()
cannot be called with an argument whose type produces a mismatch. This code has consequently been changed to add a
String
to the list instead of an
int
. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,809 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487809 | 2 | 16 | ENV00-J | Do not sign code that performs only unprivileged operations | Java uses code signing as a requirement for granting elevated privileges to code. Many
security policies
permit signed code to operate with elevated privileges. For example, Java applets can escape the default sandbox restrictions when signed. Consequently, users can grant explicit permissions either to a particular codebase or to all code signed by a particular signer. This approach places control of security in the hands of the user, who can choose whether to run an application with full or restricted permissions.
Signing code, however, has its own problems. According to Bruce Schneier [
Schneier 2000
]:
First, users have no idea how to decide if a particular signer is trusted or not. Second, just because a component is signed doesn't mean that it is safe. Third, just because two components are individually signed does not mean that using them together is safe; lots of accidental harmful interactions can be exploited. Fourth, "safe" is not an all-or-nothing thing; there are degrees of safety. And fifth, the fact that the evidence of attack (the signature on the code) is stored on the computer under attack is mostly useless: The attacker could delete or modify the signature during the attack, or simply reformat the drive where the signature is stored.
Code signing is designed to authenticate the origin of the code as well as to verify the integrity of the code. It relies on a certification authority (CA) to confirm the identity of the principal signer. Naive users should not be expected to understand how certificates and the public key infrastructure (PKI) work.
Users commonly associate digital signatures with safety of code execution, trusting the code to cause them no harm. The problem arises when a
vulnerability
is discovered in signed code. Because many systems are configured to permanently trust certain signing organizations, those systems fail to notify their users when downloading content signed by the trusted organization, even when that content contains vulnerabilities. An attacker can offer the users legitimately signed vulnerable content with the intention of
exploiting
that content.
Consider, for example, signed Java applets. When a certificate is verified, on widely used platforms, the user is presented with a security dialog in which the option "Always trust the content from the publisher" is selected by default. The dialog primarily asks whether or not the signed code should be executed. Unfortunately, if the user confirms the dialog with the check box selected, the "Always trust..." setting overrides any future warning dialogs. An attacker can take advantage of this mechanism by exploiting vulnerable code signed by the trusted organization. In this case, the code will execute with the user's implied permission and can be freely exploited.
An organization that signs its own code should not vouch for code acquired from a third party without carefully auditing the third-party code. When signing privileged code, ensure that all of the signed code is confined to a single JAR file (see
for more information) and also that any code invoked from the privileged code is also contained in that JAR file. Nonprivileged code must be left unsigned, restricting it to the sandbox. For example, unsigned applets and Java Network Launching Protocol (JNLP) applications are granted the minimum set of privileges and are restricted to the sandbox. Finally, never sign any code that is incomprehensible or unaudited.
## Exceptions
ENV00-J-EX1:
An organization that has an internal PKI and uses code signing for internal development activities (such as facilitating code check-in and tracking developer activity) may sign unprivileged code. This codebase should not be carried forward to a production environment. The keys used for internal signing must be distinct from those used to sign externally available code.
ENV00-J-EX2:
Oracle has deprecated the use of unsigned applets and will soon cease to support them. Applets that are signed have traditionally been run with full privileges. Since
Java 1.7.0 update 21
, Oracle has provided mechanisms to allow applets to be signed and yet run without full permissions. This enables applets that are today unsigned to continue to run in a security sandbox despite being signed. Signing an applet that runs with restricted privileges under versions of Java at least as recent as update 21 constitutes an exception to this rule. For more information, see
Signed Java Applet Security Improvements
on the CERT/CC blog. | null | null | ## Risk Assessment
Signing unprivileged code violates the principle of least privilege because it can circumvent security restrictions defined by the security policies of applets and JNLP applications, for example.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV00-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,914 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487914 | 2 | 16 | ENV01-J | Place all security-sensitive code in a single JAR and sign and seal it | In Java SE 6 and later, privileged code must either use the
AccessController
mechanism or be signed by an owner (or provider) whom the user trusts. Attackers could link privileged code with malicious code if the privileged code directly or indirectly invokes code from another package. Trusted JAR files often contain code that requires no elevated privileges itself but that depends on privileged code; such code is known as
security-sensitive code
. If an attacker can link security-sensitive code with malicious code, he or she can indirectly cause incorrect behavior. This exploit is called a
mix-and-match
attack.
Normally, execution of
untrusted code
causes loss of privileges; the Java security model rescinds privileges when a trusted method invokes an untrusted one. When
trusted code
calls untrusted code that attempts to perform some action requiring permissions withheld by the
security policy
, the Java security model disallows that action. However, privileged code may use a class that exists in an untrusted container and performs only unprivileged operations. If the attacker were to replace the class in the untrusted container with a malicious class, the trusted code might receive incorrect results and misbehave at the discretion of the malicious code.
According to the Java SE Documentation, "Extension Mechanism Architecture" [
EMA 2014
]:
A package sealed within a JAR specifies that all classes defined in that package must originate from the same JAR. Otherwise, a
SecurityException
is thrown.
Sealing a JAR file automatically enforces the requirement of keeping privileged code together. In addition, it is important to minimize the accessibility of classes and their members. | package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException, FileNotFoundException {
final FileInputStream fis = new FileInputStream("file.txt");
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
return null; // Nothing to return
}
}
);
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
}
package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
final FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream("file.txt");
}
}
);
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
}
## Noncompliant Code Example (Privileged Code)
This noncompliant code example includes a
doPrivileged()
block and calls a method defined in a class in a different, untrusted JAR file:
#FFcccc
package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException, FileNotFoundException {
final FileInputStream fis = new FileInputStream("file.txt");
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
return null; // Nothing to return
}
}
);
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
}
An attacker can provide an implementation of class
RetValue
so that the privileged code uses an incorrect return value. Even though class
MixMatch
consists only of trusted, signed code, an attacker can still cause this behavior by maliciously deploying a valid signed JAR file containing the untrusted
RetValue
class.
This example almost violates
but does not do so. It instead allows potentially tainted code in its
doPrivileged()
block, which is a similar issue.
## Noncompliant Code Example (Security-Sensitive Code)
This noncompliant code example improves on the previous example by moving the use of the
RetValue
class outside the
doPrivileged()
block:
#FFcccc
package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
final FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream("file.txt");
}
}
);
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
}
Although the
RetValue
class is used only outside the
doPrivileged()
block, the behavior of
RetValue.getValue()
affects the behavior of security-sensitive code that operates on the file opened within the
doPrivileged()
block. Consequently, an attacker can still
exploit
the security-sensitive code with a malicious implementation of
RetValue
. | package trusted;
public class MixMatch {
// ...
}
// In the same signed & sealed JAR file:
package trusted;
class RetValue {
int getValue() {
return 1;
}
}
Name: trusted/ // Package name
Sealed: true // Sealed attribute
## Compliant Solution
This compliant solution combines all security-sensitive code into the same package and the same JAR file. It also reduces the accessibility of the
getValue()
method to package-private. Sealing the package is necessary to prevent attackers from inserting any rogue classes.
#ccccff
package trusted;
public class MixMatch {
// ...
}
// In the same signed & sealed JAR file:
package trusted;
class RetValue {
int getValue() {
return 1;
}
}
To seal a package, use the
sealed
attribute in the JAR file's manifest file header, as follows:
Name: trusted/ // Package name
Sealed: true // Sealed attribute | ## Risk Assessment
Failure to place all privileged code together in one package and seal the package can lead to mix-and-match attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV01-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,852 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487852 | 2 | 16 | ENV02-J | Do not trust the values of environment variables | Deprecated
This guideline has been deprecated.
Both environment variables and system properties provide user-defined mappings between keys and their corresponding values and can be used to communicate those values from the environment to a process. According to the Java API [
API 2014
]
java.lang.System
class documentation:
Environment variables have a more global effect because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as
PATH
).
Programs that execute in a more trusted domain than their environment must assume that the values of environment variables are untrusted and must sanitize and validate any environment variable values before use.
The default values of system properties are set by the Java Virtual Machine (JVM) upon startup and can be considered trusted. However, they may be overridden by properties from untrusted sources, such as a configuration file. System properties from untrusted sources must be sanitized and validated before use.
The Java Tutorial
[
Campione 1996
] states:
To maximize portability, never refer to an environment variable when the same value is available in a system property. For example, if the operating system provides a user name, it will always be available in the system property
user.name
.
Actually, relying on environment variables is more than a portability issue. An attacker can essentially control all environment variables that enter a program using a mechanism such as the
java.lang.ProcessBuilder
class.
Consequently, when an environment variable contains information that is available by other means, including system properties, that environment variable must not be used. Finally, environment variables must not be used without appropriate validation. | String username = System.getenv("USER");
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Please supply a user name as the argument");
return;
}
String user = args[0];
ProcessBuilder pb = new ProcessBuilder();
pb.command("/usr/bin/printenv");
Map<String,String> environment = pb.environment();
environment.put("USER", user);
pb.redirectErrorStream(true);
try {
Process process = pb.start();
InputStream in = process.getInputStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
int exitVal = process.waitFor();
} catch (IOException x) {
// Forward to handler
} catch (InterruptedException x) {
// Forward to handler
}
}
## Noncompliant Code Example
## This noncompliant code example tries to get the user name, using an environment variable:
#ffcccc
String username = System.getenv("USER");
First, this is a portability issue.
The Java Tutorial
Campione 1996
further suggests:
The way environment variables are used also varies. For example, Windows provides the user name in an environment variable called
USERNAME
, while UNIX implementations might provide the user name in
USER
,
LOGNAME
, or both.
Second, an attacker can execute this program with the
USER
environment variable set to any value he or she chooses. The following code example does just that on a POSIX platform:
#ffcccc
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Please supply a user name as the argument");
return;
}
String user = args[0];
ProcessBuilder pb = new ProcessBuilder();
pb.command("/usr/bin/printenv");
Map<String,String> environment = pb.environment();
environment.put("USER", user);
pb.redirectErrorStream(true);
try {
Process process = pb.start();
InputStream in = process.getInputStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
int exitVal = process.waitFor();
} catch (IOException x) {
// Forward to handler
} catch (InterruptedException x) {
// Forward to handler
}
}
This program runs the POSIX
/usr/bin/printenv
command, which prints out all environment variables and their values. It takes a single argument string and sets the
USER
environment variable to that string. The subsequent output of the
printenv
program will indicate that the
USER
environment variable is set to the string requested. | String username = System.getProperty("user.name");
## Compliant Solution
This compliant solution obtains the user name using the
user.name
system property. The Java Virtual Machine (JVM), upon initialization, sets this system property to the correct user name, even when the
USER
environment variable has been set to an incorrect value or is missing.
#ccccff
String username = System.getProperty("user.name"); | ## Risk Assessment
Untrusted environment variables can provide data for injection and other attacks if not properly
sanitized
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV02-J
Low
Likely
Yes
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,671 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487671 | 2 | 16 | ENV03-J | Do not grant dangerous combinations of permissions | Certain combinations of permissions can produce significant capability increases and should not be granted. Other permissions should be granted only to special code.
AllPermission
The permission
java.security.AllPermission
grants all possible permissions to code. This facility was included to reduce the burden of managing a multitude of permissions during routine testing as well as when a body of code is completely trusted. Code is typically granted
AllPermission
via the
security policy
file; it is also possible to programmatically associate
AllPermission
with a
ProtectionDomain
. This permission is dangerous in production environments. Never grant
AllPermission
to
untrusted code
.
ReflectPermission
,
suppressAccessChecks
Granting
ReflectPermission
on the target
suppressAccessChecks
suppresses all standard Java language access checks when the permitted class attempts to operate on package-private, protected, or private members of another class. Consequently, the permitted class can obtain permissions to examine any field or invoke any method belonging to an arbitrary class [
Reflect 2006
]. As a result,
ReflectPermission
must never be granted with target
suppressAccessChecks
.
According to the technical note
Permissions in the Java SE 6 Development Kit
[
Permissions 2008
], Section
ReflectPermission
, target
suppressAccessChecks
:
Warning
:
Extreme caution should be taken before granting this permission to code
, for it provides the ability to access fields and invoke methods in a class. This includes not only public, but protected and private fields and methods as well.
RuntimePermission
,
createClassLoader
The permission
java.lang.RuntimePermission
applied to target
createClassLoader
grants code the permission to create a
ClassLoader
object. This permission is extremely dangerous because malicious code can create its own custom class loader and load classes by assigning them arbitrary permissions. A custom class loader can define a class (or
ProtectionDomain
) with permissions that override any restrictions specified in the systemwide security policy file.
Permissions in the Java SE 6 Development Kit
[
Permissions 2008
] states:
This is an extremely dangerous permission to grant. Malicious applications that can instantiate their own class loaders could then load their own rogue classes into the system. These newly loaded classes could be placed into any protection domain by the class loader, thereby automatically granting the classes the permissions for that domain. | // Grant the klib library AllPermission
grant codebase "file:${klib.home}/j2se/home/klib.jar" {
permission java.security.AllPermission;
};
protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
pc.add(new ReflectPermission("suppressAccessChecks")); // Permission to create a class loader
// Other permissions
return pc;
}
## Noncompliant Code Example (Security Policy File)
## This noncompliant example grantsAllPermissionto thekliblibrary:
#FFcccc
// Grant the klib library AllPermission
grant codebase "file:${klib.home}/j2se/home/klib.jar" {
permission java.security.AllPermission;
};
The permission itself is specified in the
security policy
file used by the security manager. Program code can obtain a permission object by subclassing the
java.security.Permission
class or any of its subclasses (
BasicPermission
, for example). The code can use the resulting object to grant
AllPermission
to a
ProtectionDomain
.
## Noncompliant Code Example (PermissionCollection)
This noncompliant code example shows an overridden
getPermissions()
method, defined in a custom class loader. It grants
java.lang.ReflectPermission
with target
suppressAccessChecks
to any class that it loads.
#FFcccc
protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
pc.add(new ReflectPermission("suppressAccessChecks")); // Permission to create a class loader
// Other permissions
return pc;
} | grant codeBase
"file:${klib.home}/j2se/home/klib.jar", signedBy "Admin" {
permission java.io.FilePermission "/tmp/*", "read";
permission java.io.SocketPermission "*", "connect";
};
// Security manager check
FilePermission perm =
new java.io.FilePermission("/tmp/JavaFile", "read");
AccessController.checkPermission(perm);
// ...
protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
// Other permissions
return pc;
}
## Compliant Solution
## This compliant solution shows a policy file that can be used to enforce fine-grained permissions:
#ccccff
grant codeBase
"file:${klib.home}/j2se/home/klib.jar", signedBy "Admin" {
permission java.io.FilePermission "/tmp/*", "read";
permission java.io.SocketPermission "*", "connect";
};
To check whether the caller has the requisite permissions, standard Java APIs use code such as the following:
#ccccff
// Security manager check
FilePermission perm =
new java.io.FilePermission("/tmp/JavaFile", "read");
AccessController.checkPermission(perm);
// ...
Always assign appropriate permissions to code. Define custom permissions when the granularity of the standard permissions is insufficient.
## Compliant Solution
This compliant solution does not grant
java.lang.ReflectPermission
with target
suppressAccessChecks
to any class that it loads:
#ccccff
protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
// Other permissions
return pc;
} | ## Risk Assessment
Granting
AllPermission
to
untrusted code
allows it to perform privileged operations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV03-J
High
Likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,890 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487890 | 2 | 16 | ENV04-J | Do not disable bytecode verification | When Java source code is compiled, it is converted into bytecode, saved in one or more class files, and executed by the Java Virtual Machine (JVM). Java class files may be compiled on one machine and executed on another machine. A properly generated class file is said to be
conforming
. When the JVM loads a class file, it has no way of knowing whether the class file is conforming. The class file could have been created by some other process, or an attacker may have tampered with a conforming class file.
The Java bytecode verifier is an internal component of the JVM that is responsible for detecting nonconforming Java bytecode. It ensures that the class file is in the proper Java class format, that illegal type casts are avoided, that operand stack underflows are impossible, and that each method eventually removes from the operand stack everything pushed by that method.
Users often assume that Java class files obtained from a trustworthy source will be conforming and, consequently, safe for execution. This belief can erroneously lead them to see bytecode verification as a superfluous activity for such classes. Consequently, they might disable bytecode verification, undermining Java's safety and security guarantees. The bytecode verifier must not be suppressed. | java -Xverify:none ApplicationName
## Noncompliant Code Example
The bytecode verification process runs by default. The
-Xverify:none
flag on the JVM command line suppresses the verification process. This noncompliant code example uses the flag to disable bytecode verification:
#FFcccc
java -Xverify:none ApplicationName | java -Xverify:all ApplicationName
## Compliant Solution
Most JVM implementations perform bytecode verification by default; it is also performed during dynamic class loading.
Specifying the
-Xverify:all
flag on the command line requires the JVM to enable bytecode verification (even when it would otherwise have been suppressed), as shown in this compliant solution:
#ccccff
java -Xverify:all ApplicationName | ## Risk Assessment
Bytecode verification ensures that the bytecode contains many of the security checks mandated by the
Java Language Specification
. Omitting the verification step could permit execution of insecure Java code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV04-J
High
Likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,615 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487615 | 2 | 16 | ENV05-J | Do not deploy an application that can be remotely monitored | Java provides several APIs that allow external programs to monitor a running Java program. These APIs also permit the Java program to be monitored remotely by programs on distinct hosts. Such features are convenient for debugging the program or fine-tuning its performance. However, if a Java program is deployed in production with remote monitoring enabled, an attacker can connect to the Java Virtual Machine (JVM) and inspect its behavior and data, including potentially sensitive information. An attacker can also exert control over the program's behavior. Consequently, remote monitoring must be disabled when running a Java program in production.
## JVM Tool Interface (JVMTI)
Java 5 introduced the JVM Tool Interface (JVMTI) [
Sun 04d
], replacing both the JVM Profiler Interface (JVMPI) and the JVM Debug Interface (JVMDI), which are now deprecated.
The JVMTI contains extensive facilities to learn about the internals of a running JVM, including facilities to monitor and modify a running Java program. These facilities are rather low level and require the use of the Java Native Interface (JNI) and C language programming. However, they provide the opportunity to access fields that would normally be inaccessible. Also, there are facilities that can change the behavior of a running Java program (for example, threads can be suspended or stopped). The JVMTI profiling tools can also measure the time that a thread takes to execute, leaving applications vulnerable to timing attacks.
The JVMTI works by using agents that communicate with the running JVM. These agents must be loaded at JVM startup and are usually specified via one of the command-line options
-agentlib
or
-agentpath
. However, agents can be specified in environment variables, although this feature can be disabled where security is a concern. The JVMTI is always enabled, and JVMTI agents may run under the default security manager without requiring any permissions to be granted.
## Java Platform Debugger Architecture (JPDA)
The Java Platform Debugger Architecture (JPDA) builds on the JVMTI and provides high-level facilities for debugging Java systems while they are running [
JPDA 2004
].
The JPDA facilities are similar to the reflection API, which is described in
. In particular, the JPDA provides methods to get and set field and array values. Access control is not enforced, so even the values of private fields can be set by a remote process via the JPDA.
Various permissions must be granted for debugging to take place under the default security manager. The following policy file was used to run the JPDA Trace demonstration under the default security manager:
grant {
permission java.io.FilePermission "traceoutput.txt", "read,write";
permission java.io.FilePermission "C:/Program Files/Java/jdk1.5.0_04/lib/tools.jar", "read";
permission java.io.FilePermission "C:/Program", "read,execute";
permission java.lang.RuntimePermission "modifyThread";
permission java.lang.RuntimePermission "modifyThreadGroup";
permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
permission java.lang.RuntimePermission "loadLibrary.dt_shmem";
permission java.util.PropertyPermission "java.home", "read";
permission java.net.SocketPermission "<localhost>", "resolve";
permission com.sun.jdi.JDIPermission "virtualMachineManager";
};
Because JPDA supports remote debugging, a remote host can access the debugger. An attacker can
exploit
this feature to study sensitive information or modify the behavior of a running Java application unless appropriate protection is enabled. A security manager can ensure that only known, trusted hosts are given permissions to use the debugger interface.
## Java SE Monitoring and Management Features
Java contains extensive facilities for monitoring and managing a JVM [
JMX 2006
]. In particular, the Java Management Extension (JMX) API enables the monitoring and control of class loading, thread state and stack traces,
deadlock
detection, memory usage, garbage collection, operating system information, and other operations [
Sun 04a
]. It also has facilities for logging monitoring and management.
The Java SE monitoring and management features fall into four broad categories:
The JMX technology:
This technology serves as the underlying interface for local and remote monitoring and management.
Instrumentation for the JVM:
These facilities enable out-of-the-box monitoring and management of the JVM and are based on the JMX specification.
Monitoring and management API:
These facilities use the
java.lang.management
package to provide the monitoring and management interface. Applications can use this package to monitor themselves or to let JMX technology–compliant tools monitor and manage them.
Monitoring and management tools:
Tools such as JConsole implement the JMX interface to provide monitoring and management facilities.
These facilities can be used either locally (on the machine that runs the JVM) or remotely. Local monitoring and management is enabled by default when a JVM is started; remote monitoring and management is not. For a JVM to be monitored and managed remotely, it must be started with various system properties set (either on the command line or in a configuration file).
When remote monitoring and management is enabled, access is password-controlled by default. However, password control can be disabled. Disabling password authentication is insecure because any user who can discover the port number that the JMX service is listening on can monitor and control the Java applications running on the JVM [
JMXG 2006
].
The JVM remote monitoring and management facility uses a secure communication channel (Secure Sockets Layer
[SSL]
) by default. However, if an attacker can start a bogus remote method invocation (RMI) registry server on the monitored machine before the legitimate RMI registry server is started, JMX passwords can be intercepted. Also, SSL can be disabled when using remote monitoring and management, which could, again, compromise security. See
The Java SE Monitoring and Management Guide
[
JMXG 2006
] for further details and for mitigation strategies.
There are also provisions to require proper authentication of the remote server. However, users may start a JVM with remote monitoring and management enabled but with no security; this would leave the JVM open to attack by outsiders. Although accidentally enabling remote monitoring and management is unlikely, users might not realize that starting a JVM so enabled, without any security, could leave their JVM exposed to attack.
If exploited, the monitoring and management facilities can seriously compromise the security of Java applications. For example, an attacker can obtain information about the number of classes loaded and threads running, thread state along with traces of live threads, system properties, virtual machine arguments, and memory consumption. | ${JDK_PATH}/bin/java -agentlib:libname=options ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_shmem,
address=mysharedmemory ApplicationName
${JDK_PATH}/bin/java
-Dcom.sun.management.jmxremote.port=8000 ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=y,address=9000 ApplicationName
## Noncompliant Code Example (JVMTI)
In this noncompliant code example, the JVMTI works by using agents that communicate with the running JVM. These agents are usually loaded at JVM startup via one of the command-line options
-agentlib
or
-agentpath
. In the following command,
libname
is the name of the library to load while
options
are passed to the agent on startup.
#FFcccc
${JDK_PATH}/bin/java -agentlib:libname=options ApplicationName
Some JVMs allow agents to be started when the JVM is already running. This practice is insecure in a production environment. Refer to the JVMTI documentation [
JVMTI 2006
] for platform-specific information on enabling/disabling this feature.
Platforms that support environment variables allow agents to be specified in such variables. "Platforms may disable this feature in cases where security is a concern; for example, the Reference Implementation disables this feature on UNIX systems when the effective user or group ID differs from the real ID" [
JVMTI 2006
].
Agents may run under the default security manager without requiring any permissions to be granted. Although the JVMTI is useful for debuggers and profilers, such levels of access are inappropriate for deployed production code.
## Noncompliant Code Example (JPDA)
This noncompliant code example uses command-line arguments to invoke the JVM so that it can be debugged from a running debugger application by listening for connections using shared memory at transport address
mysharedmemory
:
#FFcccc
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_shmem,
address=mysharedmemory ApplicationName
Likewise, the command-line arguments
-Xrunjdwp
(which is equivalent to
-agentlib
) and
-Xdebug
(which is used by the
jdb
tool) also enable application debugging.
## Noncompliant Code Example (JVM monitoring)
This noncompliant code example invokes the JVM with command-line arguments that permit remote monitoring via port 8000. This invocation may result in a security
vulnerability
when the password is weak or the SSL protocol is misapplied.
#FFcccc
${JDK_PATH}/bin/java
-Dcom.sun.management.jmxremote.port=8000 ApplicationName
## Noncompliant Code Example (Remote Debugging)
Remote debugging requires the use of sockets as the transport (
transport=dt_socket
). Remote debugging also requires specification of the type of application (
server
=
y
, where
y
denotes that the JVM is the server and is waiting for a debugger application to connect to it) and the port number to listen on (
address
=9000).
#FFcccc
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=y,address=9000 ApplicationName
Remote debugging is dangerous because an attacker can spoof the client IP address and connect to the JPDA host. Depending on the attacker's position in the network, he or she could extract debugging information by sniffing the network traffic that the JPDA host sends to the forged IP address. | ${JDK_PATH}/bin/java -Djava.security.manager ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=n,address=9000 ApplicationName
## Compliant Solution
This compliant solution starts the JVM without any agents enabled. Avoid using the
-agentlib
,
-Xrunjdwp
, and
-Xdebug
command-line arguments on production machines. This compliant solution also installs the default security manager.
#ccccff
${JDK_PATH}/bin/java -Djava.security.manager ApplicationName
Clear the environment variable
JAVA_TOOL_OPTIONS
in the manner appropriate for your platform, for example, by setting it to an empty string value. Doing prevents JVMTI agents from receiving arguments via this mechanism. The command-line argument
-Xnoagent
can also be used to disable the debugging features supported by the old Java debugger (
oldjdb
).
This compliant solution disables monitoring by remote machines. By default, local monitoring is enabled in Java 6 and later. In earlier versions, the system property
com.sun.management.jmxremote
must be set to enable local monitoring. Although the unsupported
-XX:+DisableAttachMechanism
command-line option may be used to disable local Java tools from monitoring the JVM, it is always possible to use native debuggers and other tools to perform monitoring. Fortunately, monitoring tools require at least as many privileges as the owner of the JVM process possesses, reducing the threat of a local privilege escalation attack.
Local monitoring uses temporary files and sets the file permissions to those of the owner of the JVM process. Ensure that adequate file protection is in place on the system running the JVM so that the temporary files are accessed appropriately (see
for additional information).
The
Java SE Monitoring and Management Guide
[
JMXG 2006
] provides further advice:
Local monitoring with
jconsole
is useful for development and prototyping. Using
jconsole
locally is not recommended for production environments because
jconsole
itself consumes significant system resources. Rather, use
jconsole
on a remote system to isolate it from the platform being monitored.
Moving
jconsole
to a remote system removes its system resource load from the production environment.
## Compliant Solution (Remote Debugging)
Restrict remote debugging to trusted hosts by modifying the
security policy
file to grant appropriate permissions only to those trusted hosts. For example, specify the permission
java.net.SocketPermission
for only the JPDA host and remove the permission from other hosts.
The JPDA host can serve either as a server or as a client. When the attacker cannot sniff the network to determine the identity of machines that use the JPDA host (for example, through the use of a secure channel), specify the JPDA host as the client and the debugger application as the server by changing the value of the
server
argument to
n
.
## This compliant solution allows the JPDA host to attach to a trusted debugger application:
#ccccff
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=n,address=9000 ApplicationName
When it is necessary to run a JVM with debugging enabled, avoid granting permissions that are not needed by the application. In particular, avoid granting socket permissions to arbitrary hosts; that is, omit the permission
java.net.SocketPermission "*", "connect,accept"
. | ## Risk Assessment
Deploying a Java application with the JVMTI, JPDA, or remote monitoring enabled can allow an attacker to monitor or modify its behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV05-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,339 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487339 | 2 | 16 | ENV06-J | Production code must not contain debugging entry points | According to
J2EE Bad Practices: Leftover Debug Code
[
Hewlett-Packard 2015
]:
A common development practice is to add "back door" code specifically designed for debugging or testing purposes that is not intended to be shipped or deployed with the application. When this sort of debug code is accidentally left in the application, the application is open to unintended modes of interaction. These back door entry points create security risks because they are not considered during design or testing and fall outside of the expected operating conditions of the application.
The most common example of forgotten debug code is a
main()
method appearing in a web application. Although this is an acceptable practice during product development, classes that are part of a production J2EE application should not define a
main()
. | class Stuff {
private static final bool DEBUG = False;
// Other fields and methods
public static void main(String args[]) {
Stuff.DEBUG = True;
Stuff stuff = new Stuff();
// Test stuff
}
}
## Noncompliant Code Example
In this noncompliant code example, the
Stuff
class has a
main()
function that tests its methods. Although useful for debugging, if this function is left in production code (for a web application, for example), an attacker can invoke
Stuff.main()
directly, gaining access to
Stuff
's test methods.
#FFcccc
class Stuff {
private static final bool DEBUG = False;
// Other fields and methods
public static void main(String args[]) {
Stuff.DEBUG = True;
Stuff stuff = new Stuff();
// Test stuff
}
} | ## Compliant Solution
## A compliant solution simply removes themain()method from theStuffclass, depriving attackers of this entry point. | ## Risk Assessment
Leaving extra entry points into production code could allow an attacker to gain special access to the program.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV06-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,876 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487876 | 2 | 7 | ERR00-J | Do not suppress or ignore checked exceptions | Programmers often suppress checked exceptions by catching exceptions with an empty or trivial
catch
block. Each
catch
block must ensure that the program continues only with valid
invariants
. Consequently, the
catch
block must either recover from the exceptional condition, rethrow the exception to allow the next nearest enclosing
catch
clause of a
try
statement to recover, or throw an exception that is appropriate to the context of the
catch
block.
Exceptions disrupt the expected control flow of the application. For example, no part of any expression or statement that occurs in the
try
block after the point from which the exception is thrown is evaluated. Consequently, exceptions must be handled appropriately. Many reasons for suppressing exceptions are invalid. For example, when the client cannot be expected to recover from the underlying problem, it is good practice to allow the exception to propagate outwards rather than to catch and suppress the exception. | try {
//...
} catch (IOException ioe) {
ioe.printStackTrace();
}
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
## Noncompliant Code Example
## This noncompliant code example simply prints the exception's stack trace:
#FFCCCC
try {
//...
} catch (IOException ioe) {
ioe.printStackTrace();
}
Printing the exception's stack trace can be useful for debugging purposes, but the resulting program execution is equivalent to suppressing the exception. Printing the stack trace can also leak information about the structure and state of the process to an attacker (see
for more information). Note that even though this noncompliant code example reacts to the exception by printing out a stack trace, it then proceeds as though the exception were not thrown. That is, the behavior of the application is unaffected by the exception being thrown except that any expressions or statements that occur in the
try
block after the point from which the exception is thrown are not evaluated.
## Noncompliant Code Example
If a thread is interrupted while sleeping or waiting, it causes a
java.lang.InterruptedException
to be thrown. However, the
run()
method of interface
Runnable
cannot throw a checked exception and must handle
InterruptedException
. This noncompliant code example catches and suppresses
InterruptedException
:
#FFCCCC
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
This code prevents callers of the
run()
method from determining that an interrupted exception occurred. Consequently, caller methods such as
Thread.start()
cannot act on the exception [
Goetz 2006
]. Likewise, if this code were called in its own thread, it would prevent the calling thread from knowing that the thread was interrupted. | boolean validFlag = false;
do {
try {
// ...
// If requested file does not exist, throws FileNotFoundException
// If requested file exists, sets validFlag to true
validFlag = true;
} catch (FileNotFoundException e) {
// Ask the user for a different file name
}
} while (validFlag != true);
// Use the file
public interface Reporter {
public void report(Throwable t);
}
class ExceptionReporterPermission extends Permission {
// ...
}
public class ExceptionReporter {
// Exception reporter that prints the exception
// to the console (used as default)
private static final Reporter PrintException = new Reporter() {
public void report(Throwable t) {
System.err.println(t.toString());
}
};
// Stores the default reporter
// The default reporter can be changed by the user
private static Reporter Default = PrintException;
// Helps change the default reporter back to
// PrintException in the future
public static Reporter getPrintException() {
return PrintException;
}
public static Reporter getExceptionReporter() {
return Default;
}
// May throw a SecurityException (which is unchecked)
public static void setExceptionReporter(Reporter reporter) {
// Custom permission
ExceptionReporterPermission perm = new
ExceptionReporterPermission("exc.reporter");
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Check whether the caller has appropriate permissions
sm.checkPermission(perm);
}
// Change the default exception reporter
Default = reporter;
}
}
try {
// ...
} catch (IOException warning) {
ExceptionReporter.getExceptionReporter().report(warning);
// Recover from the exception...
}
ExceptionReporter.setExceptionReporter(new ExceptionReporter() {
public void report(Throwable exception) {
JOptionPane.showMessageDialog(frame,
exception.toString,
exception.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
}});
class MyExceptionReporter extends ExceptionReporter {
private static final Logger logger =
Logger.getLogger("com.organization.Log");
public static void report(Throwable t) {
t = filter(t);
if (t != null) {
logger.log(Level.FINEST, "Loggable exception occurred", t);
}
}
public static Exception filter(Throwable t) {
if (t instanceof SensitiveException1) {
// Too sensitive, return nothing (so that no logging happens)
return null;
} else if (t instanceof SensitiveException2) {
// Return a default insensitive exception instead
return new FilteredSensitiveException(t);
}
// ...
// Return for reporting to the user
return t;
}
}
// ...Definitions for SensitiveException1, SensitiveException2
// and FilteredSensitiveException...
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
}
## Compliant Solution (Interactive)
## This compliant solution handles aFileNotFoundExceptionby requesting that the user specify another file name:
#ccccff
boolean validFlag = false;
do {
try {
// ...
// If requested file does not exist, throws FileNotFoundException
// If requested file exists, sets validFlag to true
validFlag = true;
} catch (FileNotFoundException e) {
// Ask the user for a different file name
}
} while (validFlag != true);
// Use the file
To comply with
, the user should only be allowed to access files in a user-specific directory. This prevents any other
IOException
that escapes the loop from leaking sensitive file system information.
## Compliant Solution (Exception Reporter)
Proper reporting of exceptional conditions is context-dependent. For example, GUI applications should report the exception in a graphical manner, such as in an error dialog box. Most library classes should be able to objectively determine how an exception should be reported to preserve modularity; they cannot rely on
System.err
, on any particular logger, or on the availability of the windowing environment. As a result, library classes that wish to report exceptions should specify the API they use to report exceptions. This compliant solution specifies both an interface for reporting exceptions, which exports the
report()
method, and a default exception reporter class that the library can use. The exception reporter can be overridden by subclasses.
#ccccff
public interface Reporter {
public void report(Throwable t);
}
class ExceptionReporterPermission extends Permission {
// ...
}
public class ExceptionReporter {
// Exception reporter that prints the exception
// to the console (used as default)
private static final Reporter PrintException = new Reporter() {
public void report(Throwable t) {
System.err.println(t.toString());
}
};
// Stores the default reporter
// The default reporter can be changed by the user
private static Reporter Default = PrintException;
// Helps change the default reporter back to
// PrintException in the future
public static Reporter getPrintException() {
return PrintException;
}
public static Reporter getExceptionReporter() {
return Default;
}
// May throw a SecurityException (which is unchecked)
public static void setExceptionReporter(Reporter reporter) {
// Custom permission
ExceptionReporterPermission perm = new
ExceptionReporterPermission("exc.reporter");
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Check whether the caller has appropriate permissions
sm.checkPermission(perm);
}
// Change the default exception reporter
Default = reporter;
}
}
The
setExceptionReporter()
method prevents hostile code from maliciously installing a more verbose reporter that leaks sensitive information or that directs exception reports to an inappropriate location, such as the attacker's computer, by limiting attempts to change the exception reporter to callers that have the custom permission
ExceptionReporterPermission
with target
exc.reporter
.
The library may subsequently use the exception reporter in
catch
clauses:
#ccccff
try {
// ...
} catch (IOException warning) {
ExceptionReporter.getExceptionReporter().report(warning);
// Recover from the exception...
}
Any client code that possesses the required permissions can override the
ExceptionReporter
with a handler that logs the error or provides a dialog box, or both. For example, a GUI client using Swing may require exceptions to be reported using a dialog box:
#ccccff
ExceptionReporter.setExceptionReporter(new ExceptionReporter() {
public void report(Throwable exception) {
JOptionPane.showMessageDialog(frame,
exception.toString,
exception.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
}});
## Compliant Solution (Subclass Exception Reporter and Filter-Sensitive Exceptions)
Sometimes exceptions must be hidden from the user for security reasons (see
). In such cases, one acceptable approach is to subclass the
ExceptionReporter
class and add a
filter()
method in addition to overriding the default
report()
method.
#ccccff
class MyExceptionReporter extends ExceptionReporter {
private static final Logger logger =
Logger.getLogger("com.organization.Log");
public static void report(Throwable t) {
t = filter(t);
if (t != null) {
logger.log(Level.FINEST, "Loggable exception occurred", t);
}
}
public static Exception filter(Throwable t) {
if (t instanceof SensitiveException1) {
// Too sensitive, return nothing (so that no logging happens)
return null;
} else if (t instanceof SensitiveException2) {
// Return a default insensitive exception instead
return new FilteredSensitiveException(t);
}
// ...
// Return for reporting to the user
return t;
}
}
// ...Definitions for SensitiveException1, SensitiveException2
// and FilteredSensitiveException...
The
report()
method accepts a
Throwable
instance and consequently handles all errors, checked exceptions, and unchecked exceptions. The filtering mechanism is based on a
whitelisting
approach wherein only nonsensitive exceptions are propagated to the user. Exceptions that are forbidden to appear in a log file can be filtered in the same fashion (see
). This approach provides the benefits of exception chaining by reporting exceptions tailored to the abstraction while also logging the low-level cause for future failure analysis [
Bloch 2008
].
## Compliant Solution
This compliant solution catches the
InterruptedException
and restores the interrupted status by calling the
interrupt()
method on the current thread:
#ccccff
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
}
Consequently, calling methods (or code from a calling thread) can determine that an interrupt was issued [
Goetz 2006
]. | ## Risk Assessment
Ignoring or suppressing exceptions can result in inconsistent program state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR00-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,679 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487679 | 2 | 7 | ERR01-J | Do not allow exceptions to expose sensitive information | Failure to filter sensitive information when propagating exceptions often results in information leaks that can assist an attacker's efforts to develop further exploits. An attacker may craft input arguments to expose internal structures and mechanisms of the application. Both the exception message text and the type of an exception can leak information. For example, the
FileNotFoundException
message reveals information about the file system layout, and the exception type reveals the absence of the requested file.
This rule applies to server-side applications as well as to clients. Attackers can glean sensitive information not only from vulnerable web servers but also from victims who use vulnerable web browsers. In 2004, Sch
ö
nefeld discovered an
exploit
for the Opera v7.54 web browser in which an attacker could use the
sun.security.krb5.Credentials
class in an applet as an oracle to "retrieve the name of the currently logged in user and parse his home directory from the information which is provided by the thrown
java.security.AccessControlException
" [
Sch
ö
nefeld 2004
].
All exceptions reveal information that can assist an attacker's efforts to carry out a
denial of service
(DoS) against the system. Consequently, programs must filter both exception messages and exception types that can propagate across trust boundaries. The following table lists several problematic exceptions.
Exception Name
Description of Information Leak or Threat
java.io.FileNotFoundException
Underlying file system structure, user name enumeration
java.sql.SQLException
Database structure, user name enumeration
java.net.BindException
Enumeration of open ports when untrusted client can choose server port
java.util.ConcurrentModificationException
May provide information about thread-unsafe code
javax.naming.InsufficientResourcesException
Insufficient server resources (may aid DoS)
java.util.MissingResourceException
Resource enumeration
java.util.jar.JarException
Underlying file system structure
java.security.acl.NotOwnerException
Owner enumeration
java.lang.OutOfMemoryError
DoS
java.lang.StackOverflowError
DoS
Printing the stack trace can also result in unintentionally leaking information about the structure and state of the process to an attacker. When a Java program that is run within a console terminates because of an uncaught exception, the exception's message and stack trace are displayed on the console; the stack trace may itself contain sensitive information about the program's internal structure. Consequently, any program that may be run on a console accessible to an untrusted user must never abort due to an uncaught exception. | class ExceptionExample {
public static void main(String[] args) throws FileNotFoundException {
// Linux stores a user's home directory path in
// the environment variable $HOME, Windows in %APPDATA%
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
}
}
try {
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
} catch (FileNotFoundException e) {
// Log the exception
throw new IOException("Unable to retrieve file", e);
}
class SecurityIOException extends IOException {/* ... */};
try {
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
} catch (FileNotFoundException e) {
// Log the exception
throw new SecurityIOException();
}
## Noncompliant Code Example (Leaks from Exception Message and Type)
In this noncompliant code example, the program must read a file supplied by the user, but the contents and layout of the file system are sensitive. The program accepts a file name as an input argument but fails to prevent any resulting exceptions from being presented to the user.
#FFcccc
class ExceptionExample {
public static void main(String[] args) throws FileNotFoundException {
// Linux stores a user's home directory path in
// the environment variable $HOME, Windows in %APPDATA%
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
}
}
When a requested file is absent, the
FileInputStream
constructor throws a
FileNotFoundException
, allowing an attacker to reconstruct the underlying file system by repeatedly passing fictitious path names to the program.
## Noncompliant Code Example (Wrapping and Rethrowing Sensitive Exception)
## This noncompliant code example logs the exception and then wraps it in a more general exception before rethrowing it:
#FFcccc
try {
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
} catch (FileNotFoundException e) {
// Log the exception
throw new IOException("Unable to retrieve file", e);
}
Even when the logged exception is not accessible to the user, the original exception is still informative and can be used by an attacker to discover sensitive information about the file system layout.
Note that this example also violates
, as it fails to close the input stream in a
finally
block. Subsequent code examples also omit this
finally
block for brevity.
## Noncompliant Code Example (Sanitized Exception)
This noncompliant code example logs the exception and throws a custom exception that does not wrap the
FileNotFoundException
:
#FFcccc
class SecurityIOException extends IOException {/* ... */};
try {
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
} catch (FileNotFoundException e) {
// Log the exception
throw new SecurityIOException();
}
Although this exception is less likely than the previous noncompliant code examples to leak useful information, it still reveals that the specified file cannot be read. More specifically, the program reacts differently to nonexistent file paths than it does to valid ones, and an attacker can still infer sensitive information about the file system from this program's behavior. Failure to restrict user input leaves the system vulnerable to a brute-force attack in which the attacker discovers valid file names by issuing queries that collectively cover the space of possible file names. File names that cause the program to return the
sanitized
exception indicate nonexistent files, whereas file names that do not return exceptions reveal existing files. | class ExceptionExample {
public static void main(String[] args) {
File file = null;
try {
file = new File(System.getenv("APPDATA") +
args[0]).getCanonicalFile();
if (!file.getPath().startsWith("c:\\homepath")) {
System.out.println("Invalid file");
return;
}
} catch (IOException x) {
System.out.println("Invalid file");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
} catch (FileNotFoundException x) {
System.out.println("Invalid file");
return;
}
}
}
class ExceptionExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
switch(Integer.valueOf(args[0])) {
case 1:
fis = new FileInputStream("c:\\homepath\\file1");
break;
case 2:
fis = new FileInputStream("c:\\homepath\\file2");
break;
//...
default:
System.out.println("Invalid option");
break;
}
} catch (Throwable t) {
MyExceptionReporter.report(t); // Sanitize
}
}
}
## Compliant Solution (Security Policy)
This compliant solution implements the policy that only files that live in
c:\homepath
may be opened by the user and that the user is not allowed to discover anything about files outside this directory. The solution issues a terse error message when the file cannot be opened or the file does not live in the proper directory. Any information about files outside
c:\homepath
is concealed.
The compliant solution also uses the
File.getCanonicalFile()
method to
canonicalize
the file to simplify subsequent path name comparisons (see
for more information).
#ccccff
class ExceptionExample {
public static void main(String[] args) {
File file = null;
try {
file = new File(System.getenv("APPDATA") +
args[0]).getCanonicalFile();
if (!file.getPath().startsWith("c:\\homepath")) {
System.out.println("Invalid file");
return;
}
} catch (IOException x) {
System.out.println("Invalid file");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
} catch (FileNotFoundException x) {
System.out.println("Invalid file");
return;
}
}
}
## Compliant Solution (Restricted Input)
This compliant solution operates under the policy that only
c:\homepath\file1
and
c:\homepath\file2
are permitted to be opened by the user. It also catches
Throwable
, as permitted by exception ERR08-J-EX2
(see
). It uses the
MyExceptionReporter
class described in
, which filters sensitive information from any resulting exceptions.
#ccccff
class ExceptionExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
switch(Integer.valueOf(args[0])) {
case 1:
fis = new FileInputStream("c:\\homepath\\file1");
break;
case 2:
fis = new FileInputStream("c:\\homepath\\file2");
break;
//...
default:
System.out.println("Invalid option");
break;
}
} catch (Throwable t) {
MyExceptionReporter.report(t); // Sanitize
}
}
}
Compliant solutions must ensure that security exceptions such as
java.security.AccessControlException
and
java.lang.SecurityException
continue to be logged and sanitized appropriately (see
for additional information). The
MyExceptionReporter
class from
demonstrates an acceptable approach for this logging and
sanitization
.
For scalability, the
switch
statement should be replaced with some sort of mapping from integers to valid file names or at least an enum type representing valid files. | ## Risk Assessment
Exceptions may inadvertently reveal sensitive information unless care is taken to limit the information disclosure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR01-J
Medium
Probable
No
Yes
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,839 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487839 | 2 | 7 | ERR02-J | Prevent exceptions while logging data | Exceptions that are thrown while logging is in progress can prevent successful logging unless special care is taken. Failure to account for exceptions during the logging process can cause security
vulnerabilities
, such as allowing an attacker to conceal critical security exceptions by preventing them from being logged. Consequently, programs must ensure that data logging continues to operate correctly even when exceptions are thrown during the logging process. | try {
// ...
} catch (SecurityException se) {
System.err.println(se);
// Recover from exception
}
## Noncompliant Code Example
## This noncompliant code example writes a critical security exception to the standard error stream:
#FFcccc
try {
// ...
} catch (SecurityException se) {
System.err.println(se);
// Recover from exception
}
Writing such exceptions to the standard error stream is inadequate for logging purposes. First, the standard error stream may be exhausted or closed, preventing recording of subsequent exceptions. Second, the trust level of the standard error stream may be insufficient for recording certain security-critical exceptions or errors without leaking sensitive information. If an I/O error were to occur while writing the security exception, the
catch
block would throw an
IOException
and the critical security exception would be lost. Finally, an attacker may disguise the exception so that it occurs with several other innocuous exceptions.
Using
Console.printf()
,
System.out.print*()
, or
Throwable.printStackTrace()
to output a security exception also constitutes a violation of this rule. | try {
// ...
} catch(SecurityException se) {
logger.log(Level.SEVERE, se);
// Recover from exception
}
## Compliant Solution
This compliant solution uses
java.util.logging.Logger
, the default logging API provided by JDK 1.4 and later. Use of other compliant logging mechanisms, such as log4j, is also permitted.
#ccccff
try {
// ...
} catch(SecurityException se) {
logger.log(Level.SEVERE, se);
// Recover from exception
}
Typically, only one logger is required for the entire program. | ## Risk Assessment
Exceptions thrown during data logging can cause loss of data and can conceal security problems.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR02-J
Medium
Likely
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,753 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487753 | 2 | 7 | ERR03-J | Restore prior object state on method failure | Objects in general should—and security-critical objects
must
—be maintained in a consistent state even when exceptional conditions arise. Common techniques for maintaining object consistency include
Input validation (on method arguments, for example)
Reordering logic so that code that can result in the exceptional condition executes before the object is modified
Using rollbacks in the event of failure
Performing required operations on a temporary copy of the object and committing changes to the original object only after their successful completion
Avoiding the need to modify the object at all | class Dimensions {
private int length;
private int width;
private int height;
static public final int PADDING = 2;
static public final int MAX_DIMENSION = 10;
public Dimensions(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
protected int getVolumePackage(int weight) {
length += PADDING;
width += PADDING;
height += PADDING;
try {
if (length <= PADDING || width <= PADDING || height <= PADDING ||
length > MAX_DIMENSION + PADDING || width > MAX_DIMENSION + PADDING ||
height > MAX_DIMENSION + PADDING || weight <= 0 || weight > 20) {
throw new IllegalArgumentException();
}
int volume = length * width * height;
length -= PADDING; width -= PADDING; height -= PADDING; // Revert
return volume;
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1; // Non-positive error code
}
}
public static void main(String[] args) {
Dimensions d = new Dimensions(8, 8, 8);
System.out.println(d.getVolumePackage(21)); // Prints -1 (error)
System.out.println(d.getVolumePackage(19));
// Prints 1728 (12x12x12) instead of 1000 (10x10x10)
}
}
## Noncompliant Code Example
This noncompliant code example shows a
Dimensions
class that contains three internal attributes: the
length
,
width
, and
height
of a rectangular box. The
getVolumePackage()
method is designed to return the total volume required to hold the box after accounting for packaging material, which adds 2 units to the dimensions of each side. Nonpositive values of the dimensions of the box (exclusive of packaging material) are rejected during input validation. No dimension can be larger than 10. Also, the
weight
of the object is passed in as an argument and cannot be more than 20 units.
If the
weight
is more than 20 units, it causes an
IllegalArgumentException
, which is intercepted by the custom error reporter. Although the logic restores the object's original state in the absence of this exception, the rollback code fails to execute in the event of an exception. Consequently, subsequent invocations of
getVolumePackage()
produce incorrect results.
#FFcccc
class Dimensions {
private int length;
private int width;
private int height;
static public final int PADDING = 2;
static public final int MAX_DIMENSION = 10;
public Dimensions(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
protected int getVolumePackage(int weight) {
length += PADDING;
width += PADDING;
height += PADDING;
try {
if (length <= PADDING || width <= PADDING || height <= PADDING ||
length > MAX_DIMENSION + PADDING || width > MAX_DIMENSION + PADDING ||
height > MAX_DIMENSION + PADDING || weight <= 0 || weight > 20) {
throw new IllegalArgumentException();
}
int volume = length * width * height;
length -= PADDING; width -= PADDING; height -= PADDING; // Revert
return volume;
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1; // Non-positive error code
}
}
public static void main(String[] args) {
Dimensions d = new Dimensions(8, 8, 8);
System.out.println(d.getVolumePackage(21)); // Prints -1 (error)
System.out.println(d.getVolumePackage(19));
// Prints 1728 (12x12x12) instead of 1000 (10x10x10)
}
}
The
catch
clause is permitted by exception ERR08-J-EX0 in
because it serves as a general filter passing exceptions to the
MyExceptionReporter
class, which is dedicated to safely reporting exceptions as recommended by
. Although this code only throws
IllegalArgumentException
, the
catch
clause is general enough to handle any exception in case the
try
block should be modified to throw other exceptions. | // ...
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
length -= PADDING; width -= PADDING; height -= PADDING; // Revert
return -1;
}
protected int getVolumePackage(int weight) {
length += PADDING;
width += PADDING;
height += PADDING;
try {
if (length <= PADDING || width <= PADDING || height <= PADDING ||
length > MAX_DIMENSION + PADDING ||
width > MAX_DIMENSION + PADDING ||
height > MAX_DIMENSION + PADDING ||
weight <= 0 || weight > 20) {
throw new IllegalArgumentException();
}
int volume = length * width * height;
return volume;
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1; // Non-positive error code
} finally {
// Revert
length -= PADDING; width -= PADDING; height -= PADDING;
}
}
protected int getVolumePackage(int weight) {
try {
if (length <= 0 || width <= 0 || height <= 0 ||
length > MAX_DIMENSION || width > MAX_DIMENSION || height > MAX_DIMENSION ||
weight <= 0 || weight > 20) {
throw new IllegalArgumentException(); // Validate first
}
} catch (Throwable t) { MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1;
}
length += PADDING;
width += PADDING;
height += PADDING;
int volume = length * width * height;
length -= PADDING; width -= PADDING; height -= PADDING;
return volume;
}
protected int getVolumePackage(int weight) {
try {
if (length <= 0 || width <= 0 || height <= 0 ||
length > MAX_DIMENSION || width > MAX_DIMENSION ||
height > MAX_DIMENSION || weight <= 0 || weight > 20) {
throw new IllegalArgumentException(); // Validate first
}
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1;
}
int volume = (length + PADDING) * (width + PADDING) *
(height + PADDING);
return volume;
}
## Compliant Solution (Rollback)
This compliant solution replaces the
catch
block in the
getVolumePackage()
method with code that restores prior object state in the event of an exception:
#ccccff
// ...
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
length -= PADDING; width -= PADDING; height -= PADDING; // Revert
return -1;
}
## Compliant Solution (finallyClause)
This compliant solution uses a
finally
clause to perform rollback, guaranteeing that rollback occurs whether or not an error occurs:
#ccccff
protected int getVolumePackage(int weight) {
length += PADDING;
width += PADDING;
height += PADDING;
try {
if (length <= PADDING || width <= PADDING || height <= PADDING ||
length > MAX_DIMENSION + PADDING ||
width > MAX_DIMENSION + PADDING ||
height > MAX_DIMENSION + PADDING ||
weight <= 0 || weight > 20) {
throw new IllegalArgumentException();
}
int volume = length * width * height;
return volume;
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1; // Non-positive error code
} finally {
// Revert
length -= PADDING; width -= PADDING; height -= PADDING;
}
}
## Compliant Solution (Input Validation)
This compliant solution improves on the previous solution by performing input validation before modifying the state of the object. Note that the
try
block contains only those statements that could throw the exception; all others have been moved outside the
try
block.
#ccccff
protected int getVolumePackage(int weight) {
try {
if (length <= 0 || width <= 0 || height <= 0 ||
length > MAX_DIMENSION || width > MAX_DIMENSION || height > MAX_DIMENSION ||
weight <= 0 || weight > 20) {
throw new IllegalArgumentException(); // Validate first
}
} catch (Throwable t) { MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1;
}
length += PADDING;
width += PADDING;
height += PADDING;
int volume = length * width * height;
length -= PADDING; width -= PADDING; height -= PADDING;
return volume;
}
## Compliant Solution (Unmodified Object)
This compliant solution avoids the need to modify the object. The object's state cannot be made inconsistent, and rollback is consequently unnecessary. This approach is preferred to solutions that modify the object but may be infeasible for complex code.
#ccccff
protected int getVolumePackage(int weight) {
try {
if (length <= 0 || width <= 0 || height <= 0 ||
length > MAX_DIMENSION || width > MAX_DIMENSION ||
height > MAX_DIMENSION || weight <= 0 || weight > 20) {
throw new IllegalArgumentException(); // Validate first
}
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
return -1;
}
int volume = (length + PADDING) * (width + PADDING) *
(height + PADDING);
return volume;
} | ## Risk Assessment
Failure to restore prior object state on method failure can leave the object in an inconsistent state and can violate required state
invariants
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR03-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,685 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487685 | 2 | 7 | ERR04-J | Do not complete abruptly from a finally block | Never use
return
,
break
,
continue
, or
throw
statements within a
finally
block. When program execution enters a
try
block that has a
finally
block, the
finally
block always executes regardless of whether the
try
block (or any associated
catch
blocks) executes to normal completion. Statements that cause the
finally
block to complete abruptly also cause the
try
block to complete abruptly and consequently suppress any exception thrown from the
try
or
catch
blocks. According to
The Java Language Specification
,
§14.20.2, "Execution of
try-finally
and
try-catch-finally
"
[
JLS 2015
]:
If execution of the
try
block completes abruptly for any other reason
R
, then the
finally
block is executed. Then there is a choice:
If the
finally
block completes normally, then the
try
statement completes abruptly for reason
R
.
If the
finally
block completes abruptly for reason
S
, then the
try
statement completes abruptly for reason
S
(and reason
R
is discarded). | class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
return true;
}
}
}
## Noncompliant Code Example
## In this noncompliant code example, thefinallyblock completes abruptly because of areturnstatement in the block:
#FFCCCC
class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
return true;
}
}
}
The
IllegalStateException
is suppressed by the abrupt completion of the
finally
block caused by the
return
statement. | class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
}
// Any return statements must go here;
// applicable only when exception is thrown conditionally
}
}
## Compliant Solution
## This compliant solution removes thereturnstatement from thefinallyblock:
#ccccff
class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
}
// Any return statements must go here;
// applicable only when exception is thrown conditionally
}
} | ## Risk Assessment
Abrupt completion of a
finally
block masks any exceptions thrown inside the associated
try
and
catch
blocks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR04-J
Low
Probable
Yes
Yes
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,445 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487445 | 2 | 7 | ERR05-J | Do not let checked exceptions escape from a finally block | Methods invoked from within a
finally
block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire
try
block. Abrupt termination causes any exception thrown in the
try
block to be lost, preventing any possible recovery method from handling that specific problem. Additionally, the transfer of control associated with the exception may prevent execution of any expressions or statements that occur after the point in the
finally
block from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions that are thrown from within a
finally
block.
Allowing checked exceptions to escape a
finally
block also violates
. | public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
reader.close();
// ... Other cleanup code ...
}
} catch (IOException x) {
// Forward to handler
}
}
}
## Noncompliant Code Example
This noncompliant code example contains a
finally
block that closes the
reader
object. The programmer incorrectly assumes that the statements in the
finally
block cannot throw exceptions and consequently fails to appropriately handle any exception that may arise.
#FFCCCC
public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
reader.close();
// ... Other cleanup code ...
}
} catch (IOException x) {
// Forward to handler
}
}
}
The
close()
method can throw an
IOException
, which, if thrown, would prevent execution of any subsequent cleanup statements. This problem will not be diagnosed by the compiler because any
IOException
would be caught by the outer
catch
block. Also, an exception thrown from the
close()
operation can mask any exception that gets thrown during execution of the
Do operations
block, preventing proper recovery. | public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
try {
reader.close();
} catch (IOException ie) {
// Forward to handler
}
// ... Other cleanup code ...
}
} catch (IOException x) {
// Forward to handler
}
}
}
public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try ( // try-with-resources
BufferedReader reader =
new BufferedReader(new FileReader(some_file))) {
// Do operations
} catch (IOException ex) {
System.err.println("thrown exception: " + ex.toString());
Throwable[] suppressed = ex.getSuppressed();
for (int i = 0; i < suppressed.length; i++) {
System.err.println("suppressed exception: "
+ suppressed[i].toString());
}
// Forward to handler
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please supply a path as an argument");
return;
}
doOperation(args[0]);
}
}
## Compliant Solution (Handle Exceptions infinallyBlock)
This compliant solution encloses the
close()
method invocation in a
try-catch
block of its own within the
finally
block. Consequently, the potential
IOException
can be handled without allowing it to propagate further.
#ccccff
public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
try {
reader.close();
} catch (IOException ie) {
// Forward to handler
}
// ... Other cleanup code ...
}
} catch (IOException x) {
// Forward to handler
}
}
}
## Compliant Solution (try-with-resources)
Java SE 7 introduced a feature called
try
-with-resources
that can close certain resources automatically in the event of an error. This compliant solution uses
try
-with-resources to properly close the file.
#ccccff
public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try ( // try-with-resources
BufferedReader reader =
new BufferedReader(new FileReader(some_file))) {
// Do operations
} catch (IOException ex) {
System.err.println("thrown exception: " + ex.toString());
Throwable[] suppressed = ex.getSuppressed();
for (int i = 0; i < suppressed.length; i++) {
System.err.println("suppressed exception: "
+ suppressed[i].toString());
}
// Forward to handler
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please supply a path as an argument");
return;
}
doOperation(args[0]);
}
}
When an
IOException
occurs in the
try
block of the
doOperation()
method, it is caught by the
catch
block and printed as the
thrown exception
. Exceptions that occur while creating the
BufferedReader
are included. When an
IOException
occurs while closing the
reader
, that exception is also caught by the
catch
block and printed as the thrown exception. If both the
try
block and closing the
reader
throw an
IOException
, the
catch
clause catches both exceptions and prints the
try
block exception as the thrown exception. The close exception is suppressed and printed as the
suppressed exception
. In all cases, the
reader
is safely closed. | ## Risk Assessment
Failure to handle an exception in a
finally
block may have unexpected results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR05-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
Dataset Card for SEI CERT Oracle Coding Standard for Java (Wiki rules)
Structured export of the SEI CERT Oracle Coding Standard for Java from the SEI wiki.
Dataset Details
Dataset Description
Rows contain Java-specific secure coding rules, guidance text, and examples as published on the CERT Confluence site.
- Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Language(s) (NLP): English (rule text and embedded code).
- License: Compilation distributed as
other; verify with CMU SEI for your use case.
Dataset Sources [optional]
- Repository: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards
- Paper [optional]: SEI CERT Oracle Secure Coding Standard for Java
- Demo [optional]: [More Information Needed]
Uses
Direct Use
Java static analysis benchmarks, secure coding curricula, and RAG over CERT Java rules.
Out-of-Scope Use
Does not replace Oracle / SEI official publications or internal policies.
Dataset Structure
All rows share the same columns (scraped from the SEI CERT Confluence wiki):
| Column | Description |
|---|---|
language |
Language identifier for the rule set |
page_id |
Confluence page id |
page_url |
Canonical wiki URL for the rule page |
chapter |
Chapter label when present |
section |
Section label when present |
rule_id |
Rule identifier (e.g. API00-C, CON50-J) |
title |
Short rule title |
intro |
Normative / explanatory text |
noncompliant_code |
Noncompliant example(s) when present |
compliant_solution |
Compliant example(s) when present |
risk_assessment |
Risk / severity notes when present |
breadcrumb |
Wiki breadcrumb trail when present |
Dataset Creation
Curation Rationale
Single-table format for Java CERT rules supports automated ingestion and search.
Source Data
Data Collection and Processing
Scraped from the Java section of the SEI CERT wiki into the shared column layout.
Who are the source data producers?
[More Information Needed]
Annotations [optional]
Annotation process
[More Information Needed]
Who are the annotators?
[More Information Needed]
Personal and Sensitive Information
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Dataset Card Authors [optional]
[More Information Needed]
Dataset Card Contact
[More Information Needed]
- Downloads last month
- 11