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) |
java | 88,487,873 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487873 | 2 | 7 | ERR06-J | Do not throw undeclared checked exceptions | Java requires that each method address every checked exception that can be thrown during its execution either by handling the exception within a
try-catch
block or by declaring that the exception can propagate out of the method (via the
throws
clause). Unfortunately, there are a few techniques that permit undeclared checked exceptions to be thrown at runtime. Such techniques defeat the ability of caller methods to use the
throws
clause to determine the complete set of checked exceptions that could propagate from an invoked method. Consequently, such techniques must not be used to throw undeclared checked exceptions. | public class NewInstance {
private static Throwable throwable;
private NewInstance() throws Throwable {
throw throwable;
}
public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
throwable instanceof InstantiationException) {
// Unchecked, no declaration required
throw new IllegalArgumentException();
}
NewInstance.throwable = throwable;
try {
// Next line throws the Throwable argument passed in above,
// even though the throws clause of class.newInstance fails
// to declare that this may happen
NewInstance.class.newInstance();
} catch (InstantiationException e) { /* Unreachable */
} catch (IllegalAccessException e) { /* Unreachable */
} finally { // Avoid memory leak
NewInstance.throwable = null;
}
}
}
public class UndeclaredException {
public static void main(String[] args) {
// No declared checked exceptions
NewInstance.undeclaredThrow(
new Exception("Any checked exception"));
}
}
public static void main(String[] args) {
try {
NewInstance.undeclaredThrow(
new IOException("Any checked exception"));
} catch (Throwable e) {
if (e instanceof IOException) {
System.out.println("IOException occurred");
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
// Forward to handler
}
}
}
import java.io.IOException;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeCode {
public static void main(String[] args)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe u = (Unsafe) f.get(null);
u.throwException(new IOException("No need to declare this checked exception"));
}
}
interface Thr<EXC extends Exception> {
void fn() throws EXC;
}
public class UndeclaredGen {
static void undeclaredThrow() throws RuntimeException {
@SuppressWarnings("unchecked") // Suppresses warnings
Thr<RuntimeException> thr = (Thr<RuntimeException>)(Thr)
new Thr<IOException>() {
public void fn() throws IOException {
throw new IOException();
}
};
thr.fn();
}
public static void main(String[] args) {
undeclaredThrow();
}
}
static void sneakyThrow(Throwable t) {
Thread.currentThread().stop(t);
}
## Noncompliant Code Example (Class.newInstance())
This noncompliant code example throws undeclared checked exceptions. The
undeclaredThrow()
method takes a
Throwable
argument and invokes a function that will throw the argument without declaring it. Although
undeclaredThrow()
catches any exceptions the function declares that it might throw, it nevertheless throws the argument it is given without regard to whether the argument is one of the declared exceptions. This noncompliant code example also violates
. However, because of exception ERR08-J-EX0, it does not violate
.
Any checked exception thrown by the default constructor of
java.lang.Class.newInstance()
is propagated to the caller even though
Class.newInstance()
declares that it throws only
InstantiationException
and
IllegalAccessException
. This noncompliant code example demonstrates one way to use
Class.newInstance()
to throw arbitrary checked and unchecked exceptions:
#FFcccc
public class NewInstance {
private static Throwable throwable;
private NewInstance() throws Throwable {
throw throwable;
}
public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
throwable instanceof InstantiationException) {
// Unchecked, no declaration required
throw new IllegalArgumentException();
}
NewInstance.throwable = throwable;
try {
// Next line throws the Throwable argument passed in above,
// even though the throws clause of class.newInstance fails
// to declare that this may happen
NewInstance.class.newInstance();
} catch (InstantiationException e) { /* Unreachable */
} catch (IllegalAccessException e) { /* Unreachable */
} finally { // Avoid memory leak
NewInstance.throwable = null;
}
}
}
public class UndeclaredException {
public static void main(String[] args) {
// No declared checked exceptions
NewInstance.undeclaredThrow(
new Exception("Any checked exception"));
}
}
## Noncompliant Code Example (Class.newInstance()Workarounds)
When the programmer wishes to catch and handle the possible undeclared checked exceptions, the compiler refuses to believe that any can be thrown in the particular context. This noncompliant code example attempts to catch undeclared checked exceptions thrown by
Class.newInstance()
. It catches
Exception
and dynamically checks whether the caught exception is an instance of the possible checked exception (carefully rethrowing all other exceptions).
#FFcccc
public static void main(String[] args) {
try {
NewInstance.undeclaredThrow(
new IOException("Any checked exception"));
} catch (Throwable e) {
if (e instanceof IOException) {
System.out.println("IOException occurred");
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
// Forward to handler
}
}
}
## Noncompliant Code Example (sun.misc.Unsafe)
This noncompliant code example is insecure both because it can throw undeclared checked exceptions and because it uses the
sun.misc.Unsafe
class. All
sun.*
classes are unsupported and undocumented because their use can cause portability and backward compatibility issues.
Classes loaded by the bootstrap class loader have the permissions needed to call the static factory method
Unsafe.getUnsafe()
. Arranging to have an arbitrary class loaded by the bootstrap class loader without modifying the
sun.boot.class.path
system property can be difficult. However, an alternative way to gain access is to change the accessibility of the field that holds an instance of
Unsafe
through the use of reflection. This approach works only when permitted by the current security manager (which would violate
). Given access to
Unsafe
, a program can throw an undeclared checked exception by calling the
Unsafe.throwException()
method.
#FFcccc
import java.io.IOException;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeCode {
public static void main(String[] args)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe u = (Unsafe) f.get(null);
u.throwException(new IOException("No need to declare this checked exception"));
}
}
## Noncompliant Code Example (Generic Exception)
An unchecked cast of a generic type with parameterized exception declaration can also result in unexpected checked exceptions. All such casts are diagnosed by the compiler unless the warnings are suppressed.
#FFcccc
interface Thr<EXC extends Exception> {
void fn() throws EXC;
}
public class UndeclaredGen {
static void undeclaredThrow() throws RuntimeException {
@SuppressWarnings("unchecked") // Suppresses warnings
Thr<RuntimeException> thr = (Thr<RuntimeException>)(Thr)
new Thr<IOException>() {
public void fn() throws IOException {
throw new IOException();
}
};
thr.fn();
}
public static void main(String[] args) {
undeclaredThrow();
}
}
## Noncompliant Code Example (Thread.stop(Throwable))
According to the Java API [
API 2014
], class
Thread
:
[
Thread.stop()
]
This method was originally designed to force a thread to stop and throw a given
Throwable
as an exception. It was inherently unsafe (see
Thread.stop()
for details), and furthermore could be used to generate exceptions that the target thread was not prepared to handle.
For example, the following method is behaviorally identical to Java's throw operation but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw.
#FFcccc
static void sneakyThrow(Throwable t) {
Thread.currentThread().stop(t);
}
Note that the
Thread.stop()
methods are deprecated, so this code also violates
.
## Noncompliant Code Example (Bytecode Manipulation)
It is also possible to disassemble a class, remove any declared checked exceptions, and reassemble the class so that checked exceptions are thrown at runtime when the class is used [
Roubtsov 2003
]. Compiling against a class that declares the checked exception and supplying at runtime a class that lacks the declaration can also result in undeclared checked exceptions. Undeclared checked exceptions can also be produced through crafted use of the
sun.corba.Bridge
class. All of these practices are violations of this rule. | public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
throwable instanceof InstantiationException) {
// Unchecked, no declaration required
throw new IllegalArgumentException();
}
NewInstance.throwable = throwable;
try {
Constructor constructor =
NewInstance.class.getConstructor(new Class<?>[0]);
constructor.newInstance();
} catch (InstantiationException e) { /* Unreachable */
} catch (IllegalAccessException e) { /* Unreachable */
} catch (InvocationTargetException e) {
System.out.println("Exception thrown: "
+ e.getCause().toString());
} finally { // Avoid memory leak
NewInstance.throwable = null;
}
}
## Compliant Solution (Constructor.newInstance())
This compliant solution uses
java.lang.reflect.Constructor.newInstance()
rather than
Class.newInstance()
. The
Constructor.newInstance()
method wraps any exceptions thrown from within the constructor into a checked exception called
InvocationTargetException
.
#ccccff
public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
throwable instanceof InstantiationException) {
// Unchecked, no declaration required
throw new IllegalArgumentException();
}
NewInstance.throwable = throwable;
try {
Constructor constructor =
NewInstance.class.getConstructor(new Class<?>[0]);
constructor.newInstance();
} catch (InstantiationException e) { /* Unreachable */
} catch (IllegalAccessException e) { /* Unreachable */
} catch (InvocationTargetException e) {
System.out.println("Exception thrown: "
+ e.getCause().toString());
} finally { // Avoid memory leak
NewInstance.throwable = null;
}
} | ## Risk Assessment
Failure to document undeclared checked exceptions can result in checked exceptions that the caller is unprepared to handle, consequently violating the safety property.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR06-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,928 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487928 | 2 | 7 | ERR07-J | Do not throw RuntimeException, Exception, or Throwable | Methods must not throw
RuntimeException
,
Exception
, or
Throwable
. Handling these exceptions requires catching
RuntimeException
, which is disallowed by
. Moreover, throwing a
RuntimeException
can lead to subtle errors; for example, a caller cannot examine the exception to determine why it was thrown and consequently cannot attempt recovery.
Methods can throw a specific exception subclassed from
Exception
or
RuntimeException
. Note that it is permissible to construct an exception class specifically for a single
throw
statement. | boolean isCapitalized(String s) {
if (s == null) {
throw new RuntimeException("Null String");
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
private void doSomething() throws Exception {
//...
}
## Noncompliant Code Example
The
isCapitalized()
method in this noncompliant code example accepts a string and returns true when the string consists of a capital letter followed by lowercase letters. The method also throws a
RuntimeException
when passed a null string argument.
#ffcccc
boolean isCapitalized(String s) {
if (s == null) {
throw new RuntimeException("Null String");
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
A calling method must also violate
to determine whether the
RuntimeException
was thrown.
## Noncompliant Code Example
This noncompliant code example specifies the
Exception
class in the
throws
clause of the method declaration for the
doSomething()
method:
#ffcccc
private void doSomething() throws Exception {
//...
} | boolean isCapitalized(String s) {
if (s == null) {
throw new NullPointerException();
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
private void doSomething() throws IOException {
//...
}
## Compliant Solution
## This compliant solution throwsNullPointerExceptionto denote the specific exceptional condition:
#ccccff
boolean isCapitalized(String s) {
if (s == null) {
throw new NullPointerException();
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
Note that the null check is redundant; if it were removed, the subsequent call to
s.equals("")
would throw a
NullPointerException
when
s
is null. However, the null check explicitly indicates the programmer's intent. More complex code may require explicit testing of
invariants
and appropriate
throw
statements.
## Compliant Solution
This compliant solution declares a more specific exception class in the
throws
clause of the method declaration for the
doSomething()
method:
#ccccff
private void doSomething() throws IOException {
//...
} | ## Risk Assessment
Throwing
RuntimeException
,
Exception
, or
Throwable
prevents classes from catching the intended exceptions without catching other unintended exceptions as well.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR07-J
Low
Likely
Yes
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,929 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487929 | 2 | 7 | ERR08-J | Do not catch NullPointerException or any of its ancestors | Programs must not catch
java.lang.NullPointerException
. A
NullPointerException
exception thrown at runtime indicates the existence of an underlying
null
pointer dereference that must be fixed in the application code (see
for more information). Handling the underlying null pointer dereference by catching the
NullPointerException
rather than fixing the underlying problem is inappropriate for several reasons. First, catching
NullPointerException
adds significantly more performance overhead than simply adding the necessary null checks [
Bloch 2008
]. Second, when multiple expressions in a
try
block are capable of throwing a
NullPointerException
, it is difficult or impossible to determine which expression is responsible for the exception because the
NullPointerException
catch
block handles any
NullPointerException
thrown from any location in the
try
block. Third, programs rarely remain in an expected and usable state after a
NullPointerException
has been thrown. Attempts to continue execution after first catching and logging (or worse, suppressing) the exception rarely succeed.
Likewise, programs must not catch
RuntimeException
,
Exception
, or
Throwable
. Few, if any, methods are capable of handling all possible runtime exceptions. When a method catches
RuntimeException
, it may receive exceptions unanticipated by the designer, including
NullPointerException
and
ArrayIndexOutOfBoundsException
. Many
catch
clauses simply log or ignore the enclosed exceptional condition and attempt to resume normal execution; this practice often violates
. Runtime exceptions often indicate bugs in the program that should be fixed by the developer and often cause control flow vulnerabilities. | boolean isName(String s) {
try {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
} catch (NullPointerException e) {
return false;
}
}
public interface Log {
void write(String messageToLog);
}
public class FileLog implements Log {
private final FileWriter out;
FileLog(String logFileName) throws IOException {
out = new FileWriter(logFileName, true);
}
public void write(String messageToLog) {
// Write message to file
}
}
public class ConsoleLog implements Log {
public void write(String messageToLog) {
System.out.println(messageToLog); // Write message to console
}
}
class Service {
private Log log;
Service() {
this.log = null; // No logger
}
Service(Log log) {
this.log = log; // Set the specified logger
}
public void handle() {
try {
log.write("Request received and handled");
} catch (NullPointerException npe) {
// Ignore
}
}
public static void main(String[] args) throws IOException {
Service s = new Service(new FileLog("logfile.log"));
s.handle();
s = new Service(new ConsoleLog());
s.handle();
}
}
public class DivideException {
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: " + average);
}
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (Exception e) {
System.out.println("Divide by zero exception : "
+ e.getMessage());
}
}
}
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException ae) {
throw new DivideByZeroException();
} catch (Exception e) {
System.out.println("Exception occurred :" + e.getMessage());
}
## Noncompliant Code Example (NullPointerException)
This noncompliant code example defines an
isName()
method that takes a
String
argument and returns true if the given string is a valid name. A valid name is defined as two capitalized words separated by one or more spaces. Rather than checking to see whether the given string is null, the method catches
NullPointerException
and returns false.
#FFcccc
java
boolean isName(String s) {
try {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
} catch (NullPointerException e) {
return false;
}
}
## Noncompliant Code Example (Null Object Pattern)
This noncompliant code example is derived from the logging service Null Object design pattern described by Henney [
Henney 2003
]. The logging service is composed of two classes: one that prints the triggering activity's details to a disk file using the
FileLog
class and another that prints to the console using the
ConsoleLog
class. An interface,
Log
, defines a
write()
method that is implemented by the respective log classes. Method selection occurs polymorphically at runtime. The logging infrastructure is subsequently used by a
Service
class.
#FFcccc
public interface Log {
void write(String messageToLog);
}
public class FileLog implements Log {
private final FileWriter out;
FileLog(String logFileName) throws IOException {
out = new FileWriter(logFileName, true);
}
public void write(String messageToLog) {
// Write message to file
}
}
public class ConsoleLog implements Log {
public void write(String messageToLog) {
System.out.println(messageToLog); // Write message to console
}
}
class Service {
private Log log;
Service() {
this.log = null; // No logger
}
Service(Log log) {
this.log = log; // Set the specified logger
}
public void handle() {
try {
log.write("Request received and handled");
} catch (NullPointerException npe) {
// Ignore
}
}
public static void main(String[] args) throws IOException {
Service s = new Service(new FileLog("logfile.log"));
s.handle();
s = new Service(new ConsoleLog());
s.handle();
}
}
Each
Service
object must support the possibility that a
Log
object may be
null
because clients may choose not to perform logging. This noncompliant code example eliminates null checks by using a
try-catch
block that ignores
NullPointerException
.
This design choice suppresses genuine occurrences of
NullPointerException
in violation of
. It also violates the design principle that exceptions should be used only for exceptional conditions because ignoring a null
Log
object is part of the ordinary operation of a server.
## Noncompliant Code Example (Division)
This noncompliant code example assumes that the original version of the
division()
method was declared to throw only
ArithmeticException
. However, the caller catches the more general
Exception
type to report arithmetic problems rather than catching the specific exception
ArithmeticException
type. This practice is risky because future changes to the method signature could add more exceptions to the list of potential exceptions the caller must handle. In this example, a revision of the
division()
method can throw
IOException
in addition to
ArithmeticException
. However, the compiler will not diagnose the lack of a corresponding handler because the invoking method already catches
IOException
as a result of catching
Exception
. Consequently, the recovery process might be inappropriate for the specific exception type that is thrown. Furthermore, the developer has failed to anticipate that catching
Exception
also catches unchecked exceptions.
#FFcccc
public class DivideException {
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: " + average);
}
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (Exception e) {
System.out.println("Divide by zero exception : "
+ e.getMessage());
}
}
}
## Noncompliant Code Example
This noncompliant code example attempts to solve the problem by specifically catching
ArithmeticException
. However, it continues to catch
Exception
and consequently catches both unanticipated checked exceptions and unanticipated runtime exceptions.
#FFcccc
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException ae) {
throw new DivideByZeroException();
} catch (Exception e) {
System.out.println("Exception occurred :" + e.getMessage());
}
Note that
DivideByZeroException
is a custom exception type that extends
Exception
. | boolean isName(String s) {
if (s == null) {
return false;
}
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
boolean isName(String s) /* Throws NullPointerException */ {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
public interface Log {
public static final Log NULL = new Log() {
public void write(String messageToLog) {
// Do nothing
}
};
void write(String messageToLog);
}
class Service {
private final Log log;
Service(){
this.log = Log.NULL;
}
// ...
}
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException ae) {
// DivideByZeroException extends Exception so is checked
throw new DivideByZeroException();
} catch (IOException ex) {
ExceptionReporter.report(ex);
}
}
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: "+ average);
}
}
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException | IOException ex) {
ExceptionReporter.report(ex);
}
}
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: "+ average);
}
}
## Compliant Solution
## This compliant solution explicitly checks theStringargument fornullrather than catchingNullPointerException:
#ccccff
boolean isName(String s) {
if (s == null) {
return false;
}
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
## Compliant Solution
## This compliant solution omits an explicit check for a null reference and permits aNullPointerExceptionto be thrown:
#ccccff
boolean isName(String s) /* Throws NullPointerException */ {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
Omitting the null check means that the program fails more quickly than if the program had returned false and lets an invoking method discover the null value. A method that throws a
NullPointerException
without a null check must provide a precondition that the argument being passed to it is not null.
## Compliant Solution (Null Object Pattern)
The Null Object design pattern provides an alternative to the use of explicit null checks in code. It reduces the need for explicit null checks through the use of an explicit, safe
null object
rather than a null reference.
This compliant solution modifies the no-argument constructor of class
Service
to use the
do-nothing
behavior provided by an additional class,
Log.NULL
; it leaves the other classes unchanged.
#ccccff
public interface Log {
public static final Log NULL = new Log() {
public void write(String messageToLog) {
// Do nothing
}
};
void write(String messageToLog);
}
class Service {
private final Log log;
Service(){
this.log = Log.NULL;
}
// ...
}
Declaring the
log
reference final ensures that its value is assigned during initialization.
An acceptable alternative implementation uses accessor methods to control all interaction with the reference to the current log. The accessor method to set a log ensures use of the null object in place of a null reference. The accessor method to get a log ensures that any retrieved instance is either an actual logger or a null object (but never a null reference). Instances of the null object are immutable and are inherently thread-safe.
Some system designs require returning a value from a method rather than implementing do-nothing behavior. One acceptable approach is use of an exceptional value object that throws an exception before the method returns [
Cunningham 1995
]. This approach can be a useful alternative to returning
null
.
In distributed environments, the null object must be passed by copy to ensure that remote systems avoid the overhead of a remote call argument evaluation on every access to the null object. Null object code for distributed environments must also implement the
Serializable
interface.
Code that uses this pattern must be clearly documented to ensure that security-critical messages are never discarded because the pattern has been misapplied.
## Compliant Solution
This compliant solution catches only the specific anticipated exceptions (
ArithmeticException
and
IOException
). All other exceptions are permitted to propagate up the call stack.
#ccccff
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException ae) {
// DivideByZeroException extends Exception so is checked
throw new DivideByZeroException();
} catch (IOException ex) {
ExceptionReporter.report(ex);
}
}
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: "+ average);
}
}
The
ExceptionReporter
class is documented in
.
## Compliant Solution (Java SE 7)
Java SE 7 allows a single
catch
block to catch multiple exceptions of different types, which prevents redundant code. This compliant solution catches the specific anticipated exceptions (
ArithmeticException
and
IOException
) and handles them with one catch clause. All other exceptions are permitted to propagate to the next
catch
clause of a
try
statement on the stack.
#ccccff
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200, 5);
division(200, 0); // Divide by zero
} catch (ArithmeticException | IOException ex) {
ExceptionReporter.report(ex);
}
}
public static void division(int totalSum, int totalNumber)
throws ArithmeticException, IOException {
int average = totalSum / totalNumber;
// Additional operations that may throw IOException...
System.out.println("Average: "+ average);
}
} | ## Risk Assessment
Catching
NullPointerException
may mask an underlying null dereference, degrade application performance, and result in code that is hard to understand and maintain. Likewise, catching
RuntimeException
,
Exception
, or
Throwable
may unintentionally trap other exception types and prevent them from being handled properly.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR08-J
Medium
Likely
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,663 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487663 | 2 | 7 | ERR09-J | Do not allow untrusted code to terminate the JVM | Invocation of
System.exit()
terminates the Java Virtual Machine (JVM), consequently terminating all running programs and threads. This can result in
denial-of-service (DoS) attacks
. For example, a call to
System.exit()
that is embedded in Java Server Pages (JSP) code can cause a web server to terminate, preventing further service for users. Programs must prevent both inadvertent and malicious calls to
System.exit()
. Additionally, programs should perform necessary cleanup actions when forcibly terminated (for example, by using the Windows Task Manager, POSIX
kill
command, or other mechanisms). | public class InterceptExit {
public static void main(String[] args) {
// ...
System.exit(1); // Abrupt exit
System.out.println("This never executes");
}
}
## Noncompliant Code Example
This noncompliant code example uses
System.exit()
to forcefully shut down the JVM and terminate the running process. The program lacks a security manager; consequently, it lacks the capability to check whether the caller is permitted to invoke
System.exit()
.
#FFcccc
public class InterceptExit {
public static void main(String[] args) {
// ...
System.exit(1); // Abrupt exit
System.out.println("This never executes");
}
} | class PasswordSecurityManager extends SecurityManager {
private boolean isExitAllowedFlag;
public PasswordSecurityManager(){
super();
isExitAllowedFlag = false;
}
public boolean isExitAllowed(){
return isExitAllowedFlag;
}
@Override
public void checkExit(int status) {
if (!isExitAllowed()) {
throw new SecurityException();
}
super.checkExit(status);
}
public void setExitAllowed(boolean f) {
isExitAllowedFlag = f;
}
}
public class InterceptExit {
public static void main(String[] args) {
PasswordSecurityManager secManager =
new PasswordSecurityManager();
System.setSecurityManager(secManager);
try {
// ...
System.exit(1); // Abrupt exit call
} catch (Throwable x) {
if (x instanceof SecurityException) {
System.out.println("Intercepted System.exit()");
// Log exception
} else {
// Forward to exception handler
}
}
// ...
secManager.setExitAllowed(true); // Permit exit
// System.exit() will work subsequently
// ...
}
}
## Compliant Solution
This compliant solution installs a custom security manager
PasswordSecurityManager
that overrides the
checkExit()
method defined in the
SecurityManager
class. This override is required to enable invocation of cleanup code before allowing the exit. The default
checkExit()
method in the
SecurityManager
class lacks this facility.
#ccccff
class PasswordSecurityManager extends SecurityManager {
private boolean isExitAllowedFlag;
public PasswordSecurityManager(){
super();
isExitAllowedFlag = false;
}
public boolean isExitAllowed(){
return isExitAllowedFlag;
}
@Override
public void checkExit(int status) {
if (!isExitAllowed()) {
throw new SecurityException();
}
super.checkExit(status);
}
public void setExitAllowed(boolean f) {
isExitAllowedFlag = f;
}
}
public class InterceptExit {
public static void main(String[] args) {
PasswordSecurityManager secManager =
new PasswordSecurityManager();
System.setSecurityManager(secManager);
try {
// ...
System.exit(1); // Abrupt exit call
} catch (Throwable x) {
if (x instanceof SecurityException) {
System.out.println("Intercepted System.exit()");
// Log exception
} else {
// Forward to exception handler
}
}
// ...
secManager.setExitAllowed(true); // Permit exit
// System.exit() will work subsequently
// ...
}
}
This implementation uses an internal flag to track whether the exit is permitted. The method
setExitAllowed()
sets this flag. The
checkExit()
method throws a
SecurityException
when the flag is unset (that is, false). Because this flag is not initially set, normal exception processing bypasses the initial call to
System.exit()
. The program catches the
SecurityException
and performs mandatory cleanup operations, including logging the exception. The
System.exit()
method is enabled only after cleanup is complete. | ## Risk Assessment
Allowing unauthorized calls to
System.exit()
may lead to
denial of service
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR09-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,825 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487825 | 3 | 7 | ERR50-J | Use exceptions only for exceptional conditions | Exceptions should be used only to denote exceptional conditions; they should not be used for ordinary control flow purposes. Catching a generic object such as
Throwable
is likely to catch unexpected errors; see
ERR08-J. Do not catch NullPointerException or any of its ancestors
for examples. When a program catches a specific type of exception, it does not always know from where that exception was thrown. Using a
catch
clause to handle an exception that occurs in a distant known location is a poor solution; it is preferable to handle the error as soon as it occurs—or to prevent it if possible.
The nonlocality of
throw
statements and corresponding
catch
statements can also impede optimizers from improving code that relies on exception handling. Relying on catching exceptions for control flow also complicates debugging because exceptions indicate a jump in control flow from the
throw
statement to the
catch
clause. Finally, exceptions need not be highly optimized, as it is assumed that they are thrown only in exceptional circumstances. Throwing and catching an exception frequently has worse performance than handling the error with some other mechanism. | public String processSingleString(String string) {
// ...
return string;
}
public String processStrings(String[] strings) {
String result = "";
int i = 0;
try {
while (true) {
result = result.concat(processSingleString(strings[i]));
i++;
}
} catch (ArrayIndexOutOfBoundsException e) {
// Ignore, we're done
}
return result;
}
## Noncompliant Code Example
## This noncompliant code example attempts to concatenate the processed elements of thestringsarray:
#FFCCCC
public String processSingleString(String string) {
// ...
return string;
}
public String processStrings(String[] strings) {
String result = "";
int i = 0;
try {
while (true) {
result = result.concat(processSingleString(strings[i]));
i++;
}
} catch (ArrayIndexOutOfBoundsException e) {
// Ignore, we're done
}
return result;
}
This code uses an
ArrayIndexOutOfBoundsException
to detect the end of the array. Unfortunately, since
ArrayIndexOutOfBoundsException
is a
RuntimeException
, it could be thrown by
processSingleString()
without being declared in a
throws
clause. So it is possible for
processStrings()
to terminate prematurely before processing all of the strings. | public String processStrings(String[] strings) {
String result = "";
for (int i = 0; i < strings.length; i++) {
result = result.concat( processSingleString( strings[i]));
}
return result;
}
## Compliant Solution
## This compliant solution uses a standardforloop to concatenate the strings.
#ccccff
public String processStrings(String[] strings) {
String result = "";
for (int i = 0; i < strings.length; i++) {
result = result.concat( processSingleString( strings[i]));
}
return result;
}
This code need not catch
ArrayIndexOutOfBoundsException
because it is a runtime exception, and such exceptions indicate programmer errors, which are best resolved by fixing the defect. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,451 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487451 | 3 | 7 | ERR51-J | Prefer user-defined exceptions over more general exception types | Because an exception is caught by its type, it is better to define exceptions for specific purposes than to use the general exception types for multiple purposes. Throwing general exception types makes code hard to understand and maintain and defeats much of the advantage of the Java exception-handling mechanism. | try {
doSomething();
} catch (Throwable e) {
String msg = e.getMessage();
switch (msg) {
case "file not found":
// Handle error
break;
case "connection timeout":
// Handle error
break;
case "security violation":
// Handle error
break;
default: throw e;
}
}
throw new Exception("cannot find file");
## Noncompliant Code Example
This noncompliant code example attempts to distinguish between different exceptional behaviors by looking at the exception's message:
#FFcccc
try {
doSomething();
} catch (Throwable e) {
String msg = e.getMessage();
switch (msg) {
case "file not found":
// Handle error
break;
case "connection timeout":
// Handle error
break;
case "security violation":
// Handle error
break;
default: throw e;
}
}
If
doSomething()
throws an exception or error whose type is a subclass of
Throwable
, the switch statement allows selection of a specific case to execute. For example, if the exception message is "file not found," the appropriate action is taken in the exception-handling code.
However, any change to the exception message literals involved will break the code. For example, suppose this code is executed:
throw new Exception("cannot find file");
This exception should be handled by the first case clause, but it will be rethrown because the string does not match any case clause.
Furthermore, exceptions may be thrown without a message.
## This noncompliant code example falls underERR08-J-EX0ofbecause it catches general exceptions but rethrows them. | public class TimeoutException extends Exception {
TimeoutException () {
super();
}
TimeoutException (String msg) {
super(msg);
}
}
// ...
try {
doSomething();
} catch (FileNotFoundException e) {
// Handle error
} catch (TimeoutException te) {
// Handle error
} catch (SecurityException se) {
// Handle error
}
## Compliant Solution
## This compliant solution uses specific exception types and defines new special-purpose exception types where required.
#ccccff
public class TimeoutException extends Exception {
TimeoutException () {
super();
}
TimeoutException (String msg) {
super(msg);
}
}
// ...
try {
doSomething();
} catch (FileNotFoundException e) {
// Handle error
} catch (TimeoutException te) {
// Handle error
} catch (SecurityException se) {
// Handle error
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,499 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487499 | 3 | 7 | ERR52-J | Avoid in-band error indicators | An in-band error indicator is a value returned by a method that indicates either a legitimate return value or an illegitimate value that indicates an error. Some common examples of in-band error indicators include
A valid object or a null reference.
An integer indicating a positive value, or −1 to indicate that an error occurred.
An array of valid objects or a null reference indicating the absence of valid objects. (This topic is further addressed in
)
In-band error indicators require checking for the error; however, this checking is often overlooked. Failure to check for such error conditions not only violates
but also has the unfortunate effect of propagating invalid values that may subsequently be treated as valid in later computations.
Avoid the use of in-band error indicators. They are much less common in Java's core library than in some other programming languages; nevertheless, they are used in the
read(byte[] b, int off, int len)
and
read(char[] cbuf, int off, int len)
families of methods in
java.io
.
In Java, the best way to indicate an exceptional situation is by throwing an exception rather than by returning an error code. Exceptions are propagated across scopes and cannot be ignored as easily as error codes can. When using exceptions, the error-detection and error-handling code is kept separate from the main flow of control. | static final int MAX = 21;
static final int MAX_READ = MAX - 1;
static final char TERMINATOR = '\\';
int read;
char [] chBuff = new char [MAX];
BufferedReader buffRdr;
// Set up buffRdr
read = buffRdr.read(chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;
## Noncompliant Code Example
This noncompliant code example attempts to read into an array of characters and to add an extra character into the buffer immediately after the characters that are read.
#FFCCCC
static final int MAX = 21;
static final int MAX_READ = MAX - 1;
static final char TERMINATOR = '\\';
int read;
char [] chBuff = new char [MAX];
BufferedReader buffRdr;
// Set up buffRdr
read = buffRdr.read(chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;
However, if the input buffer is initially at end-of-file, the
read
method will return −1, and the attempt to place the terminator character will throw an
ArrayIndexOutOfBoundsException
. | public static int readSafe(BufferedReader buffer, char[] cbuf,
int off, int len) throws IOException {
int read = buffer.read(cbuf, off, len);
if (read == -1) {
throw new EOFException();
} else {
return read;
}
}
// ...
BufferedReader buffRdr;
// Set up buffRdr
try {
read = readSafe(buffRdr, chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;
} catch (EOFException eof) {
chBuff[0] = TERMINATOR;
}
## Compliant Solution (Wrapping)
This compliant solution defines a
readSafe()
method that wraps the original
read()
method and throws an exception if end-of-file is detected:
#ccccff
public static int readSafe(BufferedReader buffer, char[] cbuf,
int off, int len) throws IOException {
int read = buffer.read(cbuf, off, len);
if (read == -1) {
throw new EOFException();
} else {
return read;
}
}
// ...
BufferedReader buffRdr;
// Set up buffRdr
try {
read = readSafe(buffRdr, chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;
} catch (EOFException eof) {
chBuff[0] = TERMINATOR;
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,487 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487487 | 3 | 7 | ERR53-J | Try to gracefully recover from system errors | According to the Java Language Specification,
§11.1.1, "The Kinds of Exceptions"
[
JLS 2013
],
The unchecked exceptions classes are the class
RuntimeException
and its subclasses, and the class
Error
and its subclasses. All other exception classes are checked exception classes.
Unchecked exception classes are not subject to compile-time checking because it is tedious to account for all exceptional conditions and because recovery is often difficult or impossible. However, even when recovery is impossible, the Java Virtual Machine (JVM) allows a graceful exit and a chance to at least log the error. This is made possible by using a
try-catch
block that catches
Throwable
. Also, when code must avoid leaking potentially sensitive information, catching
Throwable
is permitted. In all other cases, catching
Throwable
is not recommended because it makes handling specific exceptions difficult. Where cleanup operations such as releasing system resources can be performed, code should use a
finally
block to release the resources or a
try
-with-resources statement.
Catching
Throwable
is disallowed in general by
ERR08-J. Do not catch NullPointerException or any of its ancestors
, but it is permitted when filtering exception traces by the exception
ERR08-EX0
in that rule. | public class StackOverflow {
public static void main(String[] args) {
infiniteRun();
// ...
}
private static void infiniteRun() {
infiniteRun();
}
}
## Noncompliant Code Example
This noncompliant code example generates a
StackOverflowError
as a result of infinite recursion. It exhausts the available stack space and may result in denial of service.
#FFcccc
public class StackOverflow {
public static void main(String[] args) {
infiniteRun();
// ...
}
private static void infiniteRun() {
infiniteRun();
}
} | public class StackOverflow {
public static void main(String[] args) {
try {
infiniteRun();
} catch (Throwable t) {
// Forward to handler
} finally {
// Free cache, release resources
}
// ...
}
private static void infiniteRun() {
infiniteRun();
}
}
## Compliant Solution
This compliant solution shows a
try-catch
block that can be used to capture
java.lang.Error
or
java.lang.Throwable
. A log entry can be made at this point, followed by attempts to free key system resources in the
finally
block.
#ccccff
public class StackOverflow {
public static void main(String[] args) {
try {
infiniteRun();
} catch (Throwable t) {
// Forward to handler
} finally {
// Free cache, release resources
}
// ...
}
private static void infiniteRun() {
infiniteRun();
}
}
Note that the
Forward to handler
code must operate correctly in constrained memory conditions because the stack or heap may be nearly exhausted. In such a scenario, one useful technique is for the program to initially reserve memory specifically to be used by an out-of-memory exception handler.
Note that this solution catches
Throwable
in an attempt to handle the error; it falls under exception
ERR08-EX2
in
ERR08-J. Do not catch NullPointerException or any of its ancestors
. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,656 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487656 | 3 | 7 | ERR54-J | Use a try-with-resources statement to safely handle closeable resources | The Java Development Kit 1.7 (JDK 1.7) introduced the try-with-resources statement (see the JLS, §14.20.3, "
try
-with-resources" [
JLS 2013
]), which simplifies correct use of resources that implement the
java.lang.AutoCloseable
interface, including those that implement the
java.io.Closeable
interface.
Using the try-with-resources statement avoids problems that can arise when closing resources with an ordinary
try
-
catch
-
finally
block, such as failing to close a resource because an exception is thrown as a result of closing another resource, or masking an important exception when a resource is closed.
Use of the try-with-resources statement is also illustrated in
ERR05-J. Do not let checked exceptions escape from a finally block
,
FIO03-J. Remove temporary files before termination
, and
FIO04-J. Release resources when they are no longer needed
. | public void processFile(String inPath, String outPath)
throws IOException{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException x) {
// Handle error
}
}
}
## Noncompliant Code Example
## This noncompliant code example uses an ordinarytry-catch-finallyblock in an attempt to close two resources.
#FFcccc
public void processFile(String inPath, String outPath)
throws IOException{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException x) {
// Handle error
}
}
}
However, if an exception is thrown when the
BufferedReader
br
is closed, then the
BufferedWriter
bw
will not be closed. | public void processFile(String inPath, String outPath)
throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
if (br != null) {
try {
br.close();
} catch (IOException x) {
// Handle error
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
}
public void processFile(String inPath, String outPath)
throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(inPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(outPath))) {
// Process the input and produce the output
} 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());
}
}
}
## Compliant Solution (finally block)
This compliant solution uses a second
finally
block to guarantee that
bw
is properly closed even when an exception is thrown while closing
br
.
#ccccff
public void processFile(String inPath, String outPath)
throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
if (br != null) {
try {
br.close();
} catch (IOException x) {
// Handle error
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
}
## Compliant Solution (try-with-resources)
## This compliant solution uses a try-with-resources statement to manage bothbrandbw.
#ccccff
public void processFile(String inPath, String outPath)
throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(inPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(outPath))) {
// Process the input and produce the output
} 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());
}
}
}
This solution preserves any exceptions thrown during the processing of the input while still guaranteeing that both
br
and
bw
are properly closed, regardless of what exceptions occur. Finally, this code demonstrates how to access every exception that may be produced from the try-with-resources block.
If only one exception is thrown, either during opening, processing, or closing of the files, the exception will be printed after
"thrown exception:"
. If an exception is thrown during processing, and a second exception is thrown while trying to close either file, the first exception will be printed after
"thrown exception:"
, and the second exception will be printed after
"suppressed exception:"
. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,879 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487879 | 2 | 2 | EXP00-J | Do not ignore values returned by methods | Methods can return values to communicate failure or success or to update local objects or fields. Security risks can arise when method return values are ignored or when the invoking method fails to take suitable action. Consequently, programs must not ignore method return values.
When getter methods are named after an action, a programmer could fail to realize that a return value is expected. For example, the only purpose of the
ProcessBuilder.redirectErrorStream()
method is to report via return value whether the process builder successfully merged standard error and standard output. The method that actually performs redirection of the error stream is the overloaded single-argument method
ProcessBuilder.redirectErrorStream(boolean)
. | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
someFile.delete();
}
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original.replace('i', '9');
System.out.println(original);
}
}
## Noncompliant Code Example (File Deletion)
## This noncompliant code example attempts to delete a file but fails to check whether the operation has succeeded:
#FFcccc
public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
someFile.delete();
}
## Noncompliant Code Example (String Replacement)
This noncompliant code example ignores the return value of the
String.replace()
method, failing to update the original string. The
String.replace()
method cannot modify the state of the
String
(because
String
objects are immutable); rather, it returns a reference to a new
String
object containing the modified string.
#FFcccc
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original.replace('i', '9');
System.out.println(original);
}
}
It is especially important to process the return values of immutable object methods. Although many methods of mutable objects operate by changing some internal state of the object, methods of immutable objects cannot change the object and often return a mutated new object, leaving the original object unchanged. | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
if (!someFile.delete()) {
// Handle failure to delete the file
}
}
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original = original.replace('i', '9');
System.out.println(original);
}
}
## Compliant Solution
## This compliant solution checks the Boolean value returned by thedelete()method and handles any resulting errors:
#ccccff
public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
if (!someFile.delete()) {
// Handle failure to delete the file
}
}
## Compliant Solution
This compliant solution correctly updates the
String
reference
original
with the return value from the
String.replace()
method:
#ccccff
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original = original.replace('i', '9');
System.out.println(original);
}
} | ## Risk Assessment
Ignoring method return values can lead to unexpected program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP00-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,784 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487784 | 2 | 2 | EXP01-J | Do not use a null in a case where an object is required | Do not use the
null
value in any instance where an object is required, including the following cases:
Calling the instance method of a null object
Accessing or modifying the field of a null object
Taking the length of
null
as if it were an array
Accessing or modifying the elements of
null
as if it were an array
Throwing
null
as if it were a
Throwable
value
Using a
null
in cases where an object is required results in a
NullPointerException
being thrown, which interrupts execution of the program or thread. Code conforming to this coding standard will consequently terminate because
requires that
NullPointerException
is not caught. | public static int cardinality(Object obj, final Collection<?> col) {
int count = 0;
if (col == null) {
return count;
}
Iterator<?> it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) || obj.equals(elt)) { // Null pointer dereference
count++;
}
}
return count;
}
public boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
## Noncompliant Code Example
This noncompliant example shows a bug in Tomcat version 4.1.24, initially discovered by Reasoning [
Reasoning 2003
]. The
cardinality()
method was designed to return the number of occurrences of object
obj
in collection
col
. One valid use of the
cardinality()
method is to determine how many objects in the collection are null. However, because membership in the collection is checked using the expression
obj.equals(elt)
, a null pointer dereference is guaranteed whenever
obj
is null and
elt
is not null.
#FFcccc
public static int cardinality(Object obj, final Collection<?> col) {
int count = 0;
if (col == null) {
return count;
}
Iterator<?> it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) || obj.equals(elt)) { // Null pointer dereference
count++;
}
}
return count;
}
## Noncompliant Code Example
This noncompliant code example defines an
isProperName
()
method that returns true if the specified
String
argument is a valid name (two capitalized words separated by one or more spaces):
#FFcccc
public boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
Method
isProperName
()
is noncompliant because it may be called with a null argument, resulting in a null pointer dereference. | public static int cardinality(Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) ||
(null != obj && obj.equals(elt))) {
count++;
}
}
return count;
}
public class Foo {
private boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
public boolean testString(String s) {
if (s == null) return false;
else return isProperName(s);
}
}
public boolean isProperName(Optional<String> os) {
String names[] = os.orElse("").split(" ");
return (names.length != 2) ? false :
(isCapitalized(names[0]) && isCapitalized(names[1]));
}
## Compliant Solution
## This compliant solution eliminates the null pointer dereference by adding an explicit check:
#ccccff
public static int cardinality(Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) ||
(null != obj && obj.equals(elt))) {
count++;
}
}
return count;
}
## Compliant Solution (Wrapped Method)
This compliant solution includes the same
isProperName()
method implementation as the previous noncompliant example, but it is now a private method with only one caller in its containing class.
#ccccff
public class Foo {
private boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
public boolean testString(String s) {
if (s == null) return false;
else return isProperName(s);
}
}
The calling method,
testString()
, guarantees that
isProperName
()
is always called with a valid string reference. As a result, the class conforms with this rule even though a public
isProperName()
method would not. Guarantees of this sort can be used to eliminate null pointer dereferences.
## Compliant Solution (Optional Type)
This compliant solution uses an
Optional String
instead of a
String
object that may be null. The
Optional
class (
java.util.Optional
[
API 2014
]) was introduced in Java 8
and can be used to mitigate against null pointer
dereferences
.
#ccccff
public boolean isProperName(Optional<String> os) {
String names[] = os.orElse("").split(" ");
return (names.length != 2) ? false :
(isCapitalized(names[0]) && isCapitalized(names[1]));
}
The
Optional
class contains methods that can be used to make programs shorter and more intuitive
[
Urma 2014
]
. | ## Risk Assessment
Dereferencing a null pointer can lead to a
denial of service
. In multithreaded programs, null pointer dereferences can violate cache coherency policies and can cause resource leaks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP01-J
Low
Likely
No
Yes
P6
L2
Automated Detection
Null pointer dereferences can happen in path-dependent ways. Limitations of automatic detection tools can require manual inspection of code [
Hovemeyer 2007
] to detect instances of null pointer dereferences. Annotations for method parameters that must be non-null can reduce the need for manual inspection by assisting automated null pointer dereference detection; use of these annotations is strongly encouraged.
Tool
Version
Checker
Description
Nullness Checker
Initialization Checker
Map Key Checker
Null pointer errors (see Chapter 3)
Ensure all fields are set in the constructor (see Chapter 3.8)
Track which values are keys in a map (see Chapter 4)
JAVA.DEEPNULL.PARAM.EACTUAL
JAVA.DEEPNULL.EFIELD
JAVA.DEEPNULL.FIELD
JAVA.NULL.PARAM.ACTUAL
JAVA.NULL.DEREF
JAVA.DEEPNULL.DEREF
JAVA.DEEPNULL.RET.EMETH
JAVA.DEEPNULL.RET.METH
JAVA.NULL.RET.ARRAY
JAVA.NULL.RET.BOOL
JAVA.NULL.RET.OPT
JAVA.STRUCT.UPD
JAVA.STRUCT.DUPD
JAVA.STRUCT.UPED
JAVA.DEEPNULL.PARAM.ACTUAL
Actual Parameter Element may be null
Field Element may be null (deep)
Field may be null (deep)
Null Parameter Dereference
Null Pointer Dereference
Null Pointer Dereference (deep)
Return Value may Contain null Element
Return Value may be null
Return null Array
Return null Boolean
Return null Optional
Unchecked Parameter Dereference
Unchecked Parameter Dereference (deep)
Unchecked Parameter Element Dereference (deep)
null Passed to Method (deep)
v7.5
FORWARD_NULL
NULL_RETURNS
REVERSE_INULL
FB.BC_NULL_INSTANCEOF
FB.NP_ALWAYS_NULL
FB.NP_ALWAYS_NULL_EXCEPTION
FB.NP_ARGUMENT_MIGHT_BE_NULL
FB.NP_BOOLEAN_RETURN_NULL
FB.NP_CLONE_COULD_RETURN_NULL
FB.NP_CLOSING_NULL
FB.NP_DEREFERENCE_OF_ READLINE_VALUE
FB.NP_DOES_NOT_HANDLE_NULL
FB.NP_EQUALS_SHOULD_HANDLE_ NULL_ARGUMENT
FB.NP_FIELD_NOT_INITIALIZED_ IN_CONSTRUCTOR
FB.NP_GUARANTEED_DEREF
FB.NP_GUARANTEED_DEREF_ON_ EXCEPTION_PATH
FB.NP_IMMEDIATE_DEREFERENCE_ OF_READLINE
FB.NP_LOAD_OF_KNOWN_NULL_ VALUE
FB.NP_NONNULL_FIELD_NOT_ INITIALIZED_IN_CONSTRUCTOR
FB.NP_NONNULL_PARAM_VIOLATION
FB.NP_NONNULL_RETURN_VIOLATION
FB.NP_NULL_INSTANCEOF
FB.NP_NULL_ON_SOME_PATH
FB.NP_NULL_ON_SOME_PATH_ EXCEPTION
FB.NP_NULL_ON_SOME_PATH_ FROM_RETURN_VALUE
FB.NP_NULL_ON_SOME_PATH_ MIGHT_BE_INFEASIBLE
FB.NP_NULL_PARAM_DEREF
FB.NP_NULL_PARAM_DEREF_ALL_ TARGETS_DANGEROUS
FB.NP_NULL_PARAM_DEREF_ NONVIRTUAL
FB.NP_PARAMETER_MUST_BE_NON - NULL_BUT_MARKED_AS_NULLABLE
FB.NP_STORE_INTO_NONNULL_FIELD
FB.NP_TOSTRING_COULD_ RETURN_NULL
FB.NP_UNWRITTEN_FIELD
FB.NP_UNWRITTEN_PUBLIC_OR_ PROTECTED_FIELD
FB.RCN_REDUNDANT_COMPARISON_ OF_NULL_AND_NONNULL_VALUE
FB.RCN_REDUNDANT_COMPARISON_ TWO_NULL_VALUES
FB.RCN_REDUNDANT_NULLCHECK_ OF_NONNULL_VALUE
FB.RCN_REDUNDANT_NULLCHECK_ OF_NULL_VALUE
FB.RCN_REDUNDANT_NULLCHECK_ WOULD_HAVE_BEEN_A_NPE
Implemented
Missing_Check_against_Null
Null_Dereference
Redundant_Null_Check
Implemented
NP_DEREFERENCE_OF_READLINE_VALUE
NP_NULL_PARAM_DEREF
NP_TOSTRING_COULD_RETURN_NULL
Implemented
NPE.COND
NPE.CONST
NPE.RET
NPE.RET.UTIL
NPE.STAT
REDUN.EQNULL
Parasoft Jtest
CERT.EXP01.NP
CERT.EXP01.NCMD
Avoid NullPointerException
Ensure that dereferenced variables match variables which were previously checked for "null"
PVS-Studio
V6008
,
V6073
,
V6093
NullableReturns, ReturnNumberNull
Full Implementation
S2259
S2225
S2447
S2637
Null pointers should not be dereferenced
"toString()" and "clone()" methods should not return null
Null should not be returned from a "Boolean" method
"@NonNull" values should not be set to null
NP_DEREFERENCE_OF_READLINE_VALUE
NP_IMMEDIATE_DEREFERENCE_OF_READLINE
NP_ALWAYS_NULL
NP_NULL_ON_SOME_PATH
NP_NULL_ON_SOME_PATH_EXCEPTION
NP_NULL_PARAM_DEREF
NP_NULL_PARAM_DEREF_NONVIRTUAL
NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS
NP_TOSTRING_COULD_RETURN_NULL
Implemented | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,911 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487911 | 2 | 2 | EXP02-J | Do not use the Object.equals() method to compare two arrays | In Java, arrays are objects and support object methods such as
Object.equals()
. However, arrays do not support any methods besides those provided by
Object
. Consequently, using
Object.equals()
on any array compares only array
references
, not their
contents
. Programmers who wish to compare the contents of two arrays must use the static two-argument
Arrays.equals()
method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to
Object.equals()
. In other words, two arrays are equal if they contain equivalent elements in the same order. To test for reference equality, use the reference equality operators,
==
and
!=
.
Because the effect of using
Object.equals()
to compare two arrays is often misconstrued as content equality, and because a better alternative exists in the use of reference equality operators, the use of the
Object.equals()
method to compare two arrays is disallowed. | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1.equals(arr2)); // Prints false
## Noncompliant Code Example
## This noncompliant code example uses theObject.equals()method to compare two arrays:
#FFCCCC
int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1.equals(arr2)); // Prints false | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(Arrays.equals(arr1, arr2)); // Prints true
int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1 == arr2); // Prints false
## Compliant Solution
## This compliant solution compares the content of two arrays using the two-argumentArrays.equals()method:
#ccccff
int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(Arrays.equals(arr1, arr2)); // Prints true
## Compliant Solution
## This compliant solution compares the array references using the reference equality operators==:
#ccccff
int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1 == arr2); // Prints false | ## Risk Assessment
Using the
equals()
method or relational operators with the intention of comparing array contents produces incorrect results, which can lead to
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP02-J
Low
Likely
Yes
Yes
P9
L2
Automated Detection
Static detection of calls to
Object.equals()
is straightforward. However, it is not always possible to statically resolve the class of a method invocation's target. Consequently, it may not always be possible to determine when
Object.equals()
is invoked for an array type.
Tool
Version
Checker
Description
JAVA.COMPARE.EQ
JAVA.COMPARE.EQARRAY
Should use equals() Instead of ==
equals on Array
7.5
BAD_EQ
FB.EQ_ABSTRACT_SELF
FB.EQ_ALWAYS_FALSE
FB.EQ_ALWAYS_TRUE
FB.EQ_CHECK_FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS
FB.EQ_COMPARETO_USE_OBJECT_ EQUALS
FB.EQ_COMPARING_CLASS_NAMES
FB.EQ_DOESNT_OVERRIDE_EQUALS
FB.EQ_DONT_DEFINE_EQUALS_ FOR_ENUM
FB.EQ_GETCLASS_AND_CLASS_ CONSTANT
FB.EQ_OTHER_NO_OBJECT
FB.EQ_OTHER_USE_OBJECT
FB.EQ_OVERRIDING_EQUALS_ NOT_SYMMETRIC
FB.EQ_SELF_NO_OBJECT
FB.EQ_SELF_USE_OBJECT
FB.EQ_UNUSUAL
Implemented
JD.EQ.ARR
Parasoft Jtest
CERT.EXP02.UEIC
Do not use '==' or '!=' to compare objects
ComparisonArray
Full Implementation
S2159
Silly equality checks should not be made | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,762 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487762 | 2 | 2 | EXP03-J | Do not use the equality operators when comparing values of boxed primitives | The
values
of boxed primitives cannot be directly compared using the
==
and
!=
operators because these operators compare object references rather than object values. Programmers can find this behavior surprising because autoboxing
memoizes
, or caches, the values of some primitive variables. Consequently, reference comparisons and value comparisons produce identical results for the subset of values that are memoized.
Autoboxing automatically wraps a value of a primitive type with the corresponding wrapper object.
The Java Language Specification
(JLS),
§5.1.7, "Boxing Conversion"
[
JLS 2015
], explains which primitive values are memoized during autoboxing:
If the value
p
being boxed is
true
,
false
, a
byte
, a
char
in the range
\u0000
to
\u007f
, or an
int
or
short
number between
-128
and
127
, then let
r1
and
r2
be the results of any two boxing conversions of
p
. It is always the case that
r1 == r2
.
Primitive Type
Boxed Type
Fully Memoized
boolean
,
byte
Boolean
,
Byte
Yes
char
,
short
,
int
Char
,
Short
,
Int
No
Use of the
==
and
!=
operators for comparing the values of fully memoized boxed primitive types is permitted.
Use of the
==
and
!=
operators for comparing the
values
of boxed primitive types that are not fully memoized is permitted only when the range of values represented is guaranteed to be within the ranges specified by the JLS to be fully memoized.
Use of the
==
and
!=
operators for comparing the
values
of boxed primitive types is not allowed in all other cases.
Note that Java Virtual Machine (JVM) implementations are allowed, but not required, to memoize additional values [
JLS 2015
]:
Less memory-limited implementations could, for example, cache all characters and shorts, as well as integers and longs in the range of −32K to +32K. (
§5.1.7
)
Code that depends on implementation-defined behavior is nonportable. It is permissible to depend on implementation-specific ranges of memoized values provided that all targeted implementations support these greater ranges. | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
};
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1 == i2);
System.out.println(i1 != i2);
System.out.println(i3 == i4);
System.out.println(i3 != i4);
}
}
true
false
false
true
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers, where each element
// is greater than 127
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first list
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i) == list2.get(i)) { // Uses '=='
counter++;
}
}
// Print the counter: 0 in this example
System.out.println(counter);
}
}
public void exampleEqualOperator(){
Boolean b1 = new Boolean("true");
Boolean b2 = new Boolean("true");
if (b1 == b2) { // Never equal
System.out.println("Never printed");
}
}
## Noncompliant Code Example
This noncompliant code example defines a
Comparator
with a
compare()
method [
Bloch 2009
]. The
compare()
method accepts two boxed primitives as arguments. The
==
operator is used to compare the two boxed primitives. In this context, however, it compares the
references
to the wrapper objects rather than comparing the
values
held in those objects.
#FFCCCC
import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
};
Note that primitive integers are also accepted by this declaration because they are autoboxed at the call site.
## Noncompliant Code Example
This noncompliant code example uses the
==
operator in an attempt to compare the values of pairs of
Integer
objects. However, the
==
operator compares object references rather than object values.
#FFCCCC
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1 == i2);
System.out.println(i1 != i2);
System.out.println(i3 == i4);
System.out.println(i3 != i4);
}
}
The
Integer
class is guaranteed to cache only integer values from
-128
to
127
, which can result in equivalent values outside this range comparing as unequal when tested using the equality operators. For example, a JVM that did not cache any other values when running this program would output
true
false
false
true
## Noncompliant Code Example
Java Collections contain only objects; they cannot contain primitive types. Further, the type parameters of all Java generics must be object types rather than primitive types. That is, attempting to declare an
ArrayList<int>
(which, presumably, would contain values of type
int
) fails at compile time because type
int
is not an object type. The appropriate declaration would be
ArrayList<Integer>
, which makes use of the wrapper classes and autoboxing.
This noncompliant code example attempts to count the number of indices in arrays
list1
and
list2
that have equivalent values. Recall that class
Integer
is required to
memoize
only those integer values in the range −128 to 127; it might return a nonunique object for any value outside that range. Consequently, when comparing autoboxed integer values outside that range, the
==
operator might return false and the example could deceptively output 0.
#FFCCCC
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers, where each element
// is greater than 127
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first list
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i) == list2.get(i)) { // Uses '=='
counter++;
}
}
// Print the counter: 0 in this example
System.out.println(counter);
}
}
However, if the particular JVM running this code memoized integer values from −32,768 to 32,767, all of the
int
values in the example would have been autoboxed to the corresponding
Integer
objects, and the example code would have operated as expected. Using reference equality instead of object equality requires that all values encountered fall within the interval of values memoized by the JVM. The JLS lacks a specification of this interval; rather, it specifies a minimum range that must be memoized. Consequently, successful prediction of this program's behavior would require implementation-specific details of the JVM.
## Noncompliant Code Example (Boolean)
In this noncompliant code example, constructors for class
Boolean
return distinct newly instantiated objects. Using the reference equality operators in place of value comparisons will yield unexpected results.
#FFCCCC
public void exampleEqualOperator(){
Boolean b1 = new Boolean("true");
Boolean b2 = new Boolean("true");
if (b1 == b2) { // Never equal
System.out.println("Never printed");
}
} | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i > j ? 1 : 0) ;
}
};
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1.equals(i2));
System.out.println(!i1.equals(i2));
System.out.println(i3.equals(i4));
System.out.println(!i3.equals(i4));
}
}
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first one
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i).equals(list2.get(i))) { // Uses 'equals()'
counter++;
}
}
// Print the counter: 10 in this example
System.out.println(counter);
}
}
public void exampleEqualOperator(){
Boolean b1 = true;
Boolean b2 = true;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
b1 = Boolean.TRUE;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
}
## Compliant Solution
This compliant solution uses the comparison operators,
<
,
>
,
<=
, or
>=
, because these cause automatic unboxing of the primitive values. The
==
and
!=
operators should not be used to compare boxed primitives.
#ccccff
import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i > j ? 1 : 0) ;
}
};
## Compliant Solution
This compliant solution uses the
equals()
method instead of the
==
operator to compare the values of the objects. The program now prints
true
,
false
,
true
,
false
on all platforms, as expected.
#CCCCFF
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1.equals(i2));
System.out.println(!i1.equals(i2));
System.out.println(i3.equals(i4));
System.out.println(!i3.equals(i4));
}
}
## Compliant Solution
This compliant solution uses the
equals()
method to perform value comparisons of wrapped objects. It produces the correct output, 10.
#CCCCFF
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first one
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i).equals(list2.get(i))) { // Uses 'equals()'
counter++;
}
}
// Print the counter: 10 in this example
System.out.println(counter);
}
}
## Compliant Solution (Boolean)
Boolean.TRUE
,
Boolean.FALSE
, or the values of autoboxed
true
and
false
literals, may be compared using the reference equality operators because the Java language guarantees that the
Boolean
type is fully memoized. Consequently, these objects are guaranteed to be singletons.
#CCCCFF
public void exampleEqualOperator(){
Boolean b1 = true;
Boolean b2 = true;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
b1 = Boolean.TRUE;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
} | ## Risk Assessment
Using the equivalence operators to compare values of boxed primitives can lead to erroneous comparisons.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP03-J
Low
Likely
Yes
Yes
P9
L2
Automated Detection
Detection of all uses of the reference equality operators on boxed primitive objects is straightforward. Determining the correctness of such uses is infeasible in the general case.
Tool
Version
Checker
Description
JAVA.COMPARE.EMPTYSTR
JAVA.COMPARE.EQ
JAVA.COMPARE.EQARRAY
Comparison to empty string
Should Use equals() instead of == (Java)
equals on Array
7.5
BAD_EQ
FB.EQ_ABSTRACT_SELF
FB.EQ_ALWAYS_FALSE
FB.EQ_ALWAYS_TRUE
FB.EQ_CHECK_FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS
FB.EQ_COMPARETO_USE_OBJECT_ EQUALS
FB.EQ_COMPARING_CLASS_NAMES
FB.EQ_DOESNT_OVERRIDE_EQUALS
FB.EQ_DONT_DEFINE_EQUALS_ FOR_ENUM
FB.EQ_GETCLASS_AND_CLASS_ CONSTANT
FB.EQ_OTHER_NO_OBJECT
FB.EQ_OTHER_USE_OBJECT
FB.EQ_OVERRIDING_EQUALS_ NOT_SYMMETRIC
FB.EQ_SELF_NO_OBJECT
FB.EQ_SELF_USE_OBJECT
FB.EQ_UNUSUAL
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ
FB.ES_COMPARING_STRINGS_ WITH_EQ
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ
Implemented
CMP.OBJ
Parasoft Jtest
CERT.EXP03.UEIC
Do not use '==' or '!=' to compare objects
PVS-Studio
V6013
ComparisonError
Full Implementation
S1698
"==" and "!=" should not be used when "equals" is overridden | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,864 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487864 | 2 | 2 | EXP04-J | Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type | The interfaces of the Java Collections Framework [
JCF 2014
] use generically typed, parameterized methods, such as
add(E e)
and
put(K key, V value)
, to insert objects into the collection or map, but they have other methods, such as
contains()
,
remove()
, and
get()
, that accept an argument of type
Object
rather than a parameterized type. Consequently, these methods accept an object of
any
type. The collections framework interfaces were designed in this manner to
maximize backwards compatibility, but this design can also lead to coding errors. Programmers must ensure that arguments passed to methods such as
Map<K,V>
get()
,
Collection<E>
contains()
, and
remove()
have the same type as the parameterized type of the corresponding class instance. | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i); // Cast required so that the code compiles
s.remove(i); // Tries to remove an Integer
}
System.out.println(s.size());
}
}
## Noncompliant Code Example
After adding and removing 10 elements, the
HashSet
in this noncompliant code example still contains
10
elements and not the expected 0. Java's type checking requires that only values of type
Short
can be inserted into
s
. Consequently, the programmer has added a cast to
short
so that the code will compile. However, the
Collections<E>.remove()
method accepts an argument of type
Object
rather than of type
E
, allowing a programmer to attempt to remove an object of
any
type. In this noncompliant code example, the programmer has neglected to also cast the variable
i
before passing it to the
remove()
method, which is autoboxed into an object of type
Integer
rather than one of type
Short
. The
HashSet
contains only values of type
Short
; the code attempts to remove objects of type
Integer
. Consequently, the
remove()
method has no effect.
#FFCCCC
import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i); // Cast required so that the code compiles
s.remove(i); // Tries to remove an Integer
}
System.out.println(s.size());
}
}
This noncompliant code example also violates
EXP00-J. Do not ignore values returned by methods
because the
remove()
method returns a Boolean value indicating its success. | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i);
// Remove a Short
if (s.remove((short)i) == false) {
System.err.println("Error removing " + i);
}
}
System.out.println(s.size());
}
}
## Compliant Solution
Objects removed from a collection must share the type of the collection elements. Numeric promotion and autoboxing can produce unexpected object types. This compliant solution uses an explicit cast to
short
that matches the intended boxed type.
#CCCCFF
import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i);
// Remove a Short
if (s.remove((short)i) == false) {
System.err.println("Error removing " + i);
}
}
System.out.println(s.size());
}
} | ## Risk Assessment
Passing arguments to certain Java Collection Framework methods that are of a different type from that of the class instance can cause silent failures, resulting in unintended object retention, memory leaks, or incorrect program operation [
Techtalk 2007
].
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP04-J
Low
Probable
Yes
No
P4
L2
Automated Detection
Detection of invocations of
Collection.remove()
whose operand fails to match the type of the elements of the underlying collection is straightforward. It is possible, although unlikely, that some of these invocations could be intended. The remainder are heuristically likely to be in error. Automated detection for other APIs could be possible.
Tool
Version
Checker
Description
PVS-Studio
V6066
IncorrectClassCast
Full Implementation
S2175
Inappropriate "Collection" calls should not be made | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,732 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487732 | 2 | 2 | EXP05-J | Do not follow a write by a subsequent write or read of the same object within an expression | Deprecated
This rule may be deprecated and replaced by a similar guideline.
06/28/2014 -- Version 1.0
According to
The Java Language Specification
(JLS),
§15.7, "Evaluation Order"
[
JLS 2015
]:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
§15.7.3, "Evaluation Respects Parentheses and Precedence"
adds:
Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.
When an expression contains side effects, these two requirements can yield unexpected results. Evaluation of the
operands
proceeds left to right, without regard to operator precedence rules and indicative parentheses; evaluation of the
operators
, however, obeys precedence rules and parentheses.
Expressions must not write to memory that they subsequently read and also must not write to any memory twice. Note that memory reads and writes can occur either directly in the expression from assignments or indirectly through side effects in methods called in the expression. | class BadPrecedence {
public static void main(String[] args) {
int number = 17;
int threshold = 10;
number = (number > threshold ? 0 : -2)
+ ((31 * ++number) * (number = get()));
// ...
if (number == 0) {
System.out.println("Access granted");
} else {
System.out.println("Denied access"); // number = -2
}
}
public static int get() {
int number = 0;
// Assign number to nonzero value if authorized, else 0
return number;
}
}
number = ((31 * ++number) * (number=get())) + (number > threshold ? 0 : -2);
## Noncompliant Code Example (Order of Evaluation)
This noncompliant code example shows how side effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on thresholds. Each user has a rating that must be above the threshold to be granted access. The
get()
method is expected to return a non-zero value for authorized users and a zero value for unauthorized users.
The programmer in this example incorrectly assumes that the rightmost subexpression is evaluated first because the
*
operator has a higher precedence than the
+
operator and because the subexpression is parenthesized. This assumption leads to the incorrect conclusion that
number
is assigned 0 because of the rightmost
number = get()
subexpression. Consequently, the test in the left-hand subexpression is expected to reject the unprivileged user because the value of
number
is below the threshold of
10
.
However, the program grants access to the unauthorized user because evaluation of the side-effect-infested subexpressions follows the left-to-right ordering rule.
#FFcccc
class BadPrecedence {
public static void main(String[] args) {
int number = 17;
int threshold = 10;
number = (number > threshold ? 0 : -2)
+ ((31 * ++number) * (number = get()));
// ...
if (number == 0) {
System.out.println("Access granted");
} else {
System.out.println("Denied access"); // number = -2
}
}
public static int get() {
int number = 0;
// Assign number to nonzero value if authorized, else 0
return number;
}
}
## Noncompliant Code Example (Order of Evaluation)
This noncompliant code example reorders the previous expression so that the left-to-right evaluation order of the operands corresponds with the programmer's intent. Although this code performs as expected, it still represents poor practice by writing to
number
three times in a single expression.
#ffcccc
number = ((31 * ++number) * (number=get())) + (number > threshold ? 0 : -2); | final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold ? 0 : -2);
## Compliant Solution (Order of Evaluation)
This compliant solution uses equivalent code with no side effects and performs not more than one write per expression. The resulting expression can be reordered without concern for the evaluation order of the component expressions, making the code easier to understand and maintain.
#ccccff
final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold ? 0 : -2); | ## Risk Assessment
Failure to understand the evaluation order of expressions containing side effects can result in unexpected output.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP05-J
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Detection of all expressions involving both side effects and multiple operator precedence levels is straightforward. Determining the correctness of such uses is infeasible in the general case; heuristic warnings could be useful.
Tool
Version
Checker
Description
Parasoft Jtest
CERT.EXP05.CID
Avoid using increment or decrement operators in nested expressions
PVS-Studio
V6044
S881
Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,834 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487834 | 2 | 2 | EXP06-J | Expressions used in assertions must not produce side effects | The
assert
statement is a convenient mechanism for incorporating diagnostic tests in code. The behavior of the
assert
statement depends on the status of a runtime property. When enabled, the
assert
statement evaluates its expression argument and throws an
AssertionError
if false. When disabled,
assert
is a no-op; any side effects resulting from evaluation of the expression in the assertion are lost. Consequently, expressions used with the standard
assert
statement must not produce side effects. | private ArrayList<String> names;
void process(int index) {
assert names.remove(null); // Side effect
// ...
}
## Noncompliant Code Example
This noncompliant code attempts to delete all the null names from the list in an assertion. However, the Boolean expression is not evaluated when assertions are disabled.
#ffcccc
private ArrayList<String> names;
void process(int index) {
assert names.remove(null); // Side effect
// ...
} | private ArrayList<String> names;
void process(int index) {
boolean nullsRemoved = names.remove(null);
assert nullsRemoved; // No side effect
// ...
}
## Compliant Solution
The possibility of side effects in assertions can be avoided by decoupling the Boolean expression from the assertion:
#ccccff
private ArrayList<String> names;
void process(int index) {
boolean nullsRemoved = names.remove(null);
assert nullsRemoved; // No side effect
// ...
} | ## Risk Assessment
Side effects in assertions result in program behavior that depends on whether assertions are enabled or disabled.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP06-J
Low
Unlikely
Yes
Yes
P3
L3
Automated Detection
Automated detection of assertion operands that contain locally visible side effects is straightforward. Some analyses could require programmer assistance to determine which method invocations lack side effects.
Tool
Version
Checker
Description
JAVA.STRUCT.SE.ASSERT
Assertion contains side effects
Parasoft Jtest
CERT.EXP06.EASE
Expressions used in assertions must not produce side effects
PVS-Studio
V6055
S3346
Expressions used in "assert" should not produce side effects | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,383 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487383 | 2 | 2 | EXP07-J | Prevent loss of useful data due to weak references | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
If weak references are misused then ...
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP07-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,880 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487880 | 3 | 2 | EXP50-J | Do not confuse abstract object equality with reference equality | Java defines the equality operators
==
and
!=
for testing reference equality but uses the
equals()
method defined in
Object
and its subclasses for testing abstract object equality. Naïve programmers often confuse the intent of the
==
operation with that of the
Object.equals()
method. This confusion is frequently evident in the context of processing
String
objects.
As a general rule, use the
Object.equals()
method to check whether two objects have equivalent contents and use the equality operators
==
and
!=
to test whether two references specifically refer to
the same object
. This latter test is referred to as
referential equality
. For classes that require overriding the default
equals()
implementation, care must be taken to also override the
hashCode()
method (see
MET09-J. Classes that define an equals() method must also define a hashCode() method
).
Numeric boxed types (for example,
Byte
,
Character
,
Short
,
Integer
,
Long
,
Float
, and
Double
) should also be compared using
Object.equals()
rather than the
==
operator. While reference equality may appear to work for
Integer
values between the range −128 and 127, it may fail if either of the operands in the comparison are outside that range. Numeric relational operators other than equality (such as
<
,
<=
,
>
, and
>=
) can be safely used to compare boxed primitive types (see
EXP03-J. Do not use the equality operators when comparing values of boxed primitives
for more information). | public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1 == str2); // Prints "false"
}
}
## Noncompliant Code Example
## This noncompliant code example declares two distinctStringobjects that contain the same value:
#FFcccc
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1 == str2); // Prints "false"
}
}
The reference equality operator
==
evaluates to
true
only when the values it compares refer to the same underlying object. The references in this example are unequal because they refer to distinct objects. | public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1.equals( str2)); // Prints "true"
}
}
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
str1 = str1.intern();
str2 = str2.intern();
System.out.println(str1 == str2); // Prints "true"
}
}
## Compliant Solution (Object.equals())
## This compliant solution uses theObject.equals()method when comparing string values:
#ccccff
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1.equals( str2)); // Prints "true"
}
}
## Compliant Solution (String.intern())
Reference equality behaves like abstract object equality when it is used to compare two strings that are results of the
String.intern()
method. This compliant solution uses
String.intern()
and can perform fast string comparisons when only one copy of the string
one
is required in memory.
#ccccff
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
str1 = str1.intern();
str2 = str2.intern();
System.out.println(str1 == str2); // Prints "true"
}
}
Use of
String.intern()
should be reserved for cases in which the tokenization of strings either yields an important performance enhancement or dramatically simplifies code. Examples include programs engaged in natural language processing and compiler-like tools that tokenize program input. For most other programs, performance and readability are often improved by the use of code that applies the
Object.equals()
approach and that lacks any dependence on reference equality.
The
Java Language Specification
(JLS) [
JLS 2013
] provides very limited guarantees about the implementation of
String.intern()
. For example,
The cost of
String.intern()
grows as the number of intern strings grows. Performance should be no worse than O(
n
log
n
), but the JLS lacks a specific performance guarantee.
In early Java Virtual Machine (JVM) implementations, interned strings became immortal: they were exempt from garbage collection. This can be problematic when large numbers of strings are interned. More recent implementations can garbage-collect the storage occupied by interned strings that are no longer referenced. However, the JLS lacks any specification of this behavior.
In JVM implementations prior to Java 1.7, interned strings are allocated in the
permgen
storage region, which is typically much smaller than the rest of the heap. Consequently, interning large numbers of strings can lead to an out-of-memory condition. In many Java 1.7 implementations, interned strings are allocated on the heap, relieving this restriction. Once again, the details of allocation are unspecified by the JLS; consequently, implementations may vary.
String interning may also be used in programs that accept repetitively occurring strings. Its use boosts the performance of comparisons and minimizes memory consumption.
When canonicalization of objects is required, it may be wiser to use a custom canonicalizer built on top of
ConcurrentHashMap
; see Joshua Bloch's
Effective Java
, second edition, Item 69 [
Bloch 2008
], for details. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,457 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487457 | 3 | 2 | EXP51-J | Do not perform assignments in conditional expressions | Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts:
if
(
controlling expression
)
while
(controlling expression)
do ... while
(controlling expression)
for
(second operand)
switch
(controlling expression)
?:
(first operand)
&&
(either operand)
||
(either operand)
?:
(second or third operands) where the ternary expression is used in any of these contexts
Noncompliant Code Example | public void f(boolean a, boolean b) {
if (a = b) {
/* ... */
}
}
public void f(boolean a, boolean b, boolean flag) {
while ( (a = b) && flag ) {
/* ... */
}
}
## In this noncompliant code example, the controlling expression in theifstatement is an assignment expression:
#FFcccc
public void f(boolean a, boolean b) {
if (a = b) {
/* ... */
}
}
Although the programmer's intent could have been to assign
b
to
a
and test the value of the result, this usage frequently occurs when the programmer mistakenly used the assignment operator
=
rather than the equality operator
==
.
## In this noncompliant code example, an assignment expression appears as an operand of the&&operator:
#FFcccc
public void f(boolean a, boolean b, boolean flag) {
while ( (a = b) && flag ) {
/* ... */
}
}
Because
&&
is not a comparison operator, assignment is an illegal operand. Again, this is frequently a case of the programmer mistakenly using the assignment operator
=
instead of the equals operator
==
. | public void f(boolean a, boolean b) {
if (a == b) {
/* ... */
}
}
public void f(boolean a, boolean b) {
if ((a = b) == true) {
/* ... */
}
}
public void f(boolean a, boolean b) {
a = b;
if (a) {
/* ... */
}
}
public void f(boolean a, boolean b, boolean flag) {
while ( (a == b) && flag ) {
/* ... */
}
}
## Compliant Solution
## The conditional block shown in this compliant solution executes only whenais equal tob:
#ccccff
public void f(boolean a, boolean b) {
if (a == b) {
/* ... */
}
}
Unintended assignment of
b
to
a
cannot occur.
## Compliant Solution
## When the assignment is intended, this compliant solution clarifies the programmer's intent:
#ccccff
public void f(boolean a, boolean b) {
if ((a = b) == true) {
/* ... */
}
}
## Compliant Solution
It may be clearer to express the logic as an explicit assignment followed by the
if
condition:
#ccccff
public void f(boolean a, boolean b) {
a = b;
if (a) {
/* ... */
}
}
Noncompliant Code Example
## Compliant Solution
When the assignment of
b
to
a
is unintended, this conditional block is now executed only when
a
is equal to
b
and
flag
is
true
:
#ccccff
public void f(boolean a, boolean b, boolean flag) {
while ( (a == b) && flag ) {
/* ... */
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,475 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487475 | 3 | 2 | EXP52-J | Use braces for the body of an if, for, or while statement | Use opening and closing braces for
if
,
for
, and
while
statements even when the body contains only a single statement. Braces improve the uniformity and readability of code.
More important, it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, because the conventional indentation gives strong (but misleading) guidance to the structure. | int login;
if (invalid_login())
login = 0;
else
login = 1;
int login;
if (invalid_login())
login = 0;
else
// Debug line added below
System.out.println("Login is valid\n");
// The next line is always executed
login = 1;
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUEST;
else
privileges = ADMINISTRATOR;
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUEST;
else
privileges = ADMINISTRATOR;
## Noncompliant Code Example
## This noncompliant code example authenticates a user with anifstatement that lacks braces:
#ffcccc
int login;
if (invalid_login())
login = 0;
else
login = 1;
This program behaves as expected. However, a maintainer might subsequently add a debug statement or other logic but forget to add opening and closing braces:
#ffcccc
int login;
if (invalid_login())
login = 0;
else
// Debug line added below
System.out.println("Login is valid\n");
// The next line is always executed
login = 1;
The code's indentation disguises the functionality of the program, potentially leading to a security breach.
## Noncompliant Code Example
## This noncompliant code example nests anifstatement within anotherifstatement, without braces around theifandelsebodies:
#ffcccc
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUEST;
else
privileges = ADMINISTRATOR;
The indentation might lead the programmer to believe users are granted administrator privileges only when their login is valid. However, the
else
statement actually binds to the inner
if
statement:
#ffcccc
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUEST;
else
privileges = ADMINISTRATOR;
Consequently, this defect allows unauthorized users to obtain administrator privileges. | int login;
if (invalid_login()) {
login = 0;
} else {
login = 1;
}
int privileges;
if (invalid_login()) {
if (allow_guests()) {
privileges = GUEST;
}
} else {
privileges = ADMINISTRATOR;
}
## Compliant Solution
This compliant solution uses opening and closing braces even though the body of the
if
and
else
bodies of the if statement are single statements:
#CCCCFF
int login;
if (invalid_login()) {
login = 0;
} else {
login = 1;
}
## Compliant Solution
This compliant solution uses braces to remove the ambiguity, consequently ensuring that privileges are correctly assigned:
#CCCCFF
int privileges;
if (invalid_login()) {
if (allow_guests()) {
privileges = GUEST;
}
} else {
privileges = ADMINISTRATOR;
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,527 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487527 | 3 | 2 | EXP53-J | Use parentheses for precedence of operation | Programmers frequently make errors regarding the precedence of operators because of the unintuitively low precedence levels of
&
,
|
,
^
,
<<
, and
>>
. Avoid mistakes regarding precedence through the suitable use of parentheses, which also improves code readability. The precedence of operations by the order of the subclauses is defined in the Java Tutorials [
Tutorials 2013
].
Although it advises against depending on parentheses for specifying evaluation order
applies only to expressions that contain side effects. | public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return x & MASK + OFFSET;
}
x & (MASK + OFFSET)
x & (1337 - 1337)
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "1"
System.out.println("value=" + s == null ? 0 : 1);
}
}
## Noncompliant Code Example
The intent of the expression in this noncompliant code example is to add the variable
OFFSET
to the result of the bitwise logical AND between
x
and
MASK
:
#FFCCCC
public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return x & MASK + OFFSET;
}
According to the operator precedence guidelines, the expression is parsed as the following:
x & (MASK + OFFSET)
This expression is evaluated as follows, resulting in the value 0:
x & (1337 - 1337)
## Noncompliant Code Example
## In this noncompliant code example, the intent is to append either "0" or "1" to the string "value=":
#FFCCCC
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "1"
System.out.println("value=" + s == null ? 0 : 1);
}
}
However, the precedence rules result in the expression to be printed being parsed as
("value=" + s) == null ? 0 : 1
. | public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return (x & MASK) + OFFSET;
}
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "value=0" as expected
System.out.println("value=" + (s == null ? 0 : 1));
}
}
## Compliant Solution
## This compliant solution uses parentheses to ensure that the expression is evaluated as intended:
#ccccff
public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return (x & MASK) + OFFSET;
}
## Compliant Solution
## This compliant solution uses parentheses to ensure that the expression evaluates as intended:
#ccccff
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "value=0" as expected
System.out.println("value=" + (s == null ? 0 : 1));
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,424 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487424 | 3 | 2 | EXP54-J | Understand the differences between bitwise and logical operators | The conditional AND and OR operators (
&&
and
||
respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result of the conditional operator cannot be deduced solely by evaluating the first operand. Consequently, when the result of the conditional operator
can
be deduced solely from the result of the first operand, the second operand will remain unevaluated; its side effects, if any, will never occur.
The bitwise AND and OR operators (
&
and
|
) lack short-circuit behavior. Similar to most Java operators, they evaluate both operands. They return the same Boolean result as
&&
and
||
respectively but can have different overall effects depending on the presence or absence of side effects in the second operand.
Consequently, either the
&
or the
&&
operator can be used when performing Boolean logic. However, there are times when the short-circuiting behavior is preferred and other times when the short-circuiting behavior causes subtle bugs. | int array[]; // May be null
int i; // May be an invalid index for array
if (array != null & i >= 0 & i < array.length & array[i] >= 0) {
// Use array
} else {
// Handle error
}
if (end1 >= 0 & i2 >= 0) {
int begin1 = i1;
int begin2 = i2;
while (++i1 < array1.length &&
++i2 < array2.length &&
array1[i1] == array2[i2]) {
// Arrays match so far
}
int end1 = i1;
int end2 = i2;
assert end1 - begin1 == end2 - begin2;
}
## Noncompliant Code Example (Improper&)
This noncompliant code example, derived from Flanagan [
Flanagan 2005
], has two variables with unknown variables. The code must validate its data and then check whether
array[i]
is a valid index.
#ffcccc
int array[]; // May be null
int i; // May be an invalid index for array
if (array != null & i >= 0 & i < array.length & array[i] >= 0) {
// Use array
} else {
// Handle error
}
This code can fail as a result of the same errors it is trying to prevent. When
array
is
NULL
or
i
is not a valid index, the reference to
array
and
array[i]
will cause either a
NullPointerException
or an
ArrayIndexOutOfBoundsException
to be thrown. The exception occurs because the
&
operator fails to prevent evaluation of its right operand even when evaluation of its left operand proves that the right operand is inconsequential.
## Noncompliant Code Example (Improper&&)
This noncompliant code example demonstrates code that compares two arrays for ranges of members that match. Here
i1
and
i2
are valid array indices in
array1
and
array2
respectively. Variables
end1
and
end2
are the indices of the ends of the matching ranges in the two arrays.
#ffcccc
if (end1 >= 0 & i2 >= 0) {
int begin1 = i1;
int begin2 = i2;
while (++i1 < array1.length &&
++i2 < array2.length &&
array1[i1] == array2[i2]) {
// Arrays match so far
}
int end1 = i1;
int end2 = i2;
assert end1 - begin1 == end2 - begin2;
}
The problem with this code is that when the first condition in the
while
loop fails, the second condition does not execute. That is, once
i1
has reached
array1.length
, the loop terminates after
i1
is incremented. Consequently, the apparent range over
array1
is larger than the apparent range over
array2
, causing the final assertion to fail. | int array[]; // May be null
int i; // May be an invalid index for array
if (array != null && i >= 0 &&
i < array.length && array[i] >= 0) {
// Handle array
} else {
// Handle error
}
int array[]; // May be null
int i; // May be a valid index for array
if (array != null) {
if (i >= 0 && i < array.length) {
if (array[i] >= 0) {
// Use array
} else {
// Handle error
}
} else {
// Handle error
}
} else {
// Handle error
}
public void exampleFunction() {
while (++i1 < array1.length & // Not &&
++i2 < array2.length &&
array1[i1] == array2[i2]){
//doSomething
}
}
## Compliant Solution (Use&&)
This compliant solution mitigates the problem by using
&&
, which causes the evaluation of the conditional expression to terminate immediately if any of the conditions fail, thereby preventing a runtime exception:
#ccccff
int array[]; // May be null
int i; // May be an invalid index for array
if (array != null && i >= 0 &&
i < array.length && array[i] >= 0) {
// Handle array
} else {
// Handle error
}
## Compliant Solution (NestedifStatements)
## This compliant solution uses multipleifstatements to achieve the proper effect.
#ccccff
int array[]; // May be null
int i; // May be a valid index for array
if (array != null) {
if (i >= 0 && i < array.length) {
if (array[i] >= 0) {
// Use array
} else {
// Handle error
}
} else {
// Handle error
}
} else {
// Handle error
}
Although correct, this solution is more verbose and could be more difficult to maintain. Nevertheless, this solution is preferable when the error-handling code for each potential failure condition is different.
## Compliant Solution (Use&)
This compliant solution mitigates the problem by judiciously using
&
, which guarantees that both
i1
and
i2
are incremented regardless of the outcome of the first condition:
#ccccff
public void exampleFunction() {
while (++i1 < array1.length & // Not &&
++i2 < array2.length &&
array1[i1] == array2[i2]){
//doSomething
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,397 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487397 | 3 | 2 | EXP55-J | Use the same type for the second and third operands in conditional expressions | The conditional operator
?:
uses the
boolean
value of its first operand to decide which of the other two expressions will be evaluated. (See
§15.25, "Conditional Operator
? :
"
of the
Java Language Specification
(JLS) [
JLS 2013
].)
The general form of a Java conditional expression is
operand1 ? operand2 : operand3
.
If the value of the first operand (
operand1
) is
true
, then the second operand expression (
operand2
) is chosen.
If the value of the first operand is
false
, then the third operand expression (
operand3
) is chosen.
The conditional operator is syntactically right-associative. For example,
a?b:c?d:e?f:g
is equivalent to
a?b:(c?d:(e?f:g))
.
The JLS rules for determining the result type of a conditional expression (see following table) are complicated; programmers could be surprised by the type conversions required for expressions they have written.
Result type determination begins from the top of the table; the compiler applies the first matching rule. The Operand 2 and Operand 3 columns refer to
operand2
and
operand3
(from the previous definition) respectively. In the table,
constant int
refers to constant expressions of type
int
(such as
'0'
or variables declared
final
).
For the final table row, S1 and S2 are the types of the second and third operands respectively. T1 is the type that results from applying boxing conversion to S1, and T2 is the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion to S2. The type of the conditional expression is the result of applying capture conversion to the least upper bound of T1 and T2. See
§5.1.7, "Boxing Conversion,"
§5.1.10, "Capture Conversion,"
and
§15.12.2.7, "Inferring Type Arguments Based on Actual Arguments,"
of the JLS for additional information [
JLS 2013
].
Determining the Result Type of a Conditional Expression
Rule
Operand 2
Operand 3
Resultant Type
1
Type T
Type T
Type T
2
boolean
Boolean
boolean
3
Boolean
boolean
boolean
4
null
reference
reference
5
reference
null
reference
6
byte
or
Byte
short
or
Short
short
7
short
or
Short
byte
or
Byte
short
8
byte
,
short
,
char
,
Byte
,
Short
,
Character
constant int
byte
,
short
,
char
if value of
int
is representable
9
constant int
byte
,
short
,
char
,
Byte
,
Short
,
Character
byte
,
short
,
char
if value of
int
is representable
10
Other numeric
Other numeric
Promoted type of the second and third operands
11
T1 = boxing conversion(S1)
T2 = boxing conversion(S2)
Apply capture conversion to lub(T1,T2)
The complexity of the rules that determine the result type of a conditional expression can lead to unintended type conversions. Consequently, the second and third operands of each conditional expression should have identical types. This recommendation also applies to boxed primitives. | public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
// Other code. Value of i may change
boolean trueExp = true; // Some expression that evaluates to true
System.out.print(trueExp ? alpha : 0); // prints A
System.out.print(trueExp ? alpha : i); // prints 65
}
}
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
// Cast of i-1 is safe because value is always representable
Short workingVal = (short) (i-1);
// ... Other code may update workingVal
s.remove(((i % 2) == 1) ? i-1 : workingVal);
}
System.out.println(s.size());
}
}
## Noncompliant Code Example
In this noncompliant code example, the programmer expects that both print statements will print the value of
alpha
as a
char
:
#FFCCCC
public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
// Other code. Value of i may change
boolean trueExp = true; // Some expression that evaluates to true
System.out.print(trueExp ? alpha : 0); // prints A
System.out.print(trueExp ? alpha : i); // prints 65
}
}
The first print statement prints
A
because the compiler applies rule 8 from the result type determination table to determine that the second and third operands of the conditional expression are, or are converted to, type
char
. However, the second print statement prints
65
—the value of
alpha
as an
int
. The first matching rule from the table is rule 10. Consequently, the compiler promotes the value of
alpha
to type
int
.
## Noncompliant Code Example
This noncompliant code example prints 100 as the size of the
HashSet
rather than the expected result (some value between 0 and 50):
#FFCCCC
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
// Cast of i-1 is safe because value is always representable
Short workingVal = (short) (i-1);
// ... Other code may update workingVal
s.remove(((i % 2) == 1) ? i-1 : workingVal);
}
System.out.println(s.size());
}
}
The combination of values of types
short
and
int
in the second argument of the conditional expression (the operation
i-1
) causes the result to be an
int
, as specified by the integer promotion rules. Consequently, the
Short
object in the third argument is unboxed into a
short
, which is then promoted into an
int
. The result of the conditional expression is then autoboxed into an object of type
Integer
. Because the
HashSet
contains only values of type
Short
, the call to
HashSet.remove()
has no effect. | public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
boolean trueExp = true; // Expression that evaluates to true
System.out.print(trueExp ? alpha : ((char) 0)); // Prints A
// Deliberate narrowing cast of i; possible truncation OK
System.out.print(trueExp ? alpha : ((char) i)); // Prints A
}
}
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
// Cast of i-1 is safe because the resulting value is always representable
Short workingVal = (short) (i-1);
// ... Other code may update workingVal
// Cast of i-1 is safe because the resulting value is always representable
s.remove(((i % 2) == 1) ? Short.valueOf((short) (i-1)) : workingVal);
}
System.out.println(s.size());
}
}
## Compliant Solution
This compliant solution uses identical types for the second and third operands of each conditional expression; the explicit casts specify the type expected by the programmer:
#ccccff
public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
boolean trueExp = true; // Expression that evaluates to true
System.out.print(trueExp ? alpha : ((char) 0)); // Prints A
// Deliberate narrowing cast of i; possible truncation OK
System.out.print(trueExp ? alpha : ((char) i)); // Prints A
}
}
When the value of
i
in the second conditional expression falls outside the range that can be represented as a
char
, the explicit cast will truncate its value. This usage complies with exception
NUM12-J-EX0
of
NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data
.
## Compliant Solution
This compliant solution casts the second operand to type
short
, then explicitly invokes the
Short.valueOf()
method to create a
Short
instance whose value is
i-1
:
#ccccff
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
// Cast of i-1 is safe because the resulting value is always representable
Short workingVal = (short) (i-1);
// ... Other code may update workingVal
// Cast of i-1 is safe because the resulting value is always representable
s.remove(((i % 2) == 1) ? Short.valueOf((short) (i-1)) : workingVal);
}
System.out.println(s.size());
}
}
As a result of the cast, the second and third operands of the conditional expression both have type
Short
, and the
remove()
call has the expected result.
Writing the conditional expression as
((i % 2) == 1) ? (short) (i-1)) : workingVal
also complies with this guideline because both the second and third operands in this form have type
short
. However, this alternative is less efficient because it forces unboxing of
workingVal
on each even iteration of the loop and autoboxing of the result of the conditional expression (from
short
to
Short
) on every iteration of the loop. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,585 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487585 | 2 | 13 | FIO00-J | Do not operate on files in shared directories | Multiuser systems allow multiple users with different privileges to share a file system. Each user in such an environment must be able to determine which files are shared and which are private, and each user must be able to enforce these decisions.
Unfortunately, a wide variety of file system
vulnerabilities
can be
exploited
by an attacker to gain access to files for which they lack sufficient privileges, particularly when operating on files that reside in shared directories in which multiple users may create, move, or delete files. Privilege escalation is also possible when these programs run with elevated privileges. A number of file system properties and capabilities can be exploited by an attacker, including
file links
,
device files
, and
shared file access
. To prevent vulnerabilities, a program must operate only on files in
secure directories
.
A directory is secure with respect to a particular user if only the user and the system administrator are allowed to create, move, or delete files inside the directory. Furthermore, each parent directory must itself be a secure directory up to and including the root directory. On most systems, home or user directories are secure by default and only shared directories are insecure.
File Links
Similar to shared files, file links can be swapped out and may not always point to the intended location. As a result, file links in shared directories are untrusted and should not be operated on (see
FIO15-J. Do not operate on untrusted file links
).
Device Files
File names on many operating systems may be used to access device files. Device files are used to access hardware and peripherals. Reserved MS-DOS device names include
AUX
,
CON
,
PRN
,
COM1
, and
LPT1
. Character special files and block special files are POSIX device files that direct operations on the files to the appropriate device drivers.
Performing operations on device files intended only for ordinary character or binary files can result in crashes and
denial-of-service (DoS) attacks
. For example, when Windows attempts to interpret the device name as a file resource, it performs an invalid resource access that usually results in a crash [
Howard 2002
].
Device files in POSIX can be a security risk when an attacker can access them in an unauthorized way. For instance, if malicious programs can read or write to the
/dev/kmem
device, they may be able to alter their own priority, user ID, or other attributes of their process or they may simply crash the system. Similarly, access to disk devices, tape devices, network devices, and terminals being used by other processes can also lead to problems [
Garfinkel 1996
].
On Linux, it is possible to lock certain applications by attempting to read or write data on devices rather than files. Consider the following device path names:
/dev/mouse
/dev/console
/dev/tty0
/dev/zero
A Web browser that failed to check for these devices would allow an attacker to create a website with image tags such as
<IMG src="file:///dev/mouse">
that would lock the user's mouse.
Shared File Access
On many systems, files can be simultaneously accessed by concurrent processes. Exclusive access grants unrestricted file access to the locking process while denying access to all other processes, eliminating the potential for a
race condition
on the locked region. The
java.nio.channels.FileLock
class may be used for file locking. According to the Java API,
Class FileLock
[
API 2014
], documentation,
A file lock is either
exclusive
or
shared
. A shared lock prevents other concurrently running programs from acquiring an overlapping exclusive lock but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs.
Shared locks
support concurrent read access from multiple processes;
exclusive locks
support exclusive write access. File locks provide protection across processes, but they do not provide protection from multiple threads within a single process. Both shared locks and exclusive locks eliminate the potential for a cross-process race condition on the locked region. Exclusive locks provide mutual exclusion; shared locks prevent alteration of the state of the locked file region (one of the required properties for a
data race
).
The Java API [
API 2014
] documentation states that "whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and consequently unspecified."
Microsoft Windows uses a mandatory file-locking mechanism that prevents processes from accessing a locked file region.
Linux implements both mandatory locks and advisory locks. Advisory locks are not enforced by the operating system, which diminishes their value from a security perspective. Unfortunately, the mandatory file lock in Linux is generally impractical for the following reasons:
Mandatory locking is supported only by certain network file systems.
File systems must be mounted with support for mandatory locking, which is disabled by default.
Locking relies on the group ID bit, which can be turned off by another process (thereby defeating the lock).
The lock is implicitly dropped if the holding process closes any descriptor of the file. | String file = /* Provided by user */;
InputStream in = null;
try {
in = new FileInputStream(file);
// ...
} finally {
try {
if (in !=null) { in.close();}
} catch (IOException x) {
// Handle error
}
}
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try (InputStream in = Files.newInputStream(path)) {
// Read file
} catch (IOException x) {
// Handle error
}
String filename = /* Provided by user */
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr =
Files.readAttributes(path, BasicFileAttributes.class);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Read file
}
} catch (IOException x) {
// Handle error
}
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Read file
};
} catch (IOException x) {
// Handle error
}
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
Object fileKey = attr.fileKey();
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Check
BasicFileAttributes attr2 = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS
);
Object fileKey2 = attr2.fileKey();
if (!fileKey.equals(fileKey2)) {
System.out.println("File has been tampered with");
}
// Read file
};
} catch (IOException x) {
// Handle error
}
## Noncompliant Code Example
In this noncompliant code example, an attacker could specify the name of a locked device or a first in, first out (FIFO) file, causing the program to hang when opening the file:
#ffcccc
String file = /* Provided by user */;
InputStream in = null;
try {
in = new FileInputStream(file);
// ...
} finally {
try {
if (in !=null) { in.close();}
} catch (IOException x) {
// Handle error
}
}
## Noncompliant Code Example
This noncompliant code example uses the
try
-with-resources
statement (introduced in Java SE 7) to open the file. The
try
-with-resources statement guarantees the file's successful closure if an exception is thrown, but this code is subject to the same
vulnerabilities
as the previous example.
#ffcccc
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try (InputStream in = Files.newInputStream(path)) {
// Read file
} catch (IOException x) {
// Handle error
}
## Noncompliant Code Example (isRegularFile())
## This noncompliant code example first checks that the file is a regular file (using theNIO.2 API) before opening it:
#ffcccc
String filename = /* Provided by user */
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr =
Files.readAttributes(path, BasicFileAttributes.class);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Read file
}
} catch (IOException x) {
// Handle error
}
This test can still be circumvented by a symbolic link. By default, the
readAttributes()
method follows symbolic links and reads the file attributes of the final target of the link. The result is that the program may reference a file other than the one intended.
## Noncompliant Code Example (NOFOLLOW_LINKS)
This noncompliant code example checks the file by calling the
readAttributes()
method with the
NOFOLLOW_LINKS
link option to prevent the method from following symbolic links. This approach allows the detection of symbolic links because the
isRegularFile()
check is carried out on the symbolic link file and not on the final target of the link.
#ffcccc
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Read file
};
} catch (IOException x) {
// Handle error
}
This code is still vulnerable to a time-of-check, time-of-use (TOCTOU)
race condition
. For example, an attacker can replace the regular file with a file link or device file after the code has completed its checks but before it opens the file.
## Noncompliant Code Example (POSIX: Check-Use-Check)
This noncompliant code example performs the necessary checks and then opens the file. After opening the file, it performs a second check to make sure that the file has not been moved and that the file opened is the same file that was checked. This approach reduces the chance that an attacker has changed the file between checking and then opening the file. In both checks, the file's
fileKey
attribute is examined. The
fileKey
attribute serves as a unique key for identifying files and is more reliable than the path name as on indicator of the file's identity.
The SE 7 Documentation [
J2SE 2011
] describes the
fileKey
attribute:
Returns an object that uniquely identifies the given file, or null if a file key is not available. On some platforms or file systems it is possible to use an identifier, or a combination of identifiers to uniquely identify a file. Such identifiers are important for operations such as file tree traversal in file systems that support symbolic links or file systems that allow a file to be an entry in more than one directory. On UNIX file systems, for example, the device ID and inode are commonly used for such purposes.
The file key returned by this method can only be guaranteed to be unique if the file system and files remain static. Whether a file system re-uses identifiers after a file is deleted is implementation dependent and consequently unspecified.
File keys returned by this method can be compared for equality and are suitable for use in collections. If the file system and files remain static, and two files are the same with non-null file keys, then their file keys are equal.
As noted in the documentation,
FileKey
cannot be used if it is not available. The
fileKey()
method returns
null
on Windows. Consequently, this solution is available only on systems such as POSIX in which
fileKey()
does not return
null
.
#ffcccc
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
Object fileKey = attr.fileKey();
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
// Use
try (InputStream in = Files.newInputStream(path)) {
// Check
BasicFileAttributes attr2 = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS
);
Object fileKey2 = attr2.fileKey();
if (!fileKey.equals(fileKey2)) {
System.out.println("File has been tampered with");
}
// Read file
};
} catch (IOException x) {
// Handle error
}
Although this code goes to great lengths to prevent an attacker from successfully tricking it into opening the wrong file, it still has several
vulnerabilities
:
The TOCTOU race condition still exists between the first check and open. During this race window, an attacker can replace the regular file with a symbolic link or other nonregular file. The second check detects this
race condition
but does not eliminate it.
An attacker could subvert this code by letting the check operate on a regular file, substituting the nonregular file for the open, and then resubstituting the regular file to circumvent the second check. This vulnerability exists because Java lacks a mechanism to obtain file attributes from a file by any means other than the file name, and the binding of the file name to a file object is reasserted every time the file name is used in an operation. Consequently, an attacker can still swap a file for a nefarious file, such as a symbolic link.
A system with hard links allows an attacker to construct a malicious file that is a hard link to a protected file. Hard links cannot be reliably detected by a program and can foil
canonicalization
attempts, which are prescribed by
. | public static boolean isInSecureDir(Path file) {
return isInSecureDir(file, null);
}
public static boolean isInSecureDir(Path file, UserPrincipal user) {
return isInSecureDir(file, user, 5);
}
/**
* Indicates whether file lives in a secure directory relative
* to the program's user
* @param file Path to test
* @param user User to test. If null, defaults to current user
* @param symlinkDepth Number of symbolic links allowed
* @return true if file's directory is secure.
*/
public static boolean isInSecureDir(Path file, UserPrincipal user,
int symlinkDepth) {
if (!file.isAbsolute()) {
file = file.toAbsolutePath();
} if (symlinkDepth <=0) {
// Too many levels of symbolic links
return false;
}
// Get UserPrincipal for specified user and superuser
FileSystem fileSystem =
Paths.get(file.getRoot().toString()).getFileSystem();
UserPrincipalLookupService upls =
fileSystem.getUserPrincipalLookupService();
UserPrincipal root = null;
try {
root = upls.lookupPrincipalByName("root");
if (user == null) {
user = upls.lookupPrincipalByName(System.getProperty("user.name"));
}
if (root == null || user == null) {
return false;
}
} catch (IOException x) {
return false;
}
// If any parent dirs (from root on down) are not secure,
// dir is not secure
for (int i = 1; i <= file.getNameCount(); i++) {
Path partialPath = Paths.get(file.getRoot().toString(),
file.subpath(0, i).toString());
try {
if (Files.isSymbolicLink(partialPath)) {
if (!isInSecureDir(Files.readSymbolicLink(partialPath),
user, symlinkDepth - 1)) {
// Symbolic link, linked-to dir not secure
return false;
}
} else {
UserPrincipal owner = Files.getOwner(partialPath);
if (!user.equals(owner) && !root.equals(owner)) {
// dir owned by someone else, not secure
return false;
}
PosixFileAttributes attr =
Files.readAttributes(partialPath, PosixFileAttributes.class);
Set<PosixFilePermission> perms = attr.permissions();
if (perms.contains(PosixFilePermission.GROUP_WRITE) ||
perms.contains(PosixFilePermission.OTHERS_WRITE)) {
// Someone else can write files, not secure
return false;
}
}
} catch (IOException x) {
return false;
}
}
return true;
}
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
if (!isInSecureDir(path)) {
System.out.println("File not in secure directory");
return;
}
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
try (InputStream in = Files.newInputStream(path)) {
// Read file
}
} catch (IOException x) {
// Handle error
}
## Compliant Solution (POSIX: Secure Directory)
Because of the potential for race conditions and the inherent accessibility of shared directories, files must be operated on only in secure directories. Because programs may run with reduced privileges and lack the facilities to construct a secure directory, a program may need to throw an exception if it determines that a given path name is not in a secure directory.
Following is a POSIX-specific implementation of an
isInSecureDir()
method. This method ensures that the supplied file and all directories above it are owned by either the user or the system administrator, that each directory lacks write access for any other users, and that directories above the given file may not be deleted or renamed by any users other than the system administrator.
#ccccff
public static boolean isInSecureDir(Path file) {
return isInSecureDir(file, null);
}
public static boolean isInSecureDir(Path file, UserPrincipal user) {
return isInSecureDir(file, user, 5);
}
/**
* Indicates whether file lives in a secure directory relative
* to the program's user
* @param file Path to test
* @param user User to test. If null, defaults to current user
* @param symlinkDepth Number of symbolic links allowed
* @return true if file's directory is secure.
*/
public static boolean isInSecureDir(Path file, UserPrincipal user,
int symlinkDepth) {
if (!file.isAbsolute()) {
file = file.toAbsolutePath();
} if (symlinkDepth <=0) {
// Too many levels of symbolic links
return false;
}
// Get UserPrincipal for specified user and superuser
FileSystem fileSystem =
Paths.get(file.getRoot().toString()).getFileSystem();
UserPrincipalLookupService upls =
fileSystem.getUserPrincipalLookupService();
UserPrincipal root = null;
try {
root = upls.lookupPrincipalByName("root");
if (user == null) {
user = upls.lookupPrincipalByName(System.getProperty("user.name"));
}
if (root == null || user == null) {
return false;
}
} catch (IOException x) {
return false;
}
// If any parent dirs (from root on down) are not secure,
// dir is not secure
for (int i = 1; i <= file.getNameCount(); i++) {
Path partialPath = Paths.get(file.getRoot().toString(),
file.subpath(0, i).toString());
try {
if (Files.isSymbolicLink(partialPath)) {
if (!isInSecureDir(Files.readSymbolicLink(partialPath),
user, symlinkDepth - 1)) {
// Symbolic link, linked-to dir not secure
return false;
}
} else {
UserPrincipal owner = Files.getOwner(partialPath);
if (!user.equals(owner) && !root.equals(owner)) {
// dir owned by someone else, not secure
return false;
}
PosixFileAttributes attr =
Files.readAttributes(partialPath, PosixFileAttributes.class);
Set<PosixFilePermission> perms = attr.permissions();
if (perms.contains(PosixFilePermission.GROUP_WRITE) ||
perms.contains(PosixFilePermission.OTHERS_WRITE)) {
// Someone else can write files, not secure
return false;
}
}
} catch (IOException x) {
return false;
}
}
return true;
}
When checking directories, it is important to traverse from the root directory to the leaf directory to avoid a dangerous
race condition
whereby an attacker who has privileges to at least one of the directories can rename and re-create a directory after the privilege verification of subdirectories but before the verification of the tampered directory.
If the path contains any symbolic links, this routine will recursively invoke itself on the linked-to directory and ensure it is also secure. A symlinked directory may be secure if both its source and linked-to directory are secure. The method checks every directory in the path, ensuring that every directory is owned by the current user or the system administrator and that all directories in the path prevent other users from creating, deleting, or renaming files.
On POSIX systems, disabling group and world write access to a directory prevents modification by anyone other than the owner of the directory and the system administrator.
Note that this method is effective only on file systems that are fully compatible with POSIX file access permissions; it may behave incorrectly for file systems with other permission mechanisms.
The following compliant solution uses the
isInSecureDir()
method to ensure that an attacker cannot tamper with the file to be opened and subsequently removed. Note that once the path name of a directory has been checked using
isInSecureDir()
, all further file operations on that directory must be performed using the same path. This compliant solution also performs the same checks performed by the previous examples, such as making sure the requested file is a regular file, and not a symbolic link, device file, or other special file.
#ccccff
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try {
if (!isInSecureDir(path)) {
System.out.println("File not in secure directory");
return;
}
BasicFileAttributes attr = Files.readAttributes(
path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Check
if (!attr.isRegularFile()) {
System.out.println("Not a regular file");
return;
}
// Other necessary checks
try (InputStream in = Files.newInputStream(path)) {
// Read file
}
} catch (IOException x) {
// Handle error
}
Programs with elevated privileges may need to write files to directories owned by unprivileged users. One example is a mail daemon that reads a mail message from one user and places it in a directory owned by another user. In such cases, the mail daemon should assume the privileges of a user when reading or writing files on behalf of that user, in which case all file access should occur in secure directories relative to that user. When a program with elevated privileges must write files on its own behalf, these files should be in secure directories relative to the privileges of the program (such as directories accessible only by the system administrator). | ## Risk Assessment
Performing operations on files in shared directories can result in
DoS attacks
. If the program has elevated privileges, privilege escalation
exploits
are possible.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO00-J
Medium
Unlikely
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,592 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487592 | 2 | 13 | FIO01-J | Create files with appropriate access permissions | Files on multiuser systems are generally owned by a particular user. The owner of the file can specify which other users on the system should be allowed to access the contents of these files.
These file systems use a privileges and permissions model to protect file access. When a file is created, the file access permissions dictate who may access or operate on the file. When a program creates a file with insufficiently restrictive access permissions, an attacker may read or modify the file before the program can modify the permissions. Consequently, files must be created with access permissions that prevent unauthorized file access. | Writer out = new FileWriter("file");
## Noncompliant Code Example
The constructors for
FileOutputStream
and
FileWriter
do not allow the programmer to explicitly specify file access permissions. In this noncompliant code example, the access permissions of any file created are
implementation-defined
and may not prevent unauthorized access:
#FFCCCC
Writer out = new FileWriter("file"); | Path file = new File("file").toPath();
// Throw exception rather than overwrite existing file
Set<OpenOption> options = new HashSet<OpenOption>();
options.add(StandardOpenOption.CREATE_NEW);
options.add(StandardOpenOption.APPEND);
// File permissions should be such that only user may read/write file
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
try (SeekableByteChannel sbc =
Files.newByteChannel(file, options, attr)) {
// Write data
};
## Compliant Solution (Java 1.6 and Earlier)
Java 1.6 and earlier lack a mechanism for specifying default permissions upon file creation. Consequently, the problem must be avoided or solved using some mechanism external to Java, such as by using native code and the Java Native Interface (JNI).
## Compliant Solution (POSIX)
The I/O facility
java.nio
provides classes for managing file access permissions. Additionally, many of the methods and constructors that create files accept an argument allowing the program to specify the initial file permissions.
The
Files.newByteChannel()
method allows a file to be created with specific permissions. This method is platform-independent, but the actual permissions are platform-specific. This compliant solution defines sufficiently restrictive permissions for POSIX platforms:
#ccccff
Path file = new File("file").toPath();
// Throw exception rather than overwrite existing file
Set<OpenOption> options = new HashSet<OpenOption>();
options.add(StandardOpenOption.CREATE_NEW);
options.add(StandardOpenOption.APPEND);
// File permissions should be such that only user may read/write file
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
try (SeekableByteChannel sbc =
Files.newByteChannel(file, options, attr)) {
// Write data
}; | ## Risk Assessment
If files are created without appropriate permissions, an attacker may read or write to the files, possibly resulting in compromised system integrity and information disclosure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO01-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,501 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487501 | 2 | 13 | FIO02-J | Detect and handle file-related errors | Java's file-manipulation methods often indicate failure with a return value instead of throwing an exception. Consequently, programs that ignore the return values from file operations often fail to detect that those operations have failed. Java programs must check the return values of methods that perform file I/O. This is a specific instance of
. | File file = new File(args[0]);
file.delete();
## Noncompliant Code Example (delete())
This noncompliant code example attempts to delete a specified file but gives no indication of its success. The Java platform requires
File.delete()
to throw a
SecurityException
only when the program lacks authorization to delete the file [
API 2014
]. No other exceptions are thrown, so the deletion can silently fail.
#FFCCCC
File file = new File(args[0]);
file.delete(); | File file = new File("file");
if (!file.delete()) {
// Deletion failed, handle error
}
Path file = new File(args[0]).toPath();
try {
Files.delete(file);
} catch (IOException x) {
// Deletion failed, handle error
}
## Compliant Solution
## This compliant solution checks the return value ofdelete():
#ccccFF
File file = new File("file");
if (!file.delete()) {
// Deletion failed, handle error
}
## Compliant Solution
## This compliant solution uses thejava.nio.file.Files.delete()method from Java SE 7 to delete the file:
#ccccFF
Path file = new File(args[0]).toPath();
try {
Files.delete(file);
} catch (IOException x) {
// Deletion failed, handle error
}
The Java SE 7 Documentation [
J2SE 2011
] defines
Files.delete()
to throw the following exceptions:
Exception
Reason
NoSuchFileException
File does not exist
DirectoryNotEmptyException
File is a directory and could not otherwise be deleted because the directory is not empty
IOException
An I/O error occurs
SecurityException
In the case of the default provider and a security manager is installed, the
SecurityManager.checkDelete(String)
method is invoked to check delete access to the file
Because
SecurityException
is a runtime exception, it need not be declared. Because
NoSuchFileException
and
DirectoryNotExmptyException
both inherit from
IOException
, they will be caught by the compliant solution's
catch
clause. | ## Risk Assessment
Failure to check the return values of methods that perform file I/O can result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO02-J
Medium
Probable
Yes
Yes
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,821 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487821 | 2 | 13 | FIO03-J | Remove temporary files before termination | Temporary files can be used to
Share data between processes.
Store auxiliary program data (for example, to preserve memory).
Construct and/or load classes, JAR files, and native libraries dynamically.
Temporary files are
files
and consequently must conform to the requirements specified by other rules governing operations on files, including
and
. Temporary files have the additional requirement that they must be removed before program termination.
Removing temporary files when they are no longer required allows file names and other resources (such as secondary storage) to be recycled. Each program is responsible for ensuring that temporary files are removed during normal operation. There is no surefire method that can guarantee the removal of orphaned files in the case of abnormal termination, even in the presence of a
finally
block, because the
finally
block may fail to execute. For this reason, many systems employ temporary file cleaner utilities to sweep temporary directories and remove old files. Such utilities can be invoked manually by a system administrator or can be periodically invoked by a system process. However, these utilities are themselves frequently vulnerable to file-based
exploits
. | class TempFile {
public static void main(String[] args) throws IOException{
File f = new File("tempnam.tmp");
if (f.exists()) {
System.out.println("This file already exists");
return;
}
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
String str = "Data";
fop.write(str.getBytes());
} finally {
if (fop != null) {
try {
fop.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
class TempFile {
public static void main(String[] args) throws IOException{
File f = File.createTempFile("tempnam",".tmp");
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
String str = "Data";
fop.write(str.getBytes());
fop.flush();
} finally {
// Stream/file still open; file will
// not be deleted on Windows systems
f.deleteOnExit(); // Delete the file when the JVM terminates
if (fop != null) {
try {
fop.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
## Noncompliant Code Example
This and subsequent code examples assume that files are created in a secure directory in compliance with
and are created with proper access permissions in compliance with
. Both requirements may be managed outside the Java Virtual Machine (JVM).
## This noncompliant code example fails to remove the file upon completion:
#FFcccc
class TempFile {
public static void main(String[] args) throws IOException{
File f = new File("tempnam.tmp");
if (f.exists()) {
System.out.println("This file already exists");
return;
}
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
String str = "Data";
fop.write(str.getBytes());
} finally {
if (fop != null) {
try {
fop.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
## Noncompliant Code Example (createTempFile(),deleteOnExit())
This noncompliant code example invokes the
File.createTempFile()
method, which generates a unique temporary file name based on two parameters: a prefix and an extension. This is the only method from Java 6 and earlier that is designed to produce unique file names, although the names produced can be easily predicted. A random number generator can be used to produce the prefix if a random file name is required.
This example also uses the
deleteOnExit()
method to ensure that the temporary file is deleted when the JVM terminates. However, according to the Java API [
API 2014
]
Class
File
, method
deleteOnExit()
documentation,
Deletion will be attempted only for normal termination of the virtual machine, as defined by the
Java Language Specification
. Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably.
Consequently, the file is not deleted if the JVM terminates unexpectedly. A longstanding bug on Windows-based systems, reported as
Bug ID: 4171239
[
SDN 2008
], causes JVMs to fail to delete a file when
deleteOnExit()
is invoked before the associated stream or
RandomAccessFile
is closed.
#FFcccc
class TempFile {
public static void main(String[] args) throws IOException{
File f = File.createTempFile("tempnam",".tmp");
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
String str = "Data";
fop.write(str.getBytes());
fop.flush();
} finally {
// Stream/file still open; file will
// not be deleted on Windows systems
f.deleteOnExit(); // Delete the file when the JVM terminates
if (fop != null) {
try {
fop.close();
} catch (IOException x) {
// Handle error
}
}
}
}
} | class TempFile {
public static void main(String[] args) {
Path tempFile = null;
try {
tempFile = Files.createTempFile("tempnam", ".tmp");
try (BufferedWriter writer =
Files.newBufferedWriter(tempFile, Charset.forName("UTF8"),
StandardOpenOption.DELETE_ON_CLOSE)) {
// Write to file
}
System.out.println("Temporary file write done, file erased");
} catch (FileAlreadyExistsException x) {
System.err.println("File exists: " + tempFile);
} catch (IOException x) {
// Some other sort of failure, such as permissions.
System.err.println("Error creating temporary file: " + x);
}
}
}
## Compliant Solution (DELETE_ON_CLOSE)
This compliant solution creates a temporary file using several methods from Java's
NIO.2
package (introduced in Java SE 7). It uses the
createTempFile()
method, which creates an unpredictable name. (The actual method by which the name is created is implementation-defined and undocumented.) The file is opened using the
try
-with-resources
construct, which automatically closes the file regardless of whether an exception occurs. Finally, the file is opened with the
DELETE_ON_CLOSE
option, which removes the file automatically when it is closed.
#ccccff
class TempFile {
public static void main(String[] args) {
Path tempFile = null;
try {
tempFile = Files.createTempFile("tempnam", ".tmp");
try (BufferedWriter writer =
Files.newBufferedWriter(tempFile, Charset.forName("UTF8"),
StandardOpenOption.DELETE_ON_CLOSE)) {
// Write to file
}
System.out.println("Temporary file write done, file erased");
} catch (FileAlreadyExistsException x) {
System.err.println("File exists: " + tempFile);
} catch (IOException x) {
// Some other sort of failure, such as permissions.
System.err.println("Error creating temporary file: " + x);
}
}
}
## Compliant Solution
When a secure directory for storing temporary files is not available, the
vulnerabilities
that result from using temporary files in insecure directories can be avoided by using alternative mechanisms, including
Other IPC mechanisms such as sockets and remote procedure calls.
The low-level Java Native Interface (JNI).
Memory-mapped files.
Threads to share heap data within the same JVM (applies to data sharing between Java processes only). | ## Risk Assessment
Failure to remove temporary files before termination can result in information leakage and resource exhaustion.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO03-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,870 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487870 | 2 | 13 | FIO04-J | Release resources when they are no longer needed | The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the garbage collector cannot free nonmemory resources such as open file descriptors and database connections. Consequently, failing to release such resources can lead to resource exhaustion attacks. In addition, programs can experience resource
starvation
while waiting for a finalizer to release resources such as
Lock
or
Semaphore
objects. This can occur because Java lacks any temporal guarantee of
when
finalizers execute other than "sometime before program termination." Finally, output streams may cache object references; such cached objects are not garbage-collected until after the output stream is closed. Consequently, output streams should be closed promptly after use.
A program may leak resources when it relies on finalizers to release system resources or when there is confusion over which part of the program is responsible for releasing system resources. In a busy system, the delay before the finalizer is called for an object provides a window of
vulnerability
during which an attacker could induce a
denial-of-service (DoS) attack
. Consequently, resources other than raw memory must be explicitly freed in nonfinalizer methods because of the unsuitability of using finalizers. See
for additional reasons to avoid the use of finalizers.
Note that on Windows systems, attempts to delete open files fail silently (see
for more information). | public int processFile(String fileName)
throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
public void getResults(String sqlQuery) {
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
processResults(rs);
stmt.close(); conn.close();
} catch (SQLException e) { /* Forward to handler */ }
}
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch(SQLException e) {
// Forward to handler
} finally {
rs.close();
stmt.close(); conn.close();
}
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch (SQLException e) {
// Forward to handler
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
} if (conn !=null) {
conn.close();
}
}
## Noncompliant Code Example (File Handle)
## This noncompliant code example opens a file and uses it but fails to explicitly close the file:
#FFcccc
public int processFile(String fileName)
throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
## Noncompliant Code Example (SQL Connection)
The problem of resource pool exhaustion is exacerbated in the case of database connections. Many database servers allow only a fixed number of connections, depending on configuration and licensing. Consequently, failure to release database connections can result in rapid exhaustion of available connections. This noncompliant code example fails to close the connection when an error occurs during execution of the SQL statement or during processing of the results:
#FFcccc
public void getResults(String sqlQuery) {
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
processResults(rs);
stmt.close(); conn.close();
} catch (SQLException e) { /* Forward to handler */ }
}
## Noncompliant Code Example
This noncompliant code example attempts to address exhaustion of database connections by adding cleanup code in a
finally
block. However,
rs
,
stmt
, or
conn
could be
null
, causing the code in the
finally
block to throw a
NullPointerException
.
#FFcccc
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch(SQLException e) {
// Forward to handler
} finally {
rs.close();
stmt.close(); conn.close();
}
## Noncompliant Code Example
In this noncompliant code example, the call to
rs.close()
or the call to
stmt.close()
might throw a
SQLException
. Consequently,
conn.close()
is never called, which violates
.
#FFcccc
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch (SQLException e) {
// Forward to handler
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
} if (conn !=null) {
conn.close();
}
} | try {
final FileInputStream stream = new FileInputStream(fileName);
try {
final BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Forward to handler
}
}
}
} catch (IOException e) {
// Forward to handler
}
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// Forward to handler
}
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (rs != null) {rs.close();}
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (stmt != null) {stmt.close();}
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (conn != null) {conn.close();}
} catch (SQLException e) {
// Forward to handler
}
}
}
}
try (Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery)) {
processResults(rs);
} catch (SQLException e) {
// Forward to handler
}
## Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing
bufRead
might result in an exception, the
FileInputStream
object is closed as required.
#ccccff
try {
final FileInputStream stream = new FileInputStream(fileName);
try {
final BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Forward to handler
}
}
}
} catch (IOException e) {
// Forward to handler
}
## Compliant Solution (try-with-resources)
This compliant solution uses the
try
-with-resources statement, introduced in Java SE 7, to release all acquired resources regardless of any exceptions that might occur:
#ccccff
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// Forward to handler
}
The
try
-with-resources construct sends any
IOException
to the
catch
clause, where it is forwarded to an exception handler. Exceptions generated during the allocation of resources (that is, the creation of the
FileInputStream
or
BufferedReader
), as well as any
IOException
thrown during execution of the
while
loop and any
IOException
generated by closing
bufRead
or
stream
, are included.
## Compliant Solution
## This compliant solution ensures that resources are released as required:
#ccccff
Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlQuery);
processResults(rs);
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (rs != null) {rs.close();}
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (stmt != null) {stmt.close();}
} catch (SQLException e) {
// Forward to handler
} finally {
try {
if (conn != null) {conn.close();}
} catch (SQLException e) {
// Forward to handler
}
}
}
}
## Compliant Solution (try-with-resources)
This compliant solution uses the
try
-with-resources construct, introduced in Java SE 7, to ensure that resources are released as required:
#ccccff
try (Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery)) {
processResults(rs);
} catch (SQLException e) {
// Forward to handler
}
The
try
-with-resources construct sends any
SQLException
to the
catch
clause, where it is forwarded to an exception handler. Exceptions generated during the allocation of resources (that is, the creation of the
Connection
,
Statement
, or
ResultSet
), as well as any
SQLException
thrown by
processResults()
and any
SQLException
generated by closing
rs
,
stmt
, or
conn
are included.
## The compliant solution (try-with-resources) is not yet supported at API level 18 (Android 4.3). | ## Risk Assessment
Failure to explicitly release nonmemory system resources when they are no longer needed can result in resource exhaustion.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO04-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,782 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487782 | 2 | 13 | FIO05-J | Do not expose buffers or their backing arrays methods to untrusted code | Buffer classes defined in the
java.nio
package, such as
IntBuffer
,
CharBuffer
, and
ByteBuffer
, define a variety of methods that wrap an array (or a portion of the array) of the corresponding primitive data type into a buffer and return the buffer as a
Buffer
object. Although these methods create a new
Buffer
object, the new
Buffer
is backed by the given input array. According to the Java API for these methods [
API 2014
],
The new buffer will be backed by the given character array; that is, modifications to the buffer will cause the array to be modified and vice versa.
Exposing these buffers to untrusted code exposes the backing array of the original buffer to malicious modification. Likewise, the
duplicate()
,
array()
,
slice()
, and
subsequence()
methods create additional buffers that are backed by the original buffer's backing array; exposing such additional buffers to untrusted code affords the same opportunity for malicious modification.
This rule is an instance of
. | final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray);
}
}
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// Initialize
}
public CharBuffer getBufferCopy() {
return cb.duplicate();
}
}
## Noncompliant Code Example (wrap())
This noncompliant code example declares a
char
array, wraps it within a
CharBuffer
, and exposes that
CharBuffer
to
untrusted code
via the
getBufferCopy()
method:
#FFCCCC
final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray);
}
}
## Noncompliant Code Example (duplicate())
This noncompliant code example invokes the
duplicate()
method to create and return a copy of the
CharBuffer
. As stated in the contract for the
duplicate()
method, the returned buffer is backed by the same array as is the original buffer. Consequently, if a caller were to modify the elements of the backing array, these modifications would also affect the original buffer.
#FFCCCC
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// Initialize
}
public CharBuffer getBufferCopy() {
return cb.duplicate();
}
} | final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray).asReadOnlyBuffer();
}
}
final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
CharBuffer cb = CharBuffer.allocate(dataArray.length);
cb.put(dataArray);
return cb;
}
}
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// Initialize
}
public CharBuffer getBufferCopy() {
return cb.asReadOnlyBuffer();
}
}
## Compliant Solution (asReadOnlyBuffer())
This compliant solution returns a read-only view of the
char
array in the form of a read-only
CharBuffer
. The standard library implementation of
CharBuffer
guarantees that attempts to modify the elements of a read-only
CharBuffer
will result in a
java.nio.ReadOnlyBufferException
.
#ccccff
final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray).asReadOnlyBuffer();
}
}
## Compliant Solution (Copy)
This compliant solution allocates a new
CharBuffer
and explicitly copies the contents of the
char
array into it before returning the copy. Consequently, malicious callers can modify the copy of the array but cannot modify the original.
#ccccff
final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
CharBuffer cb = CharBuffer.allocate(dataArray.length);
cb.put(dataArray);
return cb;
}
}
## Compliant Solution (asReadOnlyBuffer())
## This compliant solution exposes a read-only view of theCharBuffertountrusted code:
#ccccff
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// Initialize
}
public CharBuffer getBufferCopy() {
return cb.asReadOnlyBuffer();
}
} | ## Risk Assessment
Exposing buffers created using the
wrap()
,
duplicate()
,
array()
,
slice()
, or
subsequence()
methods may allow an untrusted caller to alter the contents of the original data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO05-J
Medium
Likely
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,774 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487774 | 2 | 13 | FIO06-J | Do not create multiple buffered wrappers on a single byte or character stream | Java input classes such as
Scanner
and
BufferedInputStream
facilitate fast, nonblocking I/O by buffering an underlying input stream. Programs can create multiple wrappers on an
InputStream
. Programs that use multiple wrappers around a single input stream, however, can behave unpredictably depending on whether the wrappers allow look-ahead. An attacker can
exploit
this difference in behavior, for example, by redirecting
System.in
(from a file) or by using the
System.setIn()
method to redirect
System.in
. In general, any input stream that supports nonblocking buffered I/O is susceptible to this form of misuse.
An input stream must not have more than one buffered wrapper. Instead, create and use only one wrapper per input stream, either by passing it as an argument to the methods that need it or by declaring it as a class variable.
Likewise, an output stream must not have more than one buffered wrapper because multiple wrappers can cause multiple output strings to be output in an unexpected order. For example, the
javax.servlet.ServletResponse
allows for the creation of a
PrintWriter
or an
OutputStream
to hold the response generated by a web servlet. But only one or the other should be used, not both. | public final class InputLibrary {
public static char getChar() throws EOFException, IOException {
BufferedInputStream in = new BufferedInputStream(System.in); // Wrapper
int input = in.read();
if (input == -1) {
throw new EOFException();
}
// Down casting is permitted because InputStream guarantees read() in range
// 0..255 if it is not -1
return (char) input;
}
public static void main(String[] args) {
try {
// Either redirect input from the console or use
// System.setIn(new FileInputStream("input.dat"));
System.out.print("Enter first initial: ");
char first = getChar();
System.out.println("Your first initial is " + first);
System.out.print("Enter last initial: ");
char last = getChar();
System.out.println("Your last initial is " + last);
} catch (EOFException e) {
System.err.println("ERROR");
// Forward to handler
} catch (IOException e) {
System.err.println("ERROR");
// Forward to handler
}
}
}
## Noncompliant Code Example
This noncompliant code example creates multiple
BufferedInputStream
wrappers on
System.in
, even though there is only one declaration of a
BufferedInputStream
. The
getChar()
method creates a new
BufferedInputStream
each time it is called. Data that is read from the underlying stream and placed in the buffer during execution of one call cannot be replaced in the underlying stream so that a second call has access to it. Consequently, data that remains in the buffer at the end of a particular execution of
getChar()
is lost. Although this noncompliant code example uses a
BufferedInputStream
, any buffered wrapper is unsafe; this condition is also exploitable when using a
Scanner
, for example.
#FFCCCC
public final class InputLibrary {
public static char getChar() throws EOFException, IOException {
BufferedInputStream in = new BufferedInputStream(System.in); // Wrapper
int input = in.read();
if (input == -1) {
throw new EOFException();
}
// Down casting is permitted because InputStream guarantees read() in range
// 0..255 if it is not -1
return (char) input;
}
public static void main(String[] args) {
try {
// Either redirect input from the console or use
// System.setIn(new FileInputStream("input.dat"));
System.out.print("Enter first initial: ");
char first = getChar();
System.out.println("Your first initial is " + first);
System.out.print("Enter last initial: ");
char last = getChar();
System.out.println("Your last initial is " + last);
} catch (EOFException e) {
System.err.println("ERROR");
// Forward to handler
} catch (IOException e) {
System.err.println("ERROR");
// Forward to handler
}
}
}
Implementation Details (POSIX)
When compiled under Java 1.6.0 and run from the command line, this program successfully takes two characters as input and prints them out. However, when run with a file redirected to standard input, the program throws
EOFException
because the second call to
getChar()
finds no characters to read upon encountering the end of the stream.
It may appear that the
mark()
and
reset()
methods of
BufferedInputStream
could be used to
replace
the read bytes. However, these methods provide look-ahead by operating on the internal buffers of the
BufferedInputStream
rather than by operating directly on the underlying stream. Because the example code creates a new
BufferedInputStream
on each call to
getchar()
, the internal buffers of the previous
BufferedInputStream
are lost. | public final class InputLibrary {
private static BufferedInputStream in =
new BufferedInputStream(System.in);
public static char getChar() throws EOFException, IOException {
int input = in.read();
if (input == -1) {
throw new EOFException();
}
in.skip(1); // This statement is to advance to the next line.
// The noncompliant code example deceptively
// appeared to work without it (in some cases).
return (char) input;
}
public static void main(String[] args) {
try {
System.out.print("Enter first initial: ");
char first = getChar();
System.out.println("Your first initial is " + first);
System.out.print("Enter last initial: ");
char last = getChar();
System.out.println("Your last initial is " + last);
} catch (EOFException e) {
System.err.println("ERROR");
// Forward to handler
} catch (IOException e) {
System.err.println("ERROR");
// Forward to handler
}
}
}
public final class InputLibrary {
private static BufferedInputStream in =
new BufferedInputStream(System.in);
static BufferedInputStream getBufferedWrapper() {
return in;
}
// ... Other methods
}
// Some code that requires user input from System.in
class AppCode {
private static BufferedInputStream in;
AppCode() {
in = InputLibrary.getBufferedWrapper();
}
// ... Other methods
}
## Compliant Solution (Class Variable)
Create and use only a single
BufferedInputStream
on
System.in
. This compliant solution ensures that all methods can access the
BufferedInputStream
by declaring it as a class variable:
#ccccff
public final class InputLibrary {
private static BufferedInputStream in =
new BufferedInputStream(System.in);
public static char getChar() throws EOFException, IOException {
int input = in.read();
if (input == -1) {
throw new EOFException();
}
in.skip(1); // This statement is to advance to the next line.
// The noncompliant code example deceptively
// appeared to work without it (in some cases).
return (char) input;
}
public static void main(String[] args) {
try {
System.out.print("Enter first initial: ");
char first = getChar();
System.out.println("Your first initial is " + first);
System.out.print("Enter last initial: ");
char last = getChar();
System.out.println("Your last initial is " + last);
} catch (EOFException e) {
System.err.println("ERROR");
// Forward to handler
} catch (IOException e) {
System.err.println("ERROR");
// Forward to handler
}
}
}
Implementation Details (POSIX)
When compiled under Java 1.6.0 and run from the command line, this program successfully takes two characters as input and prints them out. Unlike the noncompliant code example, this program also produces correct output when run with a file redirected to standard input.
## Compliant Solution (Accessible Class Variable)
This compliant solution uses both
System.in
and the
InputLibrary
class, which creates a buffered wrapper around
System.in
. Because the
InputLibrary
class and the remainder of the program must share a single buffered wrapper, the
InputLibrary
class must export a reference to that wrapper. Code outside the
InputLibrary
class must use the exported wrapper rather than create and use its own additional buffered wrapper around
System.in
.
#ccccff
public final class InputLibrary {
private static BufferedInputStream in =
new BufferedInputStream(System.in);
static BufferedInputStream getBufferedWrapper() {
return in;
}
// ... Other methods
}
// Some code that requires user input from System.in
class AppCode {
private static BufferedInputStream in;
AppCode() {
in = InputLibrary.getBufferedWrapper();
}
// ... Other methods
}
Note that reading from a stream is not a
thread-safe
operation by default; consequently, this compliant solution may be inappropriate in multithreaded environments. In such cases, explicit
synchronization
is required. | ## Risk Assessment
Creating multiple buffered wrappers around an
InputStream
can cause unexpected program behavior when the
InputStream
is redirected.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO06-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,722 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487722 | 2 | 13 | FIO07-J | Do not let external processes block on IO buffers | The
exec()
method of the
java.lang.Runtime
class and the related
ProcessBuilder.start()
method can be used to invoke external programs. While running, these programs are represented by a
java.lang.Process
object. This process contains an input stream, output stream, and error stream. Because the
Process
object allows a Java program to communicate with its external program, the process's input stream is an
OutputStream
object, accessible by the
Process.getOutputStream()
method. Likewise, the process's output stream and error streams are both represented by
InputStream
objects, accessible by the
Process.getInputStream()
and
Process.getErrorStream()
methods.
These processes may require input to be sent to their input stream, and they may also produce output on their output stream, their error stream, or both. Incorrect handling of such external programs can cause unexpected exceptions,
denial of service
(DoS), and other security problems.
A process that tries to read input on an empty input stream will block until input is supplied. Consequently, input must be supplied when invoking such a process.
Output from an external process can exhaust the available buffer reserved for its output or error stream. When this occurs, the Java program can block the external process as well, preventing any forward progress for both the Java program and the external process. Note that many platforms limit the buffer size available for output streams. Consequently, when invoking an external process, if the process sends any data to its output stream, the output stream must be emptied. Similarly, if the process sends any data to its error stream, the error stream must also be emptied. | public class Exec {
public static void main(String args[]) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
int exitVal = proc.exitValue();
}
}
public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
int exitVal = proc.waitFor();
}
}
public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
InputStream is = proc.getInputStream();
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
}
int exitVal = proc.waitFor();
}
}
## Noncompliant Code Example (exitValue())
This noncompliant code example invokes a hypothetical cross-platform notepad application using the external command
notemaker
. The
notemaker
application does not read its input stream but sends output to both its output stream and error stream.
This noncompliant code example invokes
notemaker
using the
exec()
method, which returns a
Process
object. The
exitValue()
method returns the exit value for processes that have terminated, but it throws an
IllegalThreadStateException
when invoked on an active process. Because this noncompliant example program fails to wait for the
notemaker
process to terminate, the call to
exitValue()
is likely to throw an
IllegalThreadStateException
.
#FFcccc
public class Exec {
public static void main(String args[]) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
int exitVal = proc.exitValue();
}
}
## Noncompliant Code Example (waitFor())
In this noncompliant code example, the
waitFor()
method blocks the calling thread until the
notemaker
process terminates. This approach prevents the
IllegalThreadStateException
from the previous example. However, the example program may experience an arbitrary delay before termination. Output from the
notemaker
process can exhaust the available buffer for the output or error stream because neither stream is read while waiting for the process to complete. If either buffer becomes full, it can block the
notemaker
process as well, preventing all progress for both the
notemaker
process and the Java program.
#FFcccc
public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
int exitVal = proc.waitFor();
}
}
## Noncompliant Code Example (Process Output Stream)
This noncompliant code example properly empties the process's output stream, thereby preventing the output stream buffer from becoming full and blocking. However, it ignores the process's error stream, which can also fill and cause the process to block.
#ffcccc
public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
InputStream is = proc.getInputStream();
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
}
int exitVal = proc.waitFor();
}
} | public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("notemaker");
pb = pb.redirectErrorStream(true);
Process proc = pb.start();
InputStream is = proc.getInputStream();
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
}
int exitVal = proc.waitFor();
}
}
class StreamGobbler implements Runnable {
private final InputStream is;
private final PrintStream os;
StreamGobbler(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
os.print((char) c);
} catch (IOException x) {
// Handle error
}
}
}
public class Exec {
public static void main(String[] args)
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
// Any error message?
Thread errorGobbler
= new Thread(new StreamGobbler(proc.getErrorStream(), System.err));
// Any output?
Thread outputGobbler
= new Thread(new StreamGobbler(proc.getInputStream(), System.out));
errorGobbler.start();
outputGobbler.start();
// Any error?
int exitVal = proc.waitFor();
errorGobbler.join(); // Handle condition where the
outputGobbler.join(); // process ends before the threads finish
}
}
## Compliant Solution (redirectErrorStream())
This compliant solution redirects the process's error stream to its output stream. Consequently, the program can empty the single output stream without fear of blockage.
#ccccff
public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("notemaker");
pb = pb.redirectErrorStream(true);
Process proc = pb.start();
InputStream is = proc.getInputStream();
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
}
int exitVal = proc.waitFor();
}
}
## Compliant Solution (Process Output Stream and Error Stream)
This compliant solution spawns two threads to consume the process's output stream and error stream. Consequently, the process cannot block indefinitely on those streams.
When the output and error streams are handled separately, they must be emptied independently. Failure to do so can cause the program to block indefinitely.
#ccccff
class StreamGobbler implements Runnable {
private final InputStream is;
private final PrintStream os;
StreamGobbler(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
os.print((char) c);
} catch (IOException x) {
// Handle error
}
}
}
public class Exec {
public static void main(String[] args)
throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
// Any error message?
Thread errorGobbler
= new Thread(new StreamGobbler(proc.getErrorStream(), System.err));
// Any output?
Thread outputGobbler
= new Thread(new StreamGobbler(proc.getInputStream(), System.out));
errorGobbler.start();
outputGobbler.start();
// Any error?
int exitVal = proc.waitFor();
errorGobbler.join(); // Handle condition where the
outputGobbler.join(); // process ends before the threads finish
}
} | ## Risk Assessment
Failure to properly manage the I/O streams of external processes can result in runtime exceptions and in
DoS
vulnerabilities.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO07-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,889 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487889 | 2 | 13 | FIO08-J | Distinguish between characters or bytes read from a stream and -1 | The abstract
InputStream.read()
and
Reader.read()
methods are used to read a byte or character, respectively, from a stream. The
InputStream.read()
method reads a single byte from an input source and returns its value as an
int
in the range 0 to 255 (
0x00
-
0xff
). The
Reader.read()
method reads a single character and returns its value as an
int
in the range 0 to 65,535 (
0x0000
-
0xffff
). Both methods return the 32-bit value
-1
(
0xffffffff
) to indicate that the end of the stream has been reached and no data is available. The larger
int
size is used by both methods to differentiate between the end-of-stream indicator and the maximum byte (
0xff
) or character (
0xffff
) value. The end-of-stream indicator is an example of an in-band error indicator. In-band error indicators are problematic to work with, and the creation of new in-band-error indicators is discouraged.
Prematurely converting the resulting
int
to a
byte
or
char
before testing for the value −1 makes it impossible to distinguish between characters read and the end of stream indicator. Programs must check for the end of stream before narrowing the return value to a
byte
or
char
.
This rule applies to any method that returns the value −1 to indicate the end of a stream. It includes any
InputStream
or
Reader
subclass that provides an implementation of the
read()
method. This rule is a specific instance of
. | FileInputStream in;
// Initialize stream
byte data;
while ((data = (byte) in.read()) != -1) {
// ...
}
FileReader in;
// Initialize stream
char data;
while ((data = (char) in.read()) != -1) {
// ...
}
## Noncompliant Code Example (byte)
FileInputStream
is a subclass of
InputStream
. It will return −1 only when the end of the input stream has been reached. This noncompliant code example casts the value returned by the
read()
method directly to a value of type
byte
and then compares this value with −1 in an attempt to detect the end of the stream.
#FFcccc
FileInputStream in;
// Initialize stream
byte data;
while ((data = (byte) in.read()) != -1) {
// ...
}
If the
read()
method encounters a
0xFF
byte in the file, this value becomes indistinguishable from the −1 value used to indicate the end of stream, because the byte value is promoted and sign-extended to an
int
before being compared with −1. Consequently, the loop will halt prematurely if a
0xFF
byte is read.
## Noncompliant Code Example (char)
FileReader
is a subclass of
InputStreamReader
, which is in turn a subclass of
Reader
. It also returns −1 only when the end of the stream is reached. This noncompliant code example casts the value of type
int
returned by the
read()
method directly to a value of type
char
, which is then compared with −1 in an attempt to detect the end of stream. This conversion leaves the value of
data
as
0xFFFF
(e.g.,
Character.MAX_VALUE
) instead of −1. Consequently, the test for the end of file never evaluates to true.
#FFcccc
FileReader in;
// Initialize stream
char data;
while ((data = (char) in.read()) != -1) {
// ...
} | FileInputStream in;
// Initialize stream
int inbuff;
byte data;
while ((inbuff = in.read()) != -1) {
data = (byte) inbuff;
// ...
}
FileReader in;
// Initialize stream
int inbuff;
char data;
while ((inbuff = in.read()) != -1) {
data = (char) inbuff;
// ...
}
## Compliant Solution (byte)
Use a variable of type
int
to capture the return value of the
byte
input method. When the value returned by
read()
is not −1, it can be safely cast to type
byte
. When
read()
returns
0x000000FF
, the comparison will test against
0xFFFFFFFF
, which evaluates to false.
#ccccff
FileInputStream in;
// Initialize stream
int inbuff;
byte data;
while ((inbuff = in.read()) != -1) {
data = (byte) inbuff;
// ...
}
## Compliant Solution (char)
Use a variable of type
int
to capture the return value of the character input method. When the value returned by
read()
is not −1, it can be safely cast to type
char
.
#ccccff
FileReader in;
// Initialize stream
int inbuff;
char data;
while ((inbuff = in.read()) != -1) {
data = (char) inbuff;
// ...
} | ## Risk Assessment
Historically, using a narrow type to capture the return value of a byte input method has resulted in significant
vulnerabilities
, including command injection attacks; see
CA-1996-22 advisory
. Consequently, the severity of this error is high.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO08-J
High
Probable
Yes
Yes
P18
L1
Automated Detection
Some static analysis tools can detect violations of this rule.
Tool
Version
Checker
Description
Parasoft Jtest
CERT.FIO08.CRRV
Check the return value of methods which read or skip input
EOS_BAD_END_OF_STREAM_CHECK
Implemented (since 4.4.0) | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,720 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487720 | 2 | 13 | FIO09-J | Do not rely on the write() method to output integers outside the range 0 to 255 | The
write()
method, defined in the class
java.io.OutputStream
, takes an argument of type
int
the value of which must be in the range 0 to 255. Because a value of type
int
could be outside this range, failure to range check can result in the truncation of the higher-order bits of the argument.
The general contract for the
write()
method says that it writes one byte to the output stream. The byte to be written constitutes the eight lower-order bits of the argument
b
, passed to the
write()
method; the 24 high-order bits of
b
are ignored (see
java.io.OutputStream.write()
[
API 2014
] for more information). | class ConsoleWrite {
public static void main(String[] args) {
// Any input value > 255 will result in unexpected output
System.out.write(Integer.valueOf(args[0]));
System.out.flush();
}
}
## Noncompliant Code Example
This noncompliant code example accepts a value from the user without validating it. Any value that is not in the range of 0 to 255 is truncated. For instance,
write(303)
prints
/
on ASCII-based systems because the lower-order 8 bits of 303 are used while the 24 high-order bits are ignored (303 % 256 = 47, which is the ASCII code for
/
). That is, the result is the remainder of the input divided by 256.
#FFcccc
class ConsoleWrite {
public static void main(String[] args) {
// Any input value > 255 will result in unexpected output
System.out.write(Integer.valueOf(args[0]));
System.out.flush();
}
} | class FileWrite {
public static void main(String[] args)
throws NumberFormatException, IOException {
// Perform range checking
int value = Integer.valueOf(args[0]);
if (value < 0 || value > 255) {
throw new ArithmeticException("Value is out of range");
}
System.out.write(value);
System.out.flush();
}
}
class FileWrite {
public static void main(String[] args)
throws NumberFormatException, IOException {
DataOutputStream dos = new DataOutputStream(System.out);
dos.writeInt(Integer.valueOf(args[0].toString()));
System.out.flush();
}
}
## Compliant Solution (Range-Check Inputs)
This compliant solution prints the corresponding character only if the input integer is in the proper range. If the input is outside the representable range of an
int
, the
Integer.valueOf()
method throws a
NumberFormatException
. If the input can be represented by an
int
but is outside the range required by
write()
, this code throws an
ArithmeticException
.
#ccccff
class FileWrite {
public static void main(String[] args)
throws NumberFormatException, IOException {
// Perform range checking
int value = Integer.valueOf(args[0]);
if (value < 0 || value > 255) {
throw new ArithmeticException("Value is out of range");
}
System.out.write(value);
System.out.flush();
}
}
## Compliant Solution (writeInt())
This compliant solution uses the
writeInt()
method of the
DataOutputStream
class, which can output the entire range of values representable as an
int
:
#ccccff
class FileWrite {
public static void main(String[] args)
throws NumberFormatException, IOException {
DataOutputStream dos = new DataOutputStream(System.out);
dos.writeInt(Integer.valueOf(args[0].toString()));
System.out.flush();
}
} | ## Risk Assessment
Using the
write()
method to output integers outside the range 0 to 255 will result in truncation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO09-J
Low
Unlikely
No
Yes
P2
L3
Automated Detection
Automated detection of all uses of the
write()
method is straightforward. Sound determination of whether the truncating behavior is correct is not feasible in the general case. Heuristic checks could be useful.
Tool
Version
Checker
Description
7.5
CHECKED_RETURN
Implemented
Parasoft Jtest
CERT.FIO09.ARGWRITE
Do not rely on the write() method to output integers outside the range 0 to 255 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,767 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487767 | 2 | 13 | FIO10-J | Ensure the array is filled when using read() to fill an array | The contracts of the read methods for
InputStream
and
Reader
classes and their subclasses are complicated with regard to filling byte or character arrays. According to the Java API [
API 2014
] for the class
InputStream
, the
read(byte[] b)
method and the
read(byte[] b, int off, int len)
method provide the following behavior:
The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.
According to the Java API for the
read(byte[] b
, int off, int len
)
method:
An attempt is made to read as many as
len
bytes, but a smaller number may be read, possibly zero.
Both
read
methods return as soon as they find available input data. As a result, these methods can stop reading data before the array is filled because the available data may be insufficient to fill the array.
The documentation for the analogous
read
methods in
Reader
return the number of characters read, which implies that they also need not fill the
char
array provided as an argument.
Ignoring the result returned by the
read()
methods is a violation of
. Security issues can arise even when return values are considered because the default behavior of the
read()
methods lacks any guarantee that the entire buffer array is filled. Consequently, when using
read()
to fill an array, the program must check the return value of
read()
and must handle the case where the array is only partially filled. In such cases, the program may try to fill the rest of the array, or work only with the subset of the array that was filled, or throw an exception.
This rule applies only to
read()
methods that take an array argument. To read a single byte, use the
InputStream.read()
method that takes no arguments and returns an
int
. To read a single character, use a
Reader.read()
method that takes no arguments and returns the character read as an
int
. | public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
if (in.read(data) == -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
int offset = 0;
if (in.read(data, offset, data.length - offset)) != -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
## Noncompliant Code Example (1-argumentread())
This noncompliant code example attempts to read 1024 bytes encoded in UTF-8 from an
InputStream
and return them as a
String
. It explicitly specifies the character encoding used to build the string, in compliance with
.
#FFcccc
public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
if (in.read(data) == -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
The programmer's misunderstanding of the general contract of the
read()
method can result in failure to read the intended data in full. It is possible that less than 1024 bytes exist in the stream, perhaps because the stream originates from a file with less than 1024 bytes. It is also possible that the stream contains 1024 bytes but less than 1024 bytes are immediately available, perhaps because the stream originates from a TCP socket that sent more bytes in a subsequent packet that has not arrived yet. In either case,
read()
will return less than 1024 bytes. It indicates this through its return value, but the program ignores the return value and uses the entire array to construct a string, even though any unread bytes will fill the string with null characters.
## Noncompliant Code Example (3-argumentread())
This noncompliant code example uses the 3-argument version of
read()
to read 1024 bytes encoded in UTF-8 from an
InputStream
and return them as a
String
.
#FFcccc
public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
int offset = 0;
if (in.read(data, offset, data.length - offset)) != -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
However, this code suffers from the same flaws as the previous noncompliant code example. Again, the
read()
method can return less than 1024 bytes, either because 1024 bytes are simply not available, or the latter bytes have not arrived in the stream yet. In either case,
read()
returns less than 1024 bytes, the remaining bytes in the array remain with zero values, yet the entire array is used to construct the string. | public static String readBytes(InputStream in) throws IOException {
int offset = 0;
int bytesRead = 0;
byte[] data = new byte[1024];
while ((bytesRead = in.read(data, offset, data.length - offset))
!= -1) {
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
String str = new String(data, 0, offset, "UTF-8");
return str;
}
public static String readBytes(FileInputStream fis)
throws IOException {
byte[] data = new byte[1024];
DataInputStream dis = new DataInputStream(fis);
dis.readFully(data);
String str = new String(data, "UTF-8");
return str;
}
## Compliant Solution (Multiple Calls toread())
This compliant solution reads all the desired bytes into its buffer, accounting for the total number of bytes read and adjusting the remaining bytes' offset, consequently ensuring that the required data is read in full. It also avoids splitting multibyte encoded characters across buffers by deferring construction of the result string until the data has been fully read. (see
IDS10-J. Do not assume every character in a string is the same size
for more information).
#ccccff
public static String readBytes(InputStream in) throws IOException {
int offset = 0;
int bytesRead = 0;
byte[] data = new byte[1024];
while ((bytesRead = in.read(data, offset, data.length - offset))
!= -1) {
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
String str = new String(data, 0, offset, "UTF-8");
return str;
}
## Compliant Solution (readFully())
The no-argument and one-argument
readFully()
methods of the
DataInputStream
class guarantee that either all of the requested data is read or an exception is thrown. These methods throw
EOFException
if they detect the end of input before the required number of bytes have been read; they throw
IOException
if some other I/O error occurs.
#ccccff
public static String readBytes(FileInputStream fis)
throws IOException {
byte[] data = new byte[1024];
DataInputStream dis = new DataInputStream(fis);
dis.readFully(data);
String str = new String(data, "UTF-8");
return str;
} | ## Risk Assessment
Incorrect use of the
read()
method can result in the wrong number of bytes being read or character sequences being interpreted incorrectly.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO10-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,611 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487611 | 2 | 13 | FIO11-J | Do not convert between strings and bytes without specifying a valid character encoding | Deprecated
This rule has been moved to:
STR03-J. Do not convert between strings and bytes without specifying a valid character encoding
12/08/2014 -- Version 1.0 | null | null | null | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,759 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487759 | 2 | 13 | FIO12-J | Provide methods to read and write little-endian data | In Java, data is stored in
big-endian format
(also called network order). That is, all data is represented sequentially starting from the most significant bit to the least significant. JDK versions prior to JDK 1.4 required definition of custom methods that manage reversing byte order to maintain compatibility with little-endian systems. Correct handling of byte order–related issues is critical when exchanging data in a networked environment that includes both big-endian and little-endian machines or when working with other languages using Java Native Interface (JNI). Failure to handle byte-ordering issues can cause unexpected program behavior. | try {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("data"));
// Little-endian data might be read as big-endian
int serialNumber = dis.readInt();
} catch (IOException x) {
// Handle error
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// Handle error
}
}
}
}
## Noncompliant Code Example
The read methods (
readByte()
,
readShort()
,
readInt()
,
readLong()
,
readFloat()
, and
readDouble()
) and the corresponding write methods defined by class
java.io.DataInputStream
and class
java.io.DataOutputStream
operate only on big-endian data. Use of these methods while interoperating with traditional languages, such as C and C++, is insecure because such languages lack any guarantees about endianness. This noncompliant code example shows such a discrepancy:
#FFcccc
try {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("data"));
// Little-endian data might be read as big-endian
int serialNumber = dis.readInt();
} catch (IOException x) {
// Handle error
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// Handle error
}
}
}
} | try {
DataInputStream dis = null;
try {
dis = new DataInputStream( new FileInputStream("data"));
byte[] buffer = new byte[4];
int bytesRead = dis.read(buffer); // Bytes are read into buffer
if (bytesRead != 4) {
throw new IOException("Unexpected End of Stream");
}
int serialNumber =
ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException x) {
// Handle error
}
}
}
} catch (IOException x) {
// Handle error
}
// Read method
public static int readLittleEndianInteger(InputStream ips)
throws IOException {
byte[] buffer = new byte[4];
int check = ips.read(buffer);
if (check != 4) {
throw new IOException("Unexpected End of Stream");
}
int result = (buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8) | buffer[0];
return result;
}
// Write method
public static void writeLittleEndianInteger(int i, OutputStream ops)
throws IOException {
byte[] buffer = new byte[4];
buffer[0] = (byte) i;
buffer[1] = (byte) (i >> 8);
buffer[2] = (byte) (i >> 16);
buffer[3] = (byte) (i >> 24);
ops.write(buffer);
}
public static int reverse(int i) {
return Integer.reverseBytes(i);
}
## Compliant Solution (ByteBuffer)
This compliant solution uses methods provided by class
ByteBuffer
[
API 2014
] to correctly extract an
int
from the original input value. It wraps the input byte array with a
ByteBuffer
, sets the byte order to little-endian, and extracts the
int
. The result is stored in the integer
serialNumber
. Class
ByteBuffer
provides analogous get and put methods for other numeric types.
#ccccff
try {
DataInputStream dis = null;
try {
dis = new DataInputStream( new FileInputStream("data"));
byte[] buffer = new byte[4];
int bytesRead = dis.read(buffer); // Bytes are read into buffer
if (bytesRead != 4) {
throw new IOException("Unexpected End of Stream");
}
int serialNumber =
ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException x) {
// Handle error
}
}
}
} catch (IOException x) {
// Handle error
}
## Compliant Solution (Define Special-Purpose Methods)
An alternative compliant solution is to define read and write methods that support the necessary byte-swapping while reading from or writing to the file. In this example, the
readLittleEndianInteger()
method reads four bytes into a byte buffer and then pieces together the integer in the correct order. The
writeLittleEndianInteger()
method obtains bytes by repeatedly casting the integer so that the least significant byte is extracted on successive right shifts.
Long
values can be handled by defining a byte buffer of size 8.
#ccccff
// Read method
public static int readLittleEndianInteger(InputStream ips)
throws IOException {
byte[] buffer = new byte[4];
int check = ips.read(buffer);
if (check != 4) {
throw new IOException("Unexpected End of Stream");
}
int result = (buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8) | buffer[0];
return result;
}
// Write method
public static void writeLittleEndianInteger(int i, OutputStream ops)
throws IOException {
byte[] buffer = new byte[4];
buffer[0] = (byte) i;
buffer[1] = (byte) (i >> 8);
buffer[2] = (byte) (i >> 16);
buffer[3] = (byte) (i >> 24);
ops.write(buffer);
}
## Compliant Solution (reverseBytes())
When programming for JDK 1.5 and later, use the
reverseBytes()
method defined in the classes
Character
,
Short
,
Integer
, and
Long
to reverse the order of the integral value's bytes. Note that classes
Float
and
Double
lack such a method.
#ccccff
public static int reverse(int i) {
return Integer.reverseBytes(i);
} | ## Risk Assessment
Reading and writing data without considering endianness can lead to misinterpretations of both the magnitude and sign of the data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO12-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,885 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487885 | 2 | 13 | FIO13-J | Do not log sensitive information outside a trust boundary | Logging is essential for debugging, incident response, and collecting forensic evidence. Nevertheless, logging
sensitive data
raises many concerns, including the privacy of the stakeholders, limitations imposed by the law on the collection of personal information, and the potential for data exposure by insiders. Sensitive information includes, but is not limited to, IP addresses, user names and passwords, email addresses, credit card numbers, and any personally identifiable information such as social security numbers. Many countries prohibit or restrict collection of personal data; others permit retention of personal data only when held in an anonymized form. For example, leaking unencrypted credit card numbers into a log file could be a violation of PCI DSS (Payment Card Industry Data Security Standard) regulations [
PCI 2010
]. Consequently, logs must not contain sensitive data, particularly when prohibited by law.
Unfortunately, violations of this rule are common. For example, prior to version 0.8.1, the LineControl Java client logged sensitive information, including the local user's password, as documented by
CVE-2005-2990
.
The
java.util.logging
class provides a basic logging framework for JDK versions 1.4 and higher. Other logging frameworks exist, but the basic principles apply regardless of the particular logging framework chosen.
Programs typically support varying levels of protection. Some information, such as access times, can be safely logged. Some information can be logged, but the log file must be restricted from everyone but particular administrators. Other information, such as credit card numbers, can be included in logs only in encrypted form. Information such as passwords should not be logged at all.
For the following code examples, the log lies outside the trust boundary of the information being recorded. Also, normal log messages should include additional parameters such as date, time, source event, and so forth. This information has been omitted from the following code examples for brevity. | public void logRemoteIPAddress(String name) {
Logger logger = Logger.getLogger("com.organization.Log");
InetAddress machine = null;
try {
machine = InetAddress.getByName(name);
} catch (UnknownHostException e) {
Exception e = MyExceptionReporter.handle(e);
} catch (SecurityException e) {
Exception e = MyExceptionReporter.handle(e);
logger.severe(name + "," + machine.getHostAddress() + "," +
e.toString());
}
}
logger.info("Age: " + passengerAge);
## Noncompliant Code Example
In this noncompliant code example, a server logs the IP address of the remote client in the event of a security exception. This data can be misused, for example, to build a profile of a user's browsing habits. Such logging may violate legal restrictions in many countries.
When the log cannot contain IP addresses, it should not contain any information about a
SecurityException
, because it might leak an IP address. When an exception contains sensitive information, the custom
MyExceptionReporter
class should extract or cleanse it before returning control to the next statement in the
catch
block (see
).
#FFcccc
public void logRemoteIPAddress(String name) {
Logger logger = Logger.getLogger("com.organization.Log");
InetAddress machine = null;
try {
machine = InetAddress.getByName(name);
} catch (UnknownHostException e) {
Exception e = MyExceptionReporter.handle(e);
} catch (SecurityException e) {
Exception e = MyExceptionReporter.handle(e);
logger.severe(name + "," + machine.getHostAddress() + "," +
e.toString());
}
}
## Noncompliant Code Example
Log messages with sensitive information should not be printed to the console display for security reasons (a possible example of sensitive information is passenger age). The
java.util.logging.Logger
class supports different logging levels that can be used for classifying such information:
FINEST
,
FINER
,
FINE
,
CONFIG
,
INFO
,
WARNING
, and
SEVERE
. By default, the
INFO
,
WARNING
, and
SEVERE
levels print the message to the console, which is accessible by end users and system administrators.
If we assume that the passenger age can appear in log files on the current system but not on the console display, this code example is noncompliant.
#FFcccc
logger.info("Age: " + passengerAge); | // ...
catch (SecurityException e) {
Exception e = MyExceptionReporter.handle(e);
}
// Make sure that all handlers only print log messages rated INFO or higher
Handler handlers[] = logger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
handlers[i].setLevel(Level.INFO);
}
// ...
logger.finest("Age: " + passengerAge);
## Compliant Solution
This compliant solution does not log security exceptions except for the logging implicitly performed by
MyExceptionReporter
:
#ccccff
// ...
catch (SecurityException e) {
Exception e = MyExceptionReporter.handle(e);
}
## Compliant Solution
This compliant solution logs the passenger age at the
FINEST
level to prevent this information from displaying on the console. As noted previously, we are assuming the age may appear in system log files but not on the console.
#ccccff
// Make sure that all handlers only print log messages rated INFO or higher
Handler handlers[] = logger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
handlers[i].setLevel(Level.INFO);
}
// ...
logger.finest("Age: " + passengerAge); | ## Risk Assessment
Logging sensitive information can violate system
security policies
and can violate user privacy when the logging level is incorrect or when the log files are insecure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO13-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,524 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487524 | 2 | 13 | FIO14-J | Perform proper cleanup at program termination | When certain kinds of errors are detected, such as irrecoverable logic errors, rather than risk data corruption by continuing to execute in an indeterminate state, the appropriate strategy may be for the system to quickly shut down, allowing the operator to start it afresh in a determinate state.
Section 6.46, "Termination Strategy [REU]," [
ISO/IEC TR 24772:2010
] says:
When a fault is detected, there are many ways in which a system can react. The quickest and most noticeable way is to fail hard, also known as fail fast or fail stop. The reaction to a detected fault is to immediately halt the system. Alternatively, the reaction to a detected fault could be to fail soft. The system would keep working with the faults present, but the performance of the system would be degraded. Systems used in a high availability environment such as telephone switching centers, e-commerce, or other "always available" applications would likely use a fail soft approach. What is actually done in a fail soft approach can vary depending on whether the system is used for safety critical or security critical purposes. For fail-safe systems, such as flight controllers, traffic signals, or medical monitoring systems, there would be no effort to meet normal operational requirements, but rather to limit the damage or danger caused by the fault. A system that fails securely, such as cryptologic systems, would maintain maximum security when a fault is detected, possibly through a denial of service.
And:
The reaction to a fault in a system can depend on the criticality of the part in which the fault originates. When a program consists of several tasks, each task may be critical, or not. If a task is critical, it may or may not be restartable by the rest of the program. Ideally, a task that detects a fault within itself should be able to halt leaving its resources available for use by the rest of the program, halt clearing away its resources, or halt the entire program. The latency of task termination and whether tasks can ignore termination signals should be clearly specified. Having inconsistent reactions to a fault can potentially be a vulnerability.
Java provides two options for program termination:
Runtime.exit()
(which is equivalent to
System.exit()
) and
Runtime.halt()
.
## Runtime.exit()
Runtime.exit()
is the typical way of exiting a program. According to the Java API
[
API 2014
],
Runtime.exit()
:
terminates the currently running Java virtual machine by initiating its shutdown sequence. This method never returns normally. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is performed the virtual machine halts.
If this method is invoked after the virtual machine has begun its shutdown sequence, then if shutdown hooks are being run, this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled, then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely.
The
System.exit()
method is the conventional and convenient means of invoking this method.
The
Runtime.addShutdownHook()
method can be used to customize
Runtime.exit()
to perform additional actions at program termination. This method uses a
Thread
, which must be initialized but unstarted. The thread starts when the Java Virtual Machine (JVM) begins to shut down. Because the JVM usually has a fixed time to shut down, these threads should not be long-running and should not attempt user interaction.
## Runtime.halt()
Runtime.halt()
is similar to
Runtime.exit()
but does
not
run shutdown hooks or finalizers. According to the ava API [
API 2014
],
Runtime.halt()
forcibly terminates the currently running Java virtual machine. This method never returns normally.
This method should be used with extreme caution. Unlike the exit method, this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled. If the shutdown sequence has already been initiated, then this method does not wait for any running shutdown hooks or finalizers to finish their work.
Java programs do not flush unwritten buffered data or close open files when they exit, so programs must perform these operations manually. Programs must also perform any other cleanup that involves external resources, such as releasing shared locks. | public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
out.println("hello");
Runtime.getRuntime().exit(1);
}
}
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
out.close();
}
}));
out.println("hello");
Runtime.getRuntime().halt(1);
}
}
public class InterceptExit {
public static void main(String[] args)
throws FileNotFoundException {
InputStream in = null;
try {
in = new FileInputStream("file");
System.out.println("Regular code block");
// Abrupt exit such as ctrl + c key pressed
System.out.println("This never executes");
} finally {
if (in != null) {
try {
in.close(); // This never executes either
} catch (IOException x) {
// Handle error
}
}
}
}
}
## Noncompliant Code Example
This example creates a new file, outputs some text to it, and abruptly exits using
Runtime.exit()
. Consequently, the file may be closed without the text actually being written.
#ffcccc
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
out.println("hello");
Runtime.getRuntime().exit(1);
}
}
## Noncompliant Code Example (Runtime.halt())
This noncompliant code example calls
Runtime.halt()
instead of
Runtime.exit()
. The
Runtime.halt()
method stops the JVM without invoking any shutdown hooks; consequently, the file is not properly written to or closed.
#ffcccc
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
out.close();
}
}));
out.println("hello");
Runtime.getRuntime().halt(1);
}
}
## Noncompliant Code Example (Signal)
When a user forcefully exits a program, for example by pressing the Ctrl+C keys or by using the
kill
command, the JVM terminates abruptly. Although this event cannot be captured, the program should nevertheless perform any mandatory cleanup operations before exiting. This noncompliant code example fails to do so.
#FFcccc
public class InterceptExit {
public static void main(String[] args)
throws FileNotFoundException {
InputStream in = null;
try {
in = new FileInputStream("file");
System.out.println("Regular code block");
// Abrupt exit such as ctrl + c key pressed
System.out.println("This never executes");
} finally {
if (in != null) {
try {
in.close(); // This never executes either
} catch (IOException x) {
// Handle error
}
}
}
}
} | public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
try {
out.println("hello");
} finally {
try {
out.close();
} catch (IOException x) {
// Handle error
}
}
Runtime.getRuntime().exit(1);
}
}
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
out.close();
}
}));
out.println("hello");
Runtime.getRuntime().exit(1);
}
}
public class Hook {
public static void main(String[] args) {
try {
final InputStream in = new FileInputStream("file");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// Log shutdown and close all resources
in.close();
}
});
// ...
} catch (IOException x) {
// Handle error
} catch (FileNotFoundException x) {
// Handle error
}
}
}
## Compliant Solution (close())
This solution explicitly closes the file before exiting:
#ccccff
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
try {
out.println("hello");
} finally {
try {
out.close();
} catch (IOException x) {
// Handle error
}
}
Runtime.getRuntime().exit(1);
}
}
## Compliant Solution (Shutdown Hook)
This compliant solution adds a shutdown hook to close the file. This hook is invoked by
Runtime.exit()
and is called before the JVM is halted.
#ccccff
public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
out.close();
}
}));
out.println("hello");
Runtime.getRuntime().exit(1);
}
}
## Compliant Solution (addShutdownHook())
Use the
addShutdownHook()
method of
java.lang.Runtime
to assist with performing cleanup operations in the event of abrupt termination. The JVM starts the shutdown hook thread when abrupt termination is initiated; the shutdown hook runs concurrently with other JVM threads.
According to the Java API [
API 2014
], class
Runtime
, method
addShutdownHook()
,
A
shutdown hook
is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine....
Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously registered hook.
Some precautions must be taken because the JVM might be in a sensitive state during shutdown. Shutdown hook threads should
Be lightweight and simple.
Be thread-safe.
Hold locks when accessing data and release those locks when done.
Avoid relying on system services, because the services themselves may be shut down (for example, the logger may be shut down from another hook).
To avoid
race conditions
or
deadlock
between shutdown actions, it may be better to run a series of shutdown tasks from one thread by using a single shutdown hook [
Goetz 2006
].
## This compliant solution shows the standard method to install a hook:
#ccccff
public class Hook {
public static void main(String[] args) {
try {
final InputStream in = new FileInputStream("file");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// Log shutdown and close all resources
in.close();
}
});
// ...
} catch (IOException x) {
// Handle error
} catch (FileNotFoundException x) {
// Handle error
}
}
}
The JVM can abort for external reasons, such as an external
SIGKILL
signal (POSIX) or the
TerminateProcess()
call (Windows), or because of memory corruption caused by native methods. Shutdown hooks may fail to execute as expected in such cases because the JVM cannot guarantee that they will be executed as intended. | ## Risk Assessment
Failure to perform necessary cleanup at program termination may leave the system in an inconsistent state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO14-J
Medium
Likely
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,638 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487638 | 2 | 13 | FIO15-J | Do not reset a servlet's output stream after committing it | When a web servlet receives a request from a client, it must produce some suitable response. Java's
HttpServlet
provides the
HttpServletResponse
object to capture a suitable response. This response can be built using an output stream provided by
getOutputStream()
or a writer provided by
getWriter()
.
A response is said to be committed if its status code and HTML headers have been sent [
J2EE API 2013
]. After a response is committed, further data may be added to the response, but certain behaviors become impossible. For example, it is impossible to change the character encoding, because the encoding is included in the HTML header. Some of these illegal operations will yield a
IllegalStateException
, while others will have no effect. These illegal behaviors include the following:
Resetting the stream or recommitting to the stream
Flushing the stream's or writer's buffer
Invoking either
getWriter()
or
getOutputStream()
Redirecting an
HttpServletResponse
to another server
Modifying the stream's character encoding, content type, or buffer size | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... Write some response text
out.flush(); // Commits the stream
// ... More work
} catch (IOException x) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... Write some response text
out.flush(); // Commits the stream
// ... More work
} catch (IOException x) {
out.println(x.getMessage());
out.flush();
}
}
## Noncompliant Code Example
This noncompliant code example illustrates a servlet that indicates if an internal error occurs by using the
HttpServletResponse.sendError()
method to indicate an internal server error.
#ffcccc
java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... Write some response text
out.flush(); // Commits the stream
// ... More work
} catch (IOException x) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
If an
IOException
occurs after flushing the stream, the stream will be committed when the
catch
clause executes. Consequently, the
sendError()
operation will throw an
IllegalStateException
.
## Noncompliant Code Example
This noncompliant code example illustrates a servlet that indicates if an internal error occurs by printing an error message to the output stream and flushing it:
#ffcccc
java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... Write some response text
out.flush(); // Commits the stream
// ... More work
} catch (IOException x) {
out.println(x.getMessage());
out.flush();
}
}
If an
IOException
occurs after flushing the stream, the stream will be reflushed in the
catch
clause. | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Do work that doesn't require the output stream
} catch (IOException x) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... All work
} catch (IOException ex) {
out.println(ex.getMessage());
} finally {
out.flush();
}
}
## Compliant Solution
The
sendError()
method should be used only before an output stream or writer has been created because it overwrites any output. Once the output stream or writer has been created, errors should be output alongside valid HTML. This compliant solution uses both strategies, ensuring that the stream is flushed only once, in the
finally
clause.
#ccccff
java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Do work that doesn't require the output stream
} catch (IOException x) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... All work
} catch (IOException ex) {
out.println(ex.getMessage());
} finally {
out.flush();
}
} | ## Risk Assessment
If a servlet's output stream is reset after it has been committed, an
IllegalStateException
usually results, which can cause the servlet's response to be truncated.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO15-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,708 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487708 | 2 | 13 | FIO16-J | Canonicalize path names before validating them | According to the Java API [
API 2006
] for
class
java.io.File
:
A pathname, whether abstract or in string form, may be either
absolute
or
relative
. An absolute pathname is complete in that no other information is required to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname.
Absolute or relative path names may contain file links such as symbolic (soft) links, hard links, shortcuts, shadows, aliases, and junctions. These file links must be fully resolved before any file validation operations are performed. For example, the final target of a symbolic link called
trace
might be the path name
/home/system/trace
. Path names may also contain special file names that make validation difficult:
"
.
" refers to the directory itself.
Inside a directory, the special file name "
..
" refers to the directory's parent directory.
In addition to these specific issues, a wide variety of operating system–specific and file system–specific naming conventions make validation difficult.
Canonicalizing
file names makes it easier to validate a path name. More than one path name can refer to a single directory or file. Further, the textual representation of a path name may yield little or no information regarding the directory or file to which it refers. Consequently, all path names must be fully resolved or
canonicalized
before validation.
Validation may be necessary, for example, when attempting to restrict user access to files within a particular directory or to otherwise make security decisions based on the name of a file name or path name. Frequently, these restrictions can be circumvented by an attacker by exploiting a
directory traversal
or
path equivalence
vulnerability
. A
directory traversal
vulnerability allows an I/O operation to escape a specified operating directory. A
path equivalence
vulnerability occurs when an attacker provides a different but equivalent name for a resource to bypass security checks.
Canonicalization contains an inherent race window between the time the program obtains the canonical path name and the time it opens the file. While the canonical path name is being validated, the file system may have been modified and the canonical path name may no longer reference the original valid file. Fortunately, this
race condition
can be easily mitigated. The canonical path name can be used to determine whether the referenced file name is in a secure directory (see
for more information). If the referenced file is in a secure directory, then, by definition, an attacker cannot tamper with it and cannot exploit the race condition.
This recommendation is a specific instance of
. | File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
FileOutputStream fis = new FileOutputStream(file);
// ...
File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonicalPath();
FileOutputStream fis = new FileOutputStream(canonicalPath);
// ...
## Noncompliant Code Example
This noncompliant code example allows the user to specify the path of an image file to open.
By prepending
/img/
to the directory, this code enforces a policy that only files in this directory should be opened. The program also uses the
isInSecureDir()
method defined in
.
However, t
he user can still specify a file outside the intended directory by entering an argument that contains
../
sequences. An attacker can also create a link in the
/img
directory that refers to a directory or file outside of that directory. The path name of the link might appear to reside in the
/img
directory and consequently pass validation, but the operation will actually be performed on the final target of the link, which can reside outside the intended directory.
#FFCCCC
File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
FileOutputStream fis = new FileOutputStream(file);
// ...
## Noncompliant Code Example (getCanonicalPath())
This noncompliant code example attempts to mitigate the issue by using the
File.getCanonicalPath()
method, introduced in Java 2, which fully resolves the argument and constructs a canonicalized path. Special file names such as dot dot (
..
) are also removed so that the input is reduced to a canonicalized form before validation is carried out. An attacker cannot use
../
sequences to break out of the specified directory when the
validate()
method is present. For example, the path
/img/../etc/passwd
resolves to
/etc/passwd
. The
getCanonicalPath()
method throws a security exception when used in applets because it reveals too much information about the host machine. The
getCanonicalFile()
method behaves like
getCanonicalPath()
but returns a new
File
object instead of a
String
.
Unfortunately, the canonicalization is performed after the validation, which renders the validation ineffective.
#FFCCCC
File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonicalPath();
FileOutputStream fis = new FileOutputStream(canonicalPath);
// ... | File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonicalPath();
if (!canonicalPath.equals("/img/java/file1.txt") &&
!canonicalPath.equals("/img/java/file2.txt")) {
// Invalid file; handle error
}
FileInputStream fis = new FileInputStream(f);
// All files in /img/java can be read
grant codeBase "file:/home/programpath/" {
permission java.io.FilePermission "/img/java", "read";
};
## Compliant Solution (getCanonicalPath())
This compliant solution obtains the file name from the untrusted user input, canonicalizes it, and then validates it against a list of benign path names. It operates on the specified file only when validation succeeds, that is, only if the file is one of the two valid files
file1.txt
or
file2.txt
in
/img/java
.
#ccccff
File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonicalPath();
if (!canonicalPath.equals("/img/java/file1.txt") &&
!canonicalPath.equals("/img/java/file2.txt")) {
// Invalid file; handle error
}
FileInputStream fis = new FileInputStream(f);
## Compliant Solution (Security Manager)
A comprehensive way to handle this issue is to grant the application the permissions to operate only on files present within the intended directory—the
/img
directory in this example. This compliant solution specifies the absolute path of the program in its
security policy
file and grants
java.io.FilePermission
with target
/img/java
and the read action.
This solution requires that the
/img
directory is a secure directory, as described in
.
#ccccff
// All files in /img/java can be read
grant codeBase "file:/home/programpath/" {
permission java.io.FilePermission "/img/java", "read";
}; | ## Risk Assessment
Using path names from untrusted sources without first
canonicalizing
them and then validating them can result in directory traversal and path equivalence
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO16-J
Medium
Unlikely
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,662 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487662 | 3 | 13 | FIO50-J | Do not make assumptions about file creation | Although creating a file is usually accomplished with a single method call, this single action raises multiple security-related questions. What should be done if the file cannot be created? What should be done if the file already exists? What should be the file's initial attributes, such as permissions?
Java provides several generations of file-handling facilities. The original input/output facilities, which included basic file handling, are in the package
java.io
. More comprehensive facilities were included in JDK 1.4 with the New I/O package
java.nio
(see
New I/O APIs
[
Oracle 2010b
]). Still more comprehensive facilities were included in JDK 1.7 with the New I/O 2 package
java.nio.file
. Both
packages introduced a number of methods to support finer-grained control over file creation.
FIO01-J. Create files with appropriate access permissions
explains how to specify the permissions of a newly created file. | public void createFile(String filename)
throws FileNotFoundException{
OutputStream out = new FileOutputStream(filename);
// Work with file
}
public void createFile(String filename)
throws IOException{
OutputStream out = new FileOutputStream(filename, true);
if (!new File(filename).createNewFile()) {
// File cannot be created...handle error
} else {
out = new FileOutputStream(filename);
// Work with file
}
}
## Noncompliant Code Example
## This noncompliant code example tries to open a file for writing:
#ffcccc
java
public void createFile(String filename)
throws FileNotFoundException{
OutputStream out = new FileOutputStream(filename);
// Work with file
}
If the file existed before being opened, its former contents will be overwritten with the contents provided by the program.
## Noncompliant Code Example (TOCTOU)
This noncompliant code example tries to avoid altering an existing file by creating an empty file using
java.io.File.createNewfile()
. If a file with the given name already exists, then
createNewFile()
will return
false
without destroying the named file's contents.
#ffcccc
java
public void createFile(String filename)
throws IOException{
OutputStream out = new FileOutputStream(filename, true);
if (!new File(filename).createNewFile()) {
// File cannot be created...handle error
} else {
out = new FileOutputStream(filename);
// Work with file
}
}
Unfortunately, this solution is subject to a TOCTOU (time-of-check, time-of-use) race condition. It is possible for an attacker to modify the file system after the empty file is created but before the file is opened, such that the file that is opened is distince from the file that was created. | public void createFile(String filename)
throws FileNotFoundException{
try (OutputStream out = new BufferedOutputStream(
Files.newOutputStream(Paths.get(filename),
StandardOpenOption.CREATE_NEW))) {
// Work with out
} catch (IOException x) {
// File not writable...handle error
}
}
## Compliant Solution (Files)
This compliant solution uses the
java.nio.file.Files.newOutputStream()
method to atomically create the file and throws an exception if the file already exists:
#ccccff
java
public void createFile(String filename)
throws FileNotFoundException{
try (OutputStream out = new BufferedOutputStream(
Files.newOutputStream(Paths.get(filename),
StandardOpenOption.CREATE_NEW))) {
// Work with out
} catch (IOException x) {
// File not writable...handle error
}
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,531 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487531 | 3 | 13 | FIO51-J | Identify files using multiple file attributes | Many file-related security vulnerabilities result from a program accessing an unintended file object. This often happens because file names are only loosely bound to underlying file objects. File names provide no information regarding the nature of the file object itself. Furthermore, the binding of a file name to a file object is reevaluated each time the file name is used in an operation. This reevaluation can introduce a time-of-check, time-of-use (TOCTOU) race condition into an application. Objects of type
java.io.File
and of type
java.nio.file.Path
are bound to underlying file objects by the operating system only when the file is accessed.
The
java.io.File
constructors and the
java.io.File
methods
renameTo()
and
delete()
rely solely on file names for file identification. The same holds for the
java.nio.file.Path.get()
methods for creating
Path
objects and the
move
and
delete
methods of
java.nio.file.Files
. Use all of these methods with caution.
Fortunately, files can often be identified by other attributes in addition to the file name—for example, by comparing file creation time or modification times. Information about a file that has been created and closed can be stored and then used to validate the identity of the file when it is reopened. Comparing multiple attributes of the file increases the likelihood that the reopened file is the same file that was previously opened.
File identification is less crucial for applications that maintain their files in secure directories where they can be accessed only by the owner of the file and (possibly) by a system administrator (see
). | public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Close the file
/*
* A race condition here allows for an attacker to switch
* out the file for another
*/
// Reopen the file for reading
Path file2 = Paths.get(filename);
try (BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try(BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file
} catch (IOException e) {
// Handle error
}
// ...
// Reopen the file for reading
Path file2 = Paths.get(filename);
if (!Files.isSameFile(file1, file2)) {
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
long size = new File( filename).length();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
try (BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream( filename)))) {
// ... Work with file
} catch (IOException e) {
// Handle error
}
}
## Noncompliant Code Example
In this noncompliant code example, the file identified by the string
filename
is opened, processed, closed, and then reopened for reading:
#FFcccc
public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Close the file
/*
* A race condition here allows for an attacker to switch
* out the file for another
*/
// Reopen the file for reading
Path file2 = Paths.get(filename);
try (BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
Because the binding between the file name and the underlying file object is reevaluated when the
BufferedReader
is created, this code cannot guarantee that the file opened for reading is the same file that was previously opened for writing. An attacker might have replace the original file (with a symbolic link, for example) between the first call to
close()
and the subsequent creation of the
BufferedReader
.
## Noncompliant Code Example (Files.isSameFile())
In this noncompliant code example, the programmer attempts to ensure that the file opened for reading is the same as the file previously opened for writing by calling the method
Files.isSameFile()
:
#FFcccc
public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try(BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file
} catch (IOException e) {
// Handle error
}
// ...
// Reopen the file for reading
Path file2 = Paths.get(filename);
if (!Files.isSameFile(file1, file2)) {
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
Unfortunately, the Java API lacks any guarantee that the method
isSameFile()
actually checks whether the files are the same file. The
Java 7 API
for
isSameFile()
[
API 2011
]
says:
If both
Path
objects are equal then this method returns
true
without checking if the file exists.
That is,
isSameFile()
may simply check that the paths to the two files are the same and cannot detect if the file at that path had been replaced by a different file between the two open operations.
## Noncompliant Code Example (File Size)
## This noncompliant code example tries to ensure that the file it opens contains exactly 1024 bytes:
#ffcccc
java
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
long size = new File( filename).length();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
try (BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream( filename)))) {
// ... Work with file
} catch (IOException e) {
// Handle error
}
}
This code is subject to a TOCTOU race condition between when the file size is checked and when the file is opened. If an attacker replaces a 1024-byte file with another file during this race window, he or she can cause this program to open any file, defeating the check. | public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
FileTime creation1 = attr1.creationTime();
FileTime modified1 = attr1.lastModifiedTime();
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Reopen the file for reading
Path file2 = Paths.get(filename);
BasicFileAttributes attr2 =
Files.readAttributes(file2, BasicFileAttributes.class);
FileTime creation2 = attr2.creationTime();
FileTime modified2 = attr2.lastModifiedTime();
if ( (!creation1.equals(creation2)) ||
(!modified1.equals(modified2)) ) {
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
Object key1 = attr1.fileKey();
// Open the file for writing
try(BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file
} catch (IOException e) {
// Handle error
}
// Reopen the file for reading
Path file2 = Paths.get(filename);
BasicFileAttributes attr2 =
Files.readAttributes(file2, BasicFileAttributes.class);
Object key2 = attr2.fileKey();
if ( !key1.equals(key2) ) {
System.out.println("File tampered with");
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
public void processFile(String filename) throws IOException{
// Identify a file by its path
try (RandomAccessFile file = new
RandomAccessFile(filename, "rw")) {
// Write to file...
// Go back to beginning and read contents
file.seek(0);
string line;
while (line=file.readLine()) != null {
System.out.println(line);
}
}
}
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
try (FileInputStream in = new FileInputStream( filename);
BufferedReader br = new BufferedReader(
new InputStreamReader(in))) {
long size = in.getChannel().size();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
## Compliant Solution (Multiple Attributes)
This compliant solution checks the creation and last-modified times of the files to increase the likelihood that the file opened for reading is the same file that was written:
#ccccff
public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
FileTime creation1 = attr1.creationTime();
FileTime modified1 = attr1.lastModifiedTime();
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Reopen the file for reading
Path file2 = Paths.get(filename);
BasicFileAttributes attr2 =
Files.readAttributes(file2, BasicFileAttributes.class);
FileTime creation2 = attr2.creationTime();
FileTime modified2 = attr2.lastModifiedTime();
if ( (!creation1.equals(creation2)) ||
(!modified1.equals(modified2)) ) {
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
Although this solution is reasonably secure, a determined attacker could create a symbolic link with the same creation and last-modified times as the original file. Also, a TOCTOU race condition occurs between the time the file's attributes are first read and the time the file is first opened. Likewise, another TOCTOU condition occurs the second time the attributes are read and the file is reopened.
## Compliant Solution (POSIXfileKeyAttribute)
In environments that support the
fileKey
attribute, a more reliable approach is to check that the
fileKey
attributes of the two files are the same. The
fileKey
attribute is an object that "uniquely identifies the file"
[
API 2011
]
, as shown in this compliant solution:
#ccccff
public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
Object key1 = attr1.fileKey();
// Open the file for writing
try(BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file
} catch (IOException e) {
// Handle error
}
// Reopen the file for reading
Path file2 = Paths.get(filename);
BasicFileAttributes attr2 =
Files.readAttributes(file2, BasicFileAttributes.class);
Object key2 = attr2.fileKey();
if ( !key1.equals(key2) ) {
System.out.println("File tampered with");
// File was tampered with, handle error
}
try(BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
This approach will not work on all platforms. For example, on Windows 7 Enterprise Edition, all
fileKey
attributes are null.
The file key returned by the
fileKey()
method is guaranteed to be unique only if the file system and files remain static. A file system may reuse an identifier, for example, after a file is deleted. Like the previous compliant solution, there is a TOCTOU race window between the time the file's attributes are first read and the time the file is first opened. Another TOCTOU condition occurs the second time the attributes are read and the file is reopened.
## Compliant Solution (RandomAccessFile)
A better approach is to avoid reopening a file. The following compliant solution demonstrates use of a
RandomAccessFile
, which can be opened for both reading and writing. Because the file is only closed automatically by the
try-with-resources
statement, no race condition can occur.
#ccccff
public void processFile(String filename) throws IOException{
// Identify a file by its path
try (RandomAccessFile file = new
RandomAccessFile(filename, "rw")) {
// Write to file...
// Go back to beginning and read contents
file.seek(0);
string line;
while (line=file.readLine()) != null {
System.out.println(line);
}
}
}
## Compliant Solution (File Size)
This compliant solution uses the
FileChannel.size()
method to obtain the file size. Because this method is applied to the
FileInputStream
only after the file has been opened, this solution eliminates the race window.
#ccccff
java
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
try (FileInputStream in = new FileInputStream( filename);
BufferedReader br = new BufferedReader(
new InputStreamReader(in))) {
long size = in.getChannel().size();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
Applicability
Attackers frequently exploit file-related vulnerabilities to cause programs to access an unintended file. Proper file identification is necessary to prevent exploitation. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,632 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487632 | 3 | 13 | FIO52-J | Do not store unencrypted sensitive information on the client side | When building an application that uses a client-server model, storing sensitive information, such as user credentials, on the client side may result in its unauthorized disclosure if the client is vulnerable to attack.
For web applications, the most common mitigation to this problem is to provide the client with a cookie and store the sensitive information on the server. Cookies are created by a web server and are stored for a period of time on the client. When the client reconnects to the server, it provides the cookie, which identifies the client to the server, and the server then provides the sensitive information.
Cookies do not protect sensitive information against cross-site scripting (XSS) attacks. An attacker who is able to obtain a cookie either through an XSS attack or directly by attacking the client can obtain the sensitive information from the server using the cookie. This risk is timeboxed if the server invalidates the session after a limited time has elapsed, such as 15 minutes.
A cookie is typically a short string. If it contains sensitive information, that information should be encrypted. Sensitive information includes passwords, credit card numbers, social security numbers, and any other personally identifiable information about the user. For more details about managing passwords, see
. For more information about securing the memory that holds sensitive information, see
. | protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
LoginService loginService = new LoginServiceImpl();
if (rememberMe) {
if (request.getCookies()[0] != null &&
request.getCookies()[0].getValue() != null) {
String[] value = request.getCookies()[0].getValue().split(";");
if (!loginService.isUserValid(value[0], value[1].toCharArray())) {
// Set error and return
} else {
// Forward to welcome page
}
} else {
boolean validated = loginService.isUserValid(username, password);
if (validated) {
Cookie loginCookie = new Cookie("rememberme", username
+ ";" + new String(password));
response.addCookie(loginCookie);
// ... Forward to welcome page
} else {
// Set error and return
}
}
} else {
// No remember-me functionality selected
// Proceed with regular authentication;
// if it fails set error and return
}
Arrays.fill(password, ' ');
}
## Noncompliant Code Example
In this noncompliant code example, the login servlet stores the user name and password in the cookie to identify the user for subsequent requests:
#FFcccc
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
LoginService loginService = new LoginServiceImpl();
if (rememberMe) {
if (request.getCookies()[0] != null &&
request.getCookies()[0].getValue() != null) {
String[] value = request.getCookies()[0].getValue().split(";");
if (!loginService.isUserValid(value[0], value[1].toCharArray())) {
// Set error and return
} else {
// Forward to welcome page
}
} else {
boolean validated = loginService.isUserValid(username, password);
if (validated) {
Cookie loginCookie = new Cookie("rememberme", username
+ ";" + new String(password));
response.addCookie(loginCookie);
// ... Forward to welcome page
} else {
// Set error and return
}
}
} else {
// No remember-me functionality selected
// Proceed with regular authentication;
// if it fails set error and return
}
Arrays.fill(password, ' ');
}
However, the attempt to implement the remember-me functionality is insecure because an attacker with access to the client machine can obtain this information directly on the client. This code also violates
. The client may also have transmitted the password in clear unless it encrypted the password or uses HTTPS. | protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
LoginService loginService = new LoginServiceImpl();
boolean validated = false;
if (rememberMe) {
if (request.getCookies()[0] != null &&
request.getCookies()[0].getValue() != null) {
String[] value = request.getCookies()[0].getValue().split(";");
if (value.length != 2) {
// Set error and return
}
if (!loginService.mappingExists(value[0], value[1])) {
// (username, random) pair is checked
// Set error and return
}
} else {
validated = loginService.isUserValid(username, password);
if (!validated) {
// Set error and return
}
}
String newRandom = loginService.getRandomString();
// Reset the random every time
loginService.mapUserForRememberMe(username, newRandom);
HttpSession session = request.getSession();
session.invalidate();
session = request.getSession(true);
// Set session timeout to 15 minutes
session.setMaxInactiveInterval(60 * 15);
// Store user attribute and a random attribute in session scope
session.setAttribute("user", loginService.getUsername());
Cookie loginCookie =
new Cookie("rememberme", username + ";" + newRandom);
loginCookie.setHttpOnly(true);
loginCookie.setSecure(true);
response.addCookie(loginCookie);
// ... Forward to welcome page
} else {
// No remember-me functionality selected
// ... Authenticate using isUserValid() and if failed, set error
}
Arrays.fill(password, ' ');
}
## Compliant Solution (Session)
This compliant solution implements the remember-me functionality by storing the user name and a secure random string in the cookie. It also maintains state in the session using
HttpSession
.
#ccccff
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
LoginService loginService = new LoginServiceImpl();
boolean validated = false;
if (rememberMe) {
if (request.getCookies()[0] != null &&
request.getCookies()[0].getValue() != null) {
String[] value = request.getCookies()[0].getValue().split(";");
if (value.length != 2) {
// Set error and return
}
if (!loginService.mappingExists(value[0], value[1])) {
// (username, random) pair is checked
// Set error and return
}
} else {
validated = loginService.isUserValid(username, password);
if (!validated) {
// Set error and return
}
}
String newRandom = loginService.getRandomString();
// Reset the random every time
loginService.mapUserForRememberMe(username, newRandom);
HttpSession session = request.getSession();
session.invalidate();
session = request.getSession(true);
// Set session timeout to 15 minutes
session.setMaxInactiveInterval(60 * 15);
// Store user attribute and a random attribute in session scope
session.setAttribute("user", loginService.getUsername());
Cookie loginCookie =
new Cookie("rememberme", username + ";" + newRandom);
loginCookie.setHttpOnly(true);
loginCookie.setSecure(true);
response.addCookie(loginCookie);
// ... Forward to welcome page
} else {
// No remember-me functionality selected
// ... Authenticate using isUserValid() and if failed, set error
}
Arrays.fill(password, ' ');
}
The server maintains a mapping between user names and secure random strings. When a user selects “Remember me,” the
doPost()
method checks whether the supplied cookie contains a valid user name and random string pair. If the mapping contains a matching pair, the server authenticates the user and forwards him or her to the welcome page. If not, the server returns an error to the client. If the user selects “Remember me” but the client fails to supply a valid cookie, the server requires the user to authenticate using his or her credentials. If the authentication is successful, the server issues a new cookie with remember-me characteristics.
This solution avoids session-fixation attacks by invalidating the current session and creating a new session. It also reduces the window during which an attacker could perform a session-hijacking attack by setting the session timeout to 15 minutes between client accesses. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,483 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487483 | 3 | 13 | FIO53-J | Use the serialization methods writeUnshared() and readUnshared() with care | When objects are serialized using the
writeObject()
method, each object is written to the output stream only once. Invoking the
writeObject()
method on the same object a second time places a back-reference to the previously serialized instance in the stream. Correspondingly, the
readObject()
method produces at most one instance for each object present in the input stream that was previously written by
writeObject().
According to the Java API [
API 2013
], the
writeUnshared()
method
writes an "unshared" object to the
ObjectOutputStream
. This method is identical to
writeObject
, except that it always writes the given object as a new, unique object in the stream (as opposed to a back-reference pointing to a previously serialized instance).
Correspondingly, the
readUnshared()
method
reads an "unshared" object from the
ObjectInputStream
. This method is identical to
readObject
, except that it prevents subsequent calls to
readObject
and
readUnshared
from returning additional references to the deserialized instance obtained via this call.
Consequently, the
writeUnshared()
and
readUnshared()
methods are unsuitable for round-trip serialization of data structures that contain reference cycles.
Consider the following code example:
public class Person {
private String name;
Person() {
// Do nothing - needed for serialization
}
Person(String theName) {
name = theName;
}
// Other details not relevant to this example
}
public class Student extends Person implements Serializable {
private Professor tutor;
Student() {
// Do nothing - needed for serialization
}
Student(String theName, Professor theTutor) {
super(theName);
tutor = theTutor;
}
public Professor getTutor() {
return tutor;
}
}
public class Professor extends Person implements Serializable {
private List<Student> tutees = new ArrayList<Student>();
Professor() {
// Do nothing - needed for serialization
}
Professor(String theName) {
super(theName);
}
public List<Student> getTutees () {
return tutees;
}
/**
* checkTutees checks that all the tutees
* have this Professor as their tutor
*/
public boolean checkTutees () {
boolean result = true;
for (Student stu: tutees) {
if (stu.getTutor() != this) {
result = false;
break;
}
}
return result;
}
}
// ...
Professor jane = new Professor("Jane");
Student able = new Student("Able", jane);
Student baker = new Student("Baker", jane);
Student charlie = new Student("Charlie", jane);
jane.getTutees().add(able);
jane.getTutees().add(baker);
jane.getTutees().add(charlie);
System.out.println("checkTutees returns: " + jane.checkTutees());
// Prints "checkTutees returns: true"
Professor
and
Students
are types that extend the basic type
Person
. A student (that is, an object of type
Student
) has a tutor of type
Professor
. A professor (that is, an object of type
Professor
) has a list (actually, an
ArrayList
) of tutees (of type
Student
). The method
checkTutees()
checks whether all of the tutees of this professor have this professor as their tutor, returning
true
if that is the case and
false
otherwise.
Suppose that Professor Jane has three students, Able, Baker, and Charlie, all of whom have Professor Jane as their tutor. Issues can arise if the
writeUnshared()
and
readUnshared()
methods are used with these classes, as demonstrated in the following noncompliant code example. | String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeUnshared(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))){
Professor jane2 = (Professor)ois.readUnshared();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
}
## Noncompliant Code Example
## This noncompliant code example attempts to serialize the data from the previous example usingwriteUnshared().
#FFcccc
String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeUnshared(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))){
Professor jane2 = (Professor)ois.readUnshared();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
}
However, when the data is deserialized using
readUnshared()
, the
checkTutees()
method no longer returns
true
because the tutor objects of the three students are different from the original
Professor
object. | String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeObject(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))) {
Professor jane2 = (Professor)ois.readObject();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
}
## Compliant Solution
This compliant solution uses the
writeObject()
and
readObject()
methods to ensure that the tutor object referred to by the three students has a one-to-one mapping with the original
Professor
object. The
checkTutees()
method correctly returns
true
.
#ccccff
String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeObject(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))) {
Professor jane2 = (Professor)ois.readObject();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
} | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,713 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487713 | 2 | 0 | IDS00-J | Prevent SQL injection | SQL injection vulnerabilities arise in applications where elements of a SQL query originate from an untrusted source. Without precautions, the
untrusted data
may maliciously alter the query, resulting in information leaks or data modification. The primary means of preventing SQL injection are
sanitization
and validation, which are typically implemented as parameterized queries and stored procedures.
Suppose a system authenticates users by issuing the following query to a SQL database. If the query returns any results, authentication succeeds; otherwise, authentication fails.
sql
SELECT * FROM db_user WHERE username='<USERNAME>' AND
password='<PASSWORD>'
Suppose an attacker can substitute arbitrary strings for
<USERNAME>
and
<PASSWORD>
. In that case, the authentication mechanism can be bypassed by supplying the following
<USERNAME>
with an arbitrary password:
sql
validuser' OR '1'='1
The authentication routine dynamically constructs the following query:
sql
SELECT * FROM db_user WHERE username='validuser' OR '1'='1' AND password='<PASSWORD>'
If
validuser
is a valid user name, this
SELECT
statement yields the
validuser
record in the table. The password is never checked because
username='validuser'
is true; consequently, the items after the
OR
are not tested. As long as the components after the
OR
generate a syntactically correct SQL expression, the attacker is granted the access of
validuser
.
Similarly, an attacker could supply the following string for
<PASSWORD>
with an arbitrary username:
sql
' OR '1'='1
producing the following query:
sql
SELECT * FROM db_user WHERE username='<USERNAME>' AND password='' OR '1'='1'
'1'='1'
always evaluates to true, causing the query to yield every row in the database. In this scenario, the attacker would be authenticated without needing a valid username or password. | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(String username, char[] password)
throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "SELECT * FROM db_user WHERE username = '"
+ username +
"' AND password = '" + pwd + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
if (!rs.next()) {
throw new SecurityException(
"User name or password incorrect"
);
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "select * from db_user where username=" +
username + " and password =" + pwd;
PreparedStatement stmt = connection.prepareStatement(sqlString);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
}
## Noncompliant Code Example
This noncompliant code example shows JDBC code to authenticate a user to a system. The password is passed as a
char
array, the database connection is created, and then the passwords are hashed.
Unfortunately, this code example permits a SQL injection attack by incorporating the unsanitized input argument
username
into the SQL command, allowing an attacker to inject
validuser' OR '1'='1
. The
password
argument cannot be used to attack this program because it is passed to the
hashPassword()
function, which also
sanitizes
the input.
#FFcccc
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(String username, char[] password)
throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "SELECT * FROM db_user WHERE username = '"
+ username +
"' AND password = '" + pwd + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
if (!rs.next()) {
throw new SecurityException(
"User name or password incorrect"
);
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
}
## Noncompliant Code Example (PreparedStatement)
The JDBC library provides an API for building SQL commands that sanitize
untrusted data
. The
java.sql.PreparedStatement
class properly escapes input strings, preventing SQL injection when used correctly. This code example modifies the
doPrivilegedAction()
method to use a
PreparedStatement
instead of
java.sql.Statement
. However, the prepared statement still permits a SQL injection attack by incorporating the unsanitized input argument
username
into the prepared statement.
#FFcccc
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "select * from db_user where username=" +
username + " and password =" + pwd;
PreparedStatement stmt = connection.prepareStatement(sqlString);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
} | public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Validate username length
if (username.length() > 8) {
// Handle error
}
String sqlString =
"select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
## Compliant Solution (PreparedStatement)
This compliant solution uses a parametric query with a
?
character as a placeholder for the argument. This code also validates the length of the
username
argument, preventing an attacker from submitting an arbitrarily long user name.
#ccccff
java
public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Validate username length
if (username.length() > 8) {
// Handle error
}
String sqlString =
"select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
Use the
set*()
methods of the
PreparedStatement
class to enforce strong type checking. This technique mitigates the SQL injection
vulnerability
because the input is properly escaped by automatic entrapment within double quotes. Note that prepared statements must be used even with queries that insert data into the database. | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS00-J
High
Likely
Yes
No
P18
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,810 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487810 | 2 | 0 | IDS01-J | Normalize strings before validating them | Many applications that accept untrusted input strings employ input filtering and validation mechanisms based on the strings' character data. For example, an application's strategy for avoiding cross-site scripting (XSS) vulnerabilities may include forbidding <script> tags in inputs. Such blacklisting mechanisms are a useful part of a security strategy, even though they are insufficient for complete input validation and sanitization.
Character information in Java is based on the Unicode Standard. The following table shows the version of Unicode supported by the latest three releases of Java SE.
Java Version
Unicode Version
Java SE 6
Unicode Standard, version 4.0 [
Unicode 2003
]
Java SE 7
Unicode Standard, version 6.0.0 [
Unicode 2011
]
Java SE 8
Unicode Standard, version 6.2.0 [
Unicode 2012
]
Applications that accept untrusted input should
normalize
the input before validating it. Normalization is important because in Unicode, the same string can have many different representations.
According to the Unicode Standard [
Davis 2008
], annex #15, Unicode Normalization Forms:
When implementations keep strings in a normalized form, they can be assured that equivalent strings have a unique binary representation. | // String s may be user controllable
// \uFE64 is normalized to < and \uFE65 is normalized to > using the NFKC normalization form
String s = "\uFE64" + "script" + "\uFE65";
// Validate
Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found black listed tag
throw new IllegalStateException();
} else {
// ...
}
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
## Noncompliant Code Example
The
Normalizer.normalize()
method transforms Unicode text into
the standard normalization forms described in
Unicode Standard Annex #15 Unicode Normalization Forms
.
Frequently, the most suitable normalization form for performing input validation on arbitrarily encoded strings is KC (NFKC) .
## This noncompliant code example attempts to validate theStringbefore performing normalization.
#FFcccc
// String s may be user controllable
// \uFE64 is normalized to < and \uFE65 is normalized to > using the NFKC normalization form
String s = "\uFE64" + "script" + "\uFE65";
// Validate
Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found black listed tag
throw new IllegalStateException();
} else {
// ...
}
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
The validation logic fails to detect the
<script>
tag because it is not normalized at the time. Therefore the system accepts the invalid input. | String s = "\uFE64" + "script" + "\uFE65";
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
// Validate
Pattern pattern = Pattern.compile("[<>]");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found blacklisted tag
throw new IllegalStateException();
} else {
// ...
}
## Compliant Solution
This compliant solution normalizes the string before validating it. Alternative representations of the string are normalized to the canonical angle brackets. Consequently, input validation correctly detects the malicious input and throws an
IllegalStateException
.
#ccccff
String s = "\uFE64" + "script" + "\uFE65";
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
// Validate
Pattern pattern = Pattern.compile("[<>]");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found blacklisted tag
throw new IllegalStateException();
} else {
// ...
} | ## Risk Assessment
Validating input before normalization affords attackers the opportunity to bypass filters and other security mechanisms. It can result in the execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS01-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,909 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487909 | 2 | 0 | IDS03-J | Do not log unsanitized user input | A log injection
vulnerability
arises when a log entry contains unsanitized user input. A malicious user can insert fake log data and consequently deceive system administrators as to the system's behavior [
OWASP 2008
]. For example, an attacker might split a legitimate log entry into two log entries by entering a carriage return and line feed (CRLF) sequence to mislead an auditor. Log injection attacks can be prevented by
sanitizing
and validating any untrusted input sent to a log.
Logging unsanitized user input can also result in leaking
sensitive data
across a trust boundary. For example, an attacker might inject a script into a log file such that when the file is viewed using a web browser, the browser could provide the attacker with a copy of the administrator's cookie so that the attacker might gain access as the administrator. | if (loginSuccessful) {
logger.severe("User login succeeded for: " + username);
} else {
logger.severe("User login failed for: " + username);
}
May 15, 2011 2:19:10 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login failed for: guest
guest
May 15, 2011 2:25:52 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login succeeded for: administrator
May 15, 2011 2:19:10 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login failed for: guest
May 15, 2011 2:25:52 PM java.util.logging.LogManager log
SEVERE: User login succeeded for: administrator
## Noncompliant Code Example
## This noncompliant code example logsuntrusted datafrom an unauthenticated user without datasanitization.
#FFCCCC
if (loginSuccessful) {
logger.severe("User login succeeded for: " + username);
} else {
logger.severe("User login failed for: " + username);
}
Without sanitization, a log injection attack is possible. A standard log message when
username
is
guest
might look like this:
May 15, 2011 2:19:10 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login failed for: guest
If the
username
that is used in a log message is not
guest
but rather a multiline string like this:
guest
May 15, 2011 2:25:52 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login succeeded for: administrator
the log would contain the following misleading data:
May 15, 2011 2:19:10 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login failed for: guest
May 15, 2011 2:25:52 PM java.util.logging.LogManager log
SEVERE: User login succeeded for: administrator | if (loginSuccessful) {
logger.severe("User login succeeded for: " + sanitizeUser(username));
} else {
logger.severe("User login failed for: " + sanitizeUser(username));
}
public String sanitizeUser(String username) {
return Pattern.matches("[A-Za-z0-9_]+", username)
? username : "unauthorized user";
}
Logger sanLogger = new SanitizedTextLogger(logger);
if (loginSuccessful) {
sanLogger.severe("User login succeeded for: " + username);
} else {
sanLogger.severe("User login failed for: " + username);
}
class SanitizedTextLogger extends Logger {
Logger delegate;
public SanitizedTextLogger(Logger delegate) {
super(delegate.getName(), delegate.getResourceBundleName());
this.delegate = delegate;
}
public String sanitize(String msg) {
Pattern newline = Pattern.compile("\n");
Matcher matcher = newline.matcher(msg);
return matcher.replaceAll("\n ");
}
public void severe(String msg) {
delegate.severe(sanitize(msg));
}
// .. Other Logger methods which must also sanitize their log messages
}
## Compliant Solution (Sanitized User)
## This compliant solution sanitizes theusernamebefore logging it, preventing injection attacks.
#ccccff
if (loginSuccessful) {
logger.severe("User login succeeded for: " + sanitizeUser(username));
} else {
logger.severe("User login failed for: " + sanitizeUser(username));
}
The sanitization is done by a dedicated method for sanitizing user names:
#ccccff
public String sanitizeUser(String username) {
return Pattern.matches("[A-Za-z0-9_]+", username)
? username : "unauthorized user";
}
## Compliant Solution (Sanitized Logger)
This compliant solution uses a text logger that automatically sanitizes its input. A sanitized logger saves the developer from having to worry about unsanitized log messages.
#ccccff
Logger sanLogger = new SanitizedTextLogger(logger);
if (loginSuccessful) {
sanLogger.severe("User login succeeded for: " + username);
} else {
sanLogger.severe("User login failed for: " + username);
}
The sanitized text logger takes as delegate an actual logger. We assume the logger outputs text log messages to a file, network, or the console, and each log message has no indented lines. The sanitized text logger sanitizes all text to be logged by indenting every line except the first by two spaces. While a malicious user can indent text by more, a malicious user cannot create a fake log entry because all of her output will be indented, except for the real log output.
#ccccff
class SanitizedTextLogger extends Logger {
Logger delegate;
public SanitizedTextLogger(Logger delegate) {
super(delegate.getName(), delegate.getResourceBundleName());
this.delegate = delegate;
}
public String sanitize(String msg) {
Pattern newline = Pattern.compile("\n");
Matcher matcher = newline.matcher(msg);
return matcher.replaceAll("\n ");
}
public void severe(String msg) {
delegate.severe(sanitize(msg));
}
// .. Other Logger methods which must also sanitize their log messages
} | ## Risk Assessment
Allowing unvalidated user input to be logged can result in forging of log entries, leaking secure information, or storing
sensitive data
in a manner that violates a local law or regulation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS03-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,470 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487470 | 2 | 0 | IDS04-J | Safely extract files from ZipInputStream | Java provides the
java.util.zip
package for zip-compatible data compression. It provides classes that enable you to read, create, and modify ZIP and GZIP file formats.
A number of security concerns must be considered when extracting file entries from a ZIP file using
java.util.zip.ZipInputStream
. File names may contain path traversal information that may cause them to be extracted outside of the intended directory, frequently with the purpose of overwriting existing system files.
Directory traversal
or
path equivalence
vulnerabilities
can be eliminated by
canonicalizing
the path name, in accordance with
, and then validating the location before extraction.
A second issue is that the extraction process can cause excessive consumption of system resources, possibly resulting in a
denial-of-service attack
when resource usage is disproportionately large compared to the input data. The zip algorithm can produce very large compression ratios [
Mahmoud 2002
]. For example, a file consisting of alternating lines of
a
characters and
b
characters can achieve a compression ratio of more than 200 to 1. Even higher compression ratios can be obtained using input data that is targeted to the compression algorithm. This permits the existence of
zip bombs
in which a small ZIP or GZIP file consumes excessive resources when uncompressed. An example of a zip bomb is the file
42.zip
, which is a
zip file
consisting of 42
kilobytes
of compressed data, containing five layers of nested zip files in sets of 16, each bottom layer archive containing a 4.3
gigabyte
(4 294 967 295 bytes; ~ 3.99
GiB
) file for a total of 4.5
petabytes
(4 503 599 626 321 920 bytes; ~ 3.99
PiB
) of uncompressed data.
Zip bombs often rely on repetition of identical files to achieve their extreme compression ratios. Programs must either limit the traversal of such files or refuse to extract data beyond a certain limit. The actual limit depends on the capabilities of the platform and expected usage. | static final int BUFFER = 512;
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
}
static final int BUFFER = 512;
static final int TOOBIG = 0x6400000; // 100MB
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but only if the file is not insanely big
if (entry.getSize() > TOOBIG ) {
throw new IllegalStateException("File to be unzipped is huge.");
}
if (entry.getSize() == -1) {
throw new IllegalStateException("File to be unzipped might be huge.");
}
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
}
## Noncompliant Code Example
This noncompliant code fails to validate the name of the file that is being unzipped. It passes the name directly to the constructor of
FileOutputStream
. It also fails to check the resource consumption of the file that is being unzipped. It permits the operation to run to completion or until local resources are exhausted.
#FFcccc
static final int BUFFER = 512;
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
}
## Noncompliant Code Example (getSize())
This noncompliant code attempts to overcome the problem by calling the method
ZipEntry.getSize()
to check the uncompressed file size before uncompressing it. Unfortunately, a malicious attacker can forge the field in the ZIP file that purports to show the uncompressed size of the file, so the value returned by
getSize()
is unreliable, and local resources may still be exhausted.
#FFcccc
static final int BUFFER = 512;
static final int TOOBIG = 0x6400000; // 100MB
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but only if the file is not insanely big
if (entry.getSize() > TOOBIG ) {
throw new IllegalStateException("File to be unzipped is huge.");
}
if (entry.getSize() == -1) {
throw new IllegalStateException("File to be unzipped might be huge.");
}
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
}
Acknowledgement:
The
vulnerability
in this code was pointed out by Giancarlo Pellegrino, researcher at the Technical University of Darmstadt in Germany, and Davide Balzarotti, faculty member of EURECOM in France. | static final int BUFFER = 512;
static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
static final int TOOMANY = 1024; // Max number of files
// ...
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String canonicalPath = f.getCanonicalPath();
File iD = new File(intendedDir);
String canonicalID = iD.getCanonicalPath();
if (canonicalPath.startsWith(canonicalID)) {
return canonicalPath;
} else {
throw new IllegalStateException("File is outside extraction target directory.");
}
}
public final void unzip(String filename) throws java.io.IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
int entries = 0;
long total = 0;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but ensure that the filename is valid,
// and that the file is not insanely big
String name = validateFilename(entry.getName(), ".");
if (entry.isDirectory()) {
System.out.println("Creating directory " + name);
new File(name).mkdir();
continue;
}
FileOutputStream fos = new FileOutputStream(name);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
total += count;
}
dest.flush();
dest.close();
zis.closeEntry();
entries++;
if (entries > TOOMANY) {
throw new IllegalStateException("Too many files to unzip.");
}
if (total + BUFFER > TOOBIG) {
throw new IllegalStateException("File being unzipped is too big.");
}
}
} finally {
zis.close();
}
}
## Compliant Solution
In this compliant solution, the code validates the name of each entry before extracting the entry. If the name is invalid, the entire extraction is aborted. However, a compliant solution could also skip only that entry and continue the extraction process, or it could even extract the entry to some safe location.
Furthermore, the code inside the
while
loop tracks the uncompressed file size of each entry in a zip archive while extracting the entry. It throws an exception if the entry being extracted is too large—about 100MB in this case. We do not use the
ZipEntry.getSize()
method because the value it reports is not reliable. Finally, the code also counts the number of file entries in the archive and throws an exception if there are more than 1024 entries.
#ccccff
static final int BUFFER = 512;
static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
static final int TOOMANY = 1024; // Max number of files
// ...
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String canonicalPath = f.getCanonicalPath();
File iD = new File(intendedDir);
String canonicalID = iD.getCanonicalPath();
if (canonicalPath.startsWith(canonicalID)) {
return canonicalPath;
} else {
throw new IllegalStateException("File is outside extraction target directory.");
}
}
public final void unzip(String filename) throws java.io.IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
int entries = 0;
long total = 0;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but ensure that the filename is valid,
// and that the file is not insanely big
String name = validateFilename(entry.getName(), ".");
if (entry.isDirectory()) {
System.out.println("Creating directory " + name);
new File(name).mkdir();
continue;
}
FileOutputStream fos = new FileOutputStream(name);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
total += count;
}
dest.flush();
dest.close();
zis.closeEntry();
entries++;
if (entries > TOOMANY) {
throw new IllegalStateException("Too many files to unzip.");
}
if (total + BUFFER > TOOBIG) {
throw new IllegalStateException("File being unzipped is too big.");
}
}
} finally {
zis.close();
}
} | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS04-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,836 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487836 | 2 | 0 | IDS06-J | Exclude unsanitized user input from format strings | The
java.io
package includes a
PrintStream
class that has two equivalent formatting methods:
format()
and
printf()
.
System.out
and
System.err
are
PrintStream
objects, allowing
PrintStream
methods to be invoked on the standard output and error streams. The risks from using these methods are not as high as from using similar functions in C or C++ [
Seacord 2013
]. The standard library implementations throw an exception when any conversion argument fails to match the corresponding format specifier. Although throwing an exception helps mitigate against exploits, if
untrusted data
is incorporated into a format string, it can result in an information leak or allow a
denial-of-service attack
. Consequently, unsanitized input from an untrusted source must never be incorporated into format strings. | class Format {
static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] should contain the credit card expiration date
// but might contain %1$tm, %1$te or %1$tY format specifiers
System.out.format(
args[0] + " did not match! HINT: It was issued on %1$terd of some month", c
);
}
}
## Noncompliant Code Example
This noncompliant code example leaks information about a user's credit card. It incorporates
untrusted data
in a format string.
#FFcccc
class Format {
static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] should contain the credit card expiration date
// but might contain %1$tm, %1$te or %1$tY format specifiers
System.out.format(
args[0] + " did not match! HINT: It was issued on %1$terd of some month", c
);
}
}
In the absence of proper input validation, an attacker can determine the date against which the input is verified by supplying an input string that includes the
%1$tm
,
%1$te
, or
%1$tY
format specifiers. In this example, these
format specifiers
print 05 (May), 23 (day), and 1995 (year), respectively. | class Format {
static Calendar c =
new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] is the credit card expiration date
// Perform comparison with c,
// if it doesn't match, print the following line
System.out.format(
"%s did not match! HINT: It was issued on %terd of some month",
args[0], c
);
}
}
## Compliant Solution
This compliant solution excludes untrusted user input from the format string. Although
arg[0]
still may contain one or more format specifiers, they are now rendered inert.
#ccccff
class Format {
static Calendar c =
new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] is the credit card expiration date
// Perform comparison with c,
// if it doesn't match, print the following line
System.out.format(
"%s did not match! HINT: It was issued on %terd of some month",
args[0], c
);
}
} | ## Risk Assessment
Incorporating
untrusted data
in a format string may result in information leaks or allow a
denial-of-service attack
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS06-J
Medium
Unlikely
Yes
No
P4
L3
Automated Detection
Static analysis tools that perform taint analysis can diagnose some violations of this rule.
Tool
Version
Checker
Description
Tainting Checker
Trust and security errors (see Chapter 8)
Parasoft Jtest
CERT.IDS06.VAFS
Ensure the correct number of arguments for varargs methods with format strings
Injection25
Full Implementation
SV.EXEC
SV.EXEC.DIR
SV.EXEC.ENV
SV.EXEC.LOCAL
SV.EXEC.PATH
Implemented | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,877 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487877 | 2 | 0 | IDS07-J | Sanitize untrusted data passed to the Runtime.exec() method | External programs are commonly invoked to perform a function required by the overall system. This practice is a form of reuse and might even be considered a crude form of component-based software engineering. Command and argument injection
vulnerabilities
occur when an application fails to
sanitize
untrusted input and uses it in the execution of external programs.
Every Java application has a single instance of class
Runtime
that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the
Runtime.getRuntime()
method. The semantics of
Runtime.exec()
are poorly defined, so it is best not to rely on its behavior any more than necessary, but typically it invokes the command directly without a shell. If you want a shell, you can use
/bin/sh -c
on POSIX or
cmd.exe
on Windows. The variants of
exec()
that take the command line as a single string split it using a
StringTokenizer
. On Windows, these tokens are concatenated back into a single argument string before being executed.
Consequently, command injection attacks cannot succeed unless a command interpreter is explicitly invoked. However, argument injection attacks can occur when arguments have spaces, double quotes, and so forth, or when they start with a
-
or
/
to indicate a switch.
Any string data that originates from outside the program's trust boundary must be sanitized before being executed as a command on the current platform. | class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /C dir " + dir);
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
java -Ddir='dummy & echo bad' Java
cmd.exe /C dir dummy & echo bad
class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir});
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
sh -c 'ls dummy & echo bad'
## Noncompliant Code Example (Windows)
This noncompliant code example provides a directory listing using the
dir
command. It is implemented using
Runtime.exec()
to invoke the Windows
dir
command.
#FFcccc
class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /C dir " + dir);
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
Because
Runtime.exec()
receives unsanitized data originating from the environment, this code is susceptible to a command injection attack.
An attacker can
exploit
this program using the following command:
java -Ddir='dummy & echo bad' Java
The command executed is actually two commands:
cmd.exe /C dir dummy & echo bad
which first attempts to list a nonexistent
dummy
folder and then prints
bad
to the console.
## Noncompliant Code Example (POSIX)
This noncompliant code example provides the same functionality but uses the POSIX
ls
command. The only difference from the Windows version is the argument passed to
Runtime.exec()
.
#FFcccc
class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir});
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
The attacker can supply the same command shown in the previous noncompliant code example with similar effects. The command executed is actually
sh -c 'ls dummy & echo bad' | // ...
if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) {
// Handle error
}
// ...
// ...
String dir = null;
int number = Integer.parseInt(System.getProperty("dir")); // Only allow integer choices
switch (number) {
case 1:
dir = "data1";
break; // Option 1
case 2:
dir = "data2";
break; // Option 2
default: // Invalid
break;
}
if (dir == null) {
// Handle error
}
import java.io.File;
class DirList {
public static void main(String[] args) throws Exception {
File dir = new File(System.getProperty("dir"));
if (!dir.isDirectory()) {
System.out.println("Not a directory");
} else {
for (String file : dir.list()) {
System.out.println(file);
}
}
}
}
## Compliant Solution (Sanitization)
This compliant solution
sanitizes
the untrusted user input by permitting only a small group of whitelisted characters in the argument that will be passed to
Runtime.exec()
; all other characters are excluded.
#ccccff
// ...
if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) {
// Handle error
}
// ...
Although it is a compliant solution, this sanitization approach rejects valid directories. Also, because the command interpreter invoked is system dependent, it is difficult to establish that this solution prevents command injections on every platform on which a Java program might run.
## Compliant Solution (Restricted User Choice)
This compliant solution prevents command injection by passing only trusted strings to
Runtime.exec()
. The user has control over which string is used but cannot provide string data directly to
Runtime.exec()
.
#ccccff
// ...
String dir = null;
int number = Integer.parseInt(System.getProperty("dir")); // Only allow integer choices
switch (number) {
case 1:
dir = "data1";
break; // Option 1
case 2:
dir = "data2";
break; // Option 2
default: // Invalid
break;
}
if (dir == null) {
// Handle error
}
## This compliant solution hard codes the directories that may be listed.
This solution can quickly become unmanageable if you have many available directories. A more scalable solution is to read all the permitted directories from a properties file into a
java.util.Properties
object.
## Compliant Solution (AvoidRuntime.exec())
When the task performed by executing a system command can be accomplished by some other means, it is almost always advisable to do so. This compliant solution uses the
File.list()
method to provide a directory listing, eliminating the possibility of command or argument injection attacks.
#ccccff
import java.io.File;
class DirList {
public static void main(String[] args) throws Exception {
File dir = new File(System.getProperty("dir"));
if (!dir.isDirectory()) {
System.out.println("Not a directory");
} else {
for (String file : dir.list()) {
System.out.println(file);
}
}
}
} | ## Risk Assessment
Passing
untrusted
, unsanitized data to the
Runtime.exec()
method can result in command and argument injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS07-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,807 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487807 | 2 | 0 | IDS08-J | Sanitize untrusted data included in a regular expression | Regular expressions (regex) are widely used to match strings of text. For example, the POSIX
grep
utility supports regular expressions for finding patterns in the specified text. For introductory information on regular expressions, see the Java Tutorials [
Java Tutorials
]. The
java.util.regex
package provides the
Pattern
class that encapsulates a compiled representation of a regular expression and the
Matcher
class, which is an engine that uses a
Pattern
to perform matching operations on a
CharSequence
.
Java's powerful regex facilities must be protected from misuse. An attacker may supply a malicious input that modifies the original regular expression in such a way that the regex fails to comply with the program's specification. This attack vector, called a
regex injection
, might affect control flow, cause information leaks, or result in
denial-of-service
(DoS) vulnerabilities.
Certain constructs and properties of Java regular expressions are susceptible to exploitation:
Matching flags:
Untrusted inputs may override matching options that may or may not have been passed to the
Pattern.compile()
method.
Greediness:
An untrusted input may attempt to inject a regex that changes the original regex to match as much of the string as possible, exposing sensitive information.
Grouping:
The programmer can enclose parts of a regular expression in parentheses to perform some common action on the group. An attacker may be able to change the groupings by supplying untrusted input.
Untrusted input should be
sanitized
before use to prevent regex injection. When the user must specify a regex as input, care must be taken to ensure that the original regex cannot be modified without restriction. Whitelisting characters (such as letters and digits) before delivering the user-supplied string to the regex parser is a good input sanitization strategy. A programmer must provide only a very limited subset of regular expression functionality to the user to minimize any chance of misuse.
## Regex Injection Example
Suppose a system log file contains messages output by various system processes. Some processes produce public messages, and some processes produce sensitive messages marked "private." Here is an example log file:
10:47:03 private[423] Successful logout name: usr1 ssn: 111223333
10:47:04 public[48964] Failed to resolve network service
10:47:04 public[1] (public.message[49367]) Exited with exit code: 255
10:47:43 private[423] Successful login name: usr2 ssn: 444556666
10:48:08 public[48964] Backup failed with error: 19
A user wishes to search the log file for interesting messages but must be prevented from seeing the private messages. A program might accomplish this by permitting the user to provide search text that becomes part of the following regex:
(.*? +public\[\d+\] +.*<SEARCHTEXT>.*)
However, if an attacker can substitute any string for
<SEARCHTEXT>
, he can perform a regex injection with the following text:
.*)|(.*
When injected into the regex, the regex becomes
(.*? +public\[\d+\] +.*.*)|(.*.*)
This regex will match any line in the log file, including the private ones. | import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch {
public static void FindLogEntry(String search) {
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
Pattern searchPattern = Pattern.compile(regex);
try (FileInputStream fis = new FileInputStream("log.txt")) {
FileChannel channel = fis.getChannel();
// Get the file's size and map it into memory
long size = channel.size();
final MappedByteBuffer mappedBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, 0, size);
Charset charset = Charset.forName("ISO-8859-15");
final CharsetDecoder decoder = charset.newDecoder();
// Read file into char buffer
CharBuffer log = decoder.decode(mappedBuffer);
Matcher logMatcher = searchPattern.matcher(log);
while (logMatcher.find()) {
String match = logMatcher.group();
if (!match.isEmpty()) {
System.out.println(match);
}
}
} 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());
}
}
return;
}
## Noncompliant Code Example
## This noncompliant code example searches a log file using search terms from an untrusted user:
#FFCCCC
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch {
public static void FindLogEntry(String search) {
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
Pattern searchPattern = Pattern.compile(regex);
try (FileInputStream fis = new FileInputStream("log.txt")) {
FileChannel channel = fis.getChannel();
// Get the file's size and map it into memory
long size = channel.size();
final MappedByteBuffer mappedBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, 0, size);
Charset charset = Charset.forName("ISO-8859-15");
final CharsetDecoder decoder = charset.newDecoder();
// Read file into char buffer
CharBuffer log = decoder.decode(mappedBuffer);
Matcher logMatcher = searchPattern.matcher(log);
while (logMatcher.find()) {
String match = logMatcher.group();
if (!match.isEmpty()) {
System.out.println(match);
}
}
} 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());
}
}
return;
}
This code permits an attacker to perform a regex injection. | public static void FindLogEntry(String search) {
// Sanitize search string
StringBuilder sb = new StringBuilder(search.length());
for (int i = 0; i < search.length(); ++i) {
char ch = search.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
sb.append(ch);
}
}
search = sb.toString();
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
}
public static void FindLogEntry(String search) {
// Sanitize search string
search = Pattern.quote(search);
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
}
## Compliant Solution (Whitelisting)
This compliant solution
sanitizes
the search terms at the beginning of the
FindLogEntry()
, filtering out nonalphanumeric characters (except space and single quote):
#ccccff
public static void FindLogEntry(String search) {
// Sanitize search string
StringBuilder sb = new StringBuilder(search.length());
for (int i = 0; i < search.length(); ++i) {
char ch = search.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
sb.append(ch);
}
}
search = sb.toString();
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
}
This solution
prevents regex injection but
also restricts search terms. For example, a user may no longer search for "
name =
" because nonalphanumeric characters are removed from the search term.
## Compliant Solution (Pattern.quote())
This compliant solution
sanitizes
the search terms by using
Pattern.quote()
to escape any malicious characters in the search string. Unlike the previous compliant solution, a search string using punctuation characters, such as "
name =
" is permitted.
#ccccff
public static void FindLogEntry(String search) {
// Sanitize search string
search = Pattern.quote(search);
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
}
The
Matcher.quoteReplacement()
method can be used to escape strings used when doing regex substitution.
## Compliant Solution
Another method of mitigating this
vulnerability
is to filter out the sensitive information prior to matching. Such a solution would require the filtering to be done every time the log file is periodically refreshed, incurring extra complexity and a performance penalty. Sensitive information may still be exposed if the log format changes but the class is not also refactored to accommodate these changes. | ## Risk Assessment
Failing to
sanitize
untrusted data
included as part of a regular expression can result in the disclosure of sensitive information.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS08-J
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,808 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487808 | 2 | 0 | IDS11-J | Perform any string modifications before validation | It is important that a string not be modified after validation has occurred because doing so may allow an attacker to bypass validation. For example, a program may filter out
the
<script>
tags from HTML input to avoid cross-site scripting (XSS) and other
vulnerabilities
. If exclamation marks (!) are deleted from the input following validation, an attacker may pass the string
"
<scr!ipt>"
so that the validation check fails to detect
the
<script>
tag, but the subsequent removal of the exclamation mark creates a
<script>
tag in the input.
A programmer might decide to exclude many different categories of characters. For example,
The Unicode Standard
[
Unicode 2012
]
defines the following categories of characters, all of which can be matched using an appropriate regular expression:
Abbr
Long
Description
Cc
Control
A C0 or C1 control code
Cf
Format
A format control character
Cs
Surrogate
A surrogate code point
Co
Private_Use
A private-use character
Cn
Unassigned
A reserved unassigned code point or a noncharacter
Other programs may remove or replace any character belonging to a uniquely defined set of characters.
Any string modifications must be performed before the string is validated. | import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
// Deletes noncharacter code points
s = s.replaceAll("[\\p{Cn}]", "");
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a noncharacter code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String sb = filterString(maliciousInput);
// sb = "<script>"
}
}
## Noncompliant Code Example (Noncharacter Code Points)
In some versions of
The Unicode Standard
prior to version 5.2, conformance clause C7 allows the deletion of noncharacter code points. For example, conformance clause C7 from Unicode 5.1 [
Unicode 2007
] states:
C7. When a process purports not to modify the interpretation of a valid coded character sequence, it shall make no change to that coded character sequence other than the possible replacement of character sequences by their canonical-equivalent sequences or the deletion of noncharacter code points.
According to Unicode Technical Report #36, Unicode Security Considerations, Section 3.5, "Deletion of Code Points" [
Davis 2008b
]:
Whenever a character is invisibly deleted (instead of replaced), such as in this older version of C7, it may cause a security problem. The issue is the following: A gateway might be checking for a sensitive sequence of characters, say "delete". If what is passed in is "deXlete", where X is a noncharacter, the gateway lets it through: the sequence "deXlete" may be in and of itself harmless. However, suppose that later on, past the gateway, an internal process invisibly deletes the X. In that case, the sensitive sequence of characters is formed, and can lead to a security breach.
The
filterString()
method in this noncompliant code example normalizes the input string, validates that the input does not contain
a
<script>
tag, and then r
emoves any noncharacter code points from the input string. Because input validation is performed before the removal of
any noncharacter code points
, an attacker can include noncharacter code points in the
<script>
tag to
bypass the validation checks.
#FFcccc
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
// Deletes noncharacter code points
s = s.replaceAll("[\\p{Cn}]", "");
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a noncharacter code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String sb = filterString(maliciousInput);
// sb = "<script>"
}
} | Strange things are happening with the regex below. Our bot inserts a link to the same rec within the code regex.
11/16/2014 rCs : is this still a problem or can we delete this comment?
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Replaces all noncharacter code points with Unicode U+FFFD
s = s.replaceAll("[\\p{Cn}]", "\uFFFD");
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a non-character code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String s = filterString(maliciousInput);
// s = <scr?ipt>
}
## Compliant Solution (Noncharacter Code Points)
This compliant solution replaces the unknown or unrepresentable character with Unicode sequence
\uFFFD
, which is reserved to denote this condition. It also performs this replacement before doing any other sanitization, in particular, checking for
<script>
, to ensure that malicious input cannot bypass filters.
BLOCK
Strange things are happening with the regex below. Our bot inserts a link to the same rec within the code regex.
11/16/2014 rCs : is this still a problem or can we delete this comment?
#ccccff
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Replaces all noncharacter code points with Unicode U+FFFD
s = s.replaceAll("[\\p{Cn}]", "\uFFFD");
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a non-character code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String s = filterString(maliciousInput);
// s = <scr?ipt>
}
According to Unicode Technical Report #36, Unicode Security Considerations [
Davis 2008b
], "
U+FFFD
is usually unproblematic, because it is designed expressly for this kind of purpose. That is, because it doesn't have syntactic meaning in programming languages or structured data, it will typically just cause a failure in parsing. Where the output character set is not Unicode, though, this character may not be available." | ## Risk Assessment
Validating input before removing or modifying characters in the input string can allow malicious input to bypass validation checks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS11-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,645 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487645 | 2 | 0 | IDS14-J | Do not trust the contents of hidden form fields | HTML allows fields in a web form to be visible or hidden. Hidden fields supply values to a web server but do not provide the user with a mechanism to modify their contents. However, there are techniques that attackers can use to modify these contents anyway. A web servlet that uses a
GET
form to obtain parameters can also accept these parameters through a URL. URLs allow a user to specify any parameter names and values in the web request. Consequently, hidden form fields should not be considered any more trustworthy than visible form fields. | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println(hidden);
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
}
## Noncompliant Code Example
The following noncompliant code example demonstrates a servlet that accepts a visible field and a hidden field, and echoes them back to the user. The visible parameter is
sanitized
before being passed to the browser, but the hidden field is not.
#ffcccc
java
public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println(hidden);
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
}
When fed the parameter
param1
, the web page displays the following:
Visible Parameter: param1
Hidden Parameter: a benign value
However, an attacker can easily supply a value to the hidden parameter by encoding it in the URL as follows:
http://localhost:8080/sample/SampleServlet?visible=dummy&hidden=%3Cfont%20color=red%3ESurprise%3C/font%3E
!!!
When this URL is provided to the browser, the browser displays:
Visible Parameter: dummy
Hidden Parameter:
Surprise
!!! | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println( sanitize(hidden)); // Hidden variable sanitized
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
}
## Compliant Solution
## This compliant solution applies the samesanitizationto the hidden parameter as is applied to the visible parameter:
#ccccff
java
public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println( sanitize(hidden)); // Hidden variable sanitized
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
}
Consequently, when the malicious URL is entered into a browser, the servlet produces the following:
Visible Parameter: dummy
Hidden Parameter: <font color=red>Surprise</font>!!! | ## Risk Assessment
Trusting the contents of hidden form fields may lead to all sorts of nasty problems.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS14-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,640 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487640 | 2 | 0 | IDS15-J | Do not allow sensitive information to leak outside a trust boundary | This rule is a stub.
Several guidelines are instances of this one, including
,
, and
.
Noncompliant Code Example
This noncompliant code example shows an example where ...
#FFCCCC
Compliant Solution
In this compliant solution, ...
#CCCCFF
Risk Assessment
Leaking sensitive information outside a trust boundary is not a good idea.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS15-J
Medium
Likely
No
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
Tainting Checker
Trust and security errors (see Chapter 8)
Injection04
Full Implementation
Bibliography
[
Fortify 2014
]
1
,
2
,
3
,
4
. | null | null | null | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,619 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487619 | 2 | 0 | IDS16-J | Prevent XML Injection | The extensible markup language (XML) is designed to help store, structure, and transfer data. Because of its platform independence, flexibility, and relative simplicity, XML has found use in a wide range of applications. However, because of its versatility, XML is vulnerable to a wide spectrum of attacks, including
XML injection
.
A user who has the ability to provide input string data that is incorporated into an XML document can inject XML tags. These tags are interpreted by the XML parser and may cause data to be overridden.
An online store application that allows the user to specify the quantity of an item available for purchase might generate the following XML document:
<item>
<description>Widget</description>
<price>500.0</price>
<quantity>1</quantity>
</item>
An attacker might input the following string instead of a count for the quantity:
1</quantity><price>1.0</price><quantity>1
In this case, the XML resolves to the following:
<item>
<description>Widget</description>
<price>500.0</price>
<quantity>1</quantity><price>1.0</price><quantity>1</quantity>
</item>
An XML parser may interpret the XML in this example such that the second price field overrides the first, changing the price of the item to $1. Alternatively, the attacker may be able to inject special characters, such as comment blocks and
CDATA
delimiters, which corrupt the meaning of the XML. | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStreamBad(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
}
## Noncompliant Code Example
In this noncompliant code example, a client method uses simple string concatenation to build an XML query to send to a server. XML injection is possible because the method performs no input validation.
#FFcccc
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStreamBad(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
} | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException, NumberFormatException {
// Write XML string only if quantity is an unsigned integer (count).
int count = Integer.parseUnsignedInt(quantity);
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + count + "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
}
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="quantity" type="xs:nonNegativeInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString;
xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500.0</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
InputSource xmlStream = new InputSource(new StringReader(xmlString));
// Build a validating SAX parser using our schema
SchemaFactory sf = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
DefaultHandler defHandler = new DefaultHandler() {
public void warning(SAXParseException s) throws SAXParseException {
throw s;
}
public void error(SAXParseException s) throws SAXParseException {
throw s;
}
public void fatalError(SAXParseException s) throws SAXParseException {
throw s;
}
};
StreamSource ss = new StreamSource(new File("schema.xsd"));
try {
Schema schema = sf.newSchema(ss);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser saxParser = spf.newSAXParser();
// To set the custom entity resolver,
// an XML reader needs to be created
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
saxParser.parse(xmlStream, defHandler);
} catch (ParserConfigurationException x) {
throw new IOException("Unable to validate XML", x);
} catch (SAXException x) {
throw new IOException("Invalid quantity", x);
}
// Our XML is valid, proceed
outStream.write(xmlString.getBytes());
outStream.flush();
}
}
## Compliant Solution (Input Validation)
Depending on the specific data and command interpreter or parser to which data is being sent, appropriate methods must be used to
sanitize
untrusted user input. This compliant solution validates that
quantity
is an unsigned integer:
#ccccff
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException, NumberFormatException {
// Write XML string only if quantity is an unsigned integer (count).
int count = Integer.parseUnsignedInt(quantity);
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + count + "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
}
## Compliant Solution (XML Schema)
A more general mechanism for checking XML for attempted injection is to validate it using a Document Type Definition (DTD) or schema. The schema must be rigidly defined to prevent injections from being mistaken for valid XML. Here is a suitable schema for validating our XML snippet:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="quantity" type="xs:nonNegativeInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The schema is available as the file
schema.xsd
. This compliant solution employs this schema to prevent XML injection from succeeding. It also relies on the
CustomResolver
class defined in
IDS17-J. Prevent XML External Entity Attacks
to prevent XML external entity (XXE) attacks.
#ccccff
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString;
xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500.0</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
InputSource xmlStream = new InputSource(new StringReader(xmlString));
// Build a validating SAX parser using our schema
SchemaFactory sf = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
DefaultHandler defHandler = new DefaultHandler() {
public void warning(SAXParseException s) throws SAXParseException {
throw s;
}
public void error(SAXParseException s) throws SAXParseException {
throw s;
}
public void fatalError(SAXParseException s) throws SAXParseException {
throw s;
}
};
StreamSource ss = new StreamSource(new File("schema.xsd"));
try {
Schema schema = sf.newSchema(ss);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser saxParser = spf.newSAXParser();
// To set the custom entity resolver,
// an XML reader needs to be created
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
saxParser.parse(xmlStream, defHandler);
} catch (ParserConfigurationException x) {
throw new IOException("Unable to validate XML", x);
} catch (SAXException x) {
throw new IOException("Invalid quantity", x);
}
// Our XML is valid, proceed
outStream.write(xmlString.getBytes());
outStream.flush();
}
}
Using a schema or DTD to validate XML is convenient when receiving XML that may have been loaded with unsanitized input. If such an XML string has not yet been built,
sanitizing
input before constructing XML yields better performance. | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS16-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,620 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487620 | 2 | 0 | IDS17-J | Prevent XML External Entity Attacks | Entity declarations
define shortcuts to commonly used text or special characters. An entity declaration may define either an
internal
or
external entity
. For internal entities, the content of the entity is given in the declaration. For external entities, the content is specified by a Uniform Resource Identifier (URI).
Entities may be either
parsed
or
unparsed
. The contents of a parsed entity are called its
replacement text
. An unparsed entity is a resource whose contents may or may not be text, and if text, may be other than XML. Parsed entities are invoked by name using an
entity reference
; unparsed entities are invoked by name.
According to XML W3C Recommendation, section 4.4.3, "Included If Validating" [
W3C 2008
]:
When an XML processor recognizes a reference to a parsed entity, to validate the document, the processor MUST include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor MAY, but need not, include the entity's replacement text.
Because inclusion of replacement text from an external entity is optional, not all XML processors are vulnerable to external entity attacks during validation.
An
XML external entity (XXE)
attack occurs when XML input containing a reference to an external entity is processed by an improperly configured XML parser. An attacker might use an XXE attack to gain access to sensitive information by manipulating the URI of the entity to refer to files on the local file system containing
sensitive data
such as passwords and private user data. An attacker might launch a
denial-of-service attack
, for example, by specifying
/dev/random
or
/dev/tty
as input URIs, which can crash or indefinitely block a program. | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inStream, defaultHandler);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
}
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo>
## Noncompliant Code Example
This noncompliant code example attempts to parse the file
evil.xml
, report any errors, and exit. However, a SAX (Simple API for XML) or a DOM (Document Object Model) parser will attempt to access the URI specified by the
SYSTEM
attribute, which means it will attempt to read the contents of the local
/dev/tty
file. On POSIX systems, reading this file causes the program to block until input data is supplied to the machine's console. Consequently, an attacker can use this malicious XML file to cause the program to hang.
#FFcccc
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inStream, defaultHandler);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
}
This program is subject to a remote XXE attack if the
evil.xml
file contains the following:
#ffcccc
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo> | import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class CustomResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// Check for known good entities
String entityPath = "file:/Users/onlinestore/good.xml";
if (systemId.equals(entityPath)) {
System.out.println("Resolving entity: " + publicId + " " + systemId);
return new InputSource(entityPath);
} else {
// Disallow unknown entities by returning a blank path
return new InputSource();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler) throws ParserConfigurationException,
SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// Create an XML reader to set the entity resolver.
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
reader.setContentHandler(defaultHandler);
InputSource is = new InputSource(inStream);
reader.parse(is);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
}
## Compliant Solution (EntityResolver)
This compliant solution defines a
CustomResolver
class that implements the interface
org.xml.sax.EntityResolver
. This interface enables a SAX application to customize handling of external entities. The customized handler uses a simple whitelist for external entities. The
resolveEntity()
method returns an empty
InputSource
when an input fails to resolve to any of the specified, safe entity source paths.
#ccccff
import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class CustomResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// Check for known good entities
String entityPath = "file:/Users/onlinestore/good.xml";
if (systemId.equals(entityPath)) {
System.out.println("Resolving entity: " + publicId + " " + systemId);
return new InputSource(entityPath);
} else {
// Disallow unknown entities by returning a blank path
return new InputSource();
}
}
}
The
setEntityResolver()
method registers the instance with the corresponding SAX driver. When parsing malicious input, the empty
InputSource
returned by the custom resolver causes a
java.net
.MalformedURLException
to be thrown. Note that you must create an
XMLReader
object on which to set the custom entity resolver.
#ccccff
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler) throws ParserConfigurationException,
SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// Create an XML reader to set the entity resolver.
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
reader.setContentHandler(defaultHandler);
InputSource is = new InputSource(inStream);
reader.parse(is);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
} | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS17-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,459 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487459 | 3 | 0 | IDS50-J | Use conservative file naming conventions | File and path names containing particular characters or character sequences can cause problems when used in the construction of a file or path name:
Leading dashes: Leading dashes can cause problems when programs are called with the file name as a parameter because the first character or characters of the file name might be interpreted as an option switch.
Control characters, such as newlines, carriage returns, and escape: Control characters in a file name can cause unexpected results from shell scripts and in logging.
Spaces: Spaces can cause problems with scripts and when double quotes are not used to surround the file name.
Invalid character encodings: Character encodings can make it difficult to perform proper validation of file and path names. (See
).
Namespace prefixing and conventions
: Namespace prefixes can cause unexpected and potentially insecure behavior when included in a path name.
Command interpreters, scripts, and parsers: Characters that have special meaning when processed by a command interpreter, shell, or parser.
As a result of the influence of MS-DOS, 8.3 file names of the form
xxxxxxxx.xxx
, where
x
denotes an alphanumeric character, are generally supported by modern systems. On some platforms, file names are case sensitive, and on other platforms, they are case insensitive. VU#439395 is an example of a vulnerability resulting from a failure to deal appropriately with case sensitivity issues [
VU#439395
]. Developers should generate file and path names using a safe subset of ASCII characters and, for security critical applications, only accept names that use these characters.
The degree to restrict a filename depends on the source of the filename. If the source is untrusted (e.g., a Web server receiving a file upload), conservatively restrict filenames. However, if the source is trusted (e.g., command-line arguments supplied by the user the program is running as), do not restrict filenames. For filenames restricted by the OS, let the OS block the name and catch the exception from trying to create the file). | File f = new File("A\uD8AB");
OutputStream out = new FileOutputStream(f);
A?
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
File f = new File(args[0]);
OutputStream out = new FileOutputStream(f);
// ...
}
## Noncompliant Code Example
## In the following noncompliant code example, unsafe characters are used as part of a file name.
#ffcccc
File f = new File("A\uD8AB");
OutputStream out = new FileOutputStream(f);
A platform is free to define its own mapping of the unsafe characters. For example, when tested on an Ubuntu Linux distribution, this noncompliant code example resulted in the following file name:
A?
## Noncompliant Code Example
## This noncompliant code example creates a file with input from the user without sanitizing the input.
#FFCCCC
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
File f = new File(args[0]);
OutputStream out = new FileOutputStream(f);
// ...
}
No checks are performed on the file name to prevent troublesome characters. If an attacker knew this code was in a program used to create or rename files that would later be used in a script or automated process of some sort, the attacker could choose particular characters in the output file name to confuse the later process for malicious purposes. | File f = new File("name.ext");
OutputStream out = new FileOutputStream(f);
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
String filename = args[0];
Pattern pattern = Pattern.compile("[^A-Za-z0-9._]");
Matcher matcher = pattern.matcher(filename);
if (matcher.find()) {
// File name contains bad chars; handle error
}
File f = new File(filename);
OutputStream out = new FileOutputStream(f);
// ...
}
## Compliant Solution
Use a descriptive file name, containing only the subset of ASCII previously described.
#ccccff
File f = new File("name.ext");
OutputStream out = new FileOutputStream(f);
## Compliant Solution
This compliant solution uses a whitelist to reject file names containing unsafe characters. Further input validation may be necessary, for example, to ensure that
a file or directory name does not end with a period.
#ccccFF
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
String filename = args[0];
Pattern pattern = Pattern.compile("[^A-Za-z0-9._]");
Matcher matcher = pattern.matcher(filename);
if (matcher.find()) {
// File name contains bad chars; handle error
}
File f = new File(filename);
OutputStream out = new FileOutputStream(f);
// ...
} | ## Risk Assessment
Failing to use only a safe subset of ASCII can result in misinterpreted data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS50-J
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,918 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487918 | 3 | 0 | IDS51-J | Properly encode or escape output | Proper input sanitization can prevent insertion of malicious data into a subsystem such as a database. However, different subsystems require different types of sanitization. Fortunately, it is usually obvious which subsystems will eventually receive which inputs, and consequently what type of sanitization is required.
Several subsystems exist for the purpose of outputting data. An HTML renderer is one common subsystem for displaying output. Data sent to an output subsystem may appear to originate from a trusted source. However, it is dangerous to assume that output sanitization is unnecessary because such data may indirectly originate from an
un
trusted source and may include malicious content. Failure to properly sanitize data passed to an output subsystem can allow several types of attacks. For example, HTML renderers are prone to HTML injection and cross-site scripting (XSS) attacks [
OWASP 2011
]. Output sanitization to prevent such attacks is as vital as input sanitization.
As with input validation, data should be normalized before sanitizing it for malicious characters. Properly encode all output characters other than those known to be safe to avoid vulnerabilities caused by data that bypasses validation. See
for more information. | @RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(
HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
try {
UserInfo userDetails = getUserInfo();
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
List<Notification> notificationList =
NotificationService.getNotificationsForUserId(userDetails.getPersonId());
for (Notification notification: notificationList) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("id", notification.getId());
map.put("message", notification.getMessage());
list.add(map);
}
mv.addObject("Notifications", list);
}
catch(Throwable t) {
// Log to file and handle
}
return mv;
}
String buildUrl(String q) {
String url = "https://example.com?query=" + q;
return url;
}
## Noncompliant Code Example
This noncompliant code example uses the model-view-controller (MVC) concept of the Java EE–based Spring Framework to display data to the user without encoding or escaping it. Because the data is sent to a web browser, the code is subject to both HTML injection and XSS attacks.
#FFCCCC
@RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(
HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
try {
UserInfo userDetails = getUserInfo();
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
List<Notification> notificationList =
NotificationService.getNotificationsForUserId(userDetails.getPersonId());
for (Notification notification: notificationList) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("id", notification.getId());
map.put("message", notification.getMessage());
list.add(map);
}
mv.addObject("Notifications", list);
}
catch(Throwable t) {
// Log to file and handle
}
return mv;
}
## Noncompliant Code Example
This noncompliant code example takes a user input query string and build a URL. Because the URL is not properly encoded, the URL returned may not be valid if it contains non-URL-safe characters, as per
RFC 1738.
#FFCCCC
String buildUrl(String q) {
String url = "https://example.com?query=" + q;
return url;
}
For example, if the user supplies the input string "
<#catgifs>
", the
url
returned is
"https://example.com?query=<#catgifs>"
which is not a valid URL. | public class ValidateOutput {
// Allows only alphanumeric characters and spaces
private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9\\s]{0,20}$");
// Validates and encodes the input field based on a whitelist
public String validate(String name, String input) throws ValidationException {
String canonical = normalize(input);
if (!pattern.matcher(canonical).matches()) {
throw new ValidationException("Improper format in " + name + " field");
}
// Performs output encoding for nonvalid characters
canonical = HTMLEntityEncode(canonical);
return canonical;
}
// Normalizes to known instances
private String normalize(String input) {
String canonical =
java.text.Normalizer.normalize(input, Normalizer.Form.NFKC);
return canonical;
}
// Encodes nonvalid data
private static String HTMLEntityEncode(String input) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
sb.append(ch);
} else {
sb.append("&#" + (int)ch + ";");
}
}
return sb.toString();
}
}
// ...
@RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(HttpServletRequest request, HttpServletResponse response) {
ValidateOutput vo = new ValidateOutput();
ModelAndView mv = new ModelAndView();
try {
UserInfo userDetails = getUserInfo();
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
List<Notification> notificationList =
NotificationService.getNotificationsForUserId(userDetails.getPersonId());
for (Notification notification: notificationList) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", vo.validate("id", notification.getId()));
map.put("message", vo.validate("message", notification.getMessage()));
list.add(map);
}
mv.addObject("Notifications", list);
}
catch(Throwable t) {
// Log to file and handle
}
return mv;
}
String buildEncodedUrl(String q) {
String encodedUrl = "https://example.com?query=" + Base64.getUrlEncoder().encodeToString(q.getBytes());
return encodedUrl;
}
## Compliant Solution
This compliant solution defines a
ValidateOutput
class that normalizes the output to a known character set, performs output sanitization using a whitelist, and encodes any unspecified data values to enforce a double-checking mechanism. Note that the required whitelisting patterns can vary according to the specific needs of different fields [
OWASP 2013
].
#ccccff
public class ValidateOutput {
// Allows only alphanumeric characters and spaces
private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9\\s]{0,20}$");
// Validates and encodes the input field based on a whitelist
public String validate(String name, String input) throws ValidationException {
String canonical = normalize(input);
if (!pattern.matcher(canonical).matches()) {
throw new ValidationException("Improper format in " + name + " field");
}
// Performs output encoding for nonvalid characters
canonical = HTMLEntityEncode(canonical);
return canonical;
}
// Normalizes to known instances
private String normalize(String input) {
String canonical =
java.text.Normalizer.normalize(input, Normalizer.Form.NFKC);
return canonical;
}
// Encodes nonvalid data
private static String HTMLEntityEncode(String input) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
sb.append(ch);
} else {
sb.append("&#" + (int)ch + ";");
}
}
return sb.toString();
}
}
// ...
@RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(HttpServletRequest request, HttpServletResponse response) {
ValidateOutput vo = new ValidateOutput();
ModelAndView mv = new ModelAndView();
try {
UserInfo userDetails = getUserInfo();
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
List<Notification> notificationList =
NotificationService.getNotificationsForUserId(userDetails.getPersonId());
for (Notification notification: notificationList) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", vo.validate("id", notification.getId()));
map.put("message", vo.validate("message", notification.getMessage()));
list.add(map);
}
mv.addObject("Notifications", list);
}
catch(Throwable t) {
// Log to file and handle
}
return mv;
}
Output encoding and escaping is mandatory when accepting dangerous characters such as double quotes and angle braces. Even when input is whitelisted to disallow such characters, output escaping is recommended because it provides a second level of defense. Note that the exact escape sequence can vary depending on where the output is embedded. For example, untrusted output may occur in an HTML value attribute, CSS, URL, or script; output encoding routine will be different in each case. It is also impossible to securely use untrusted data in some contexts. Consult the OWASP
XSS (Cross-Site Scripting) Prevention Cheat Sheet
for more information on preventing XSS attacks.
## Compliant Solution (Java 8)
Use
java.util.Base64
to encode and decode data when transferring binary data over mediums that only allow printable characters like URLs, filenames, and MIME.
#ccccff
String buildEncodedUrl(String q) {
String encodedUrl = "https://example.com?query=" + Base64.getUrlEncoder().encodeToString(q.getBytes());
return encodedUrl;
}
If the user supplies the input string "<#catgifs>", the
url
returned is
"
https://example.com?query=%3C%23catgifs%3E
"
which is a valid URL. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,444 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487444 | 3 | 0 | IDS52-J | Prevent code injection | Code injection can occur when untrusted input is injected into dynamically constructed code. One obvious source of potential vulnerabilities is the use of JavaScript from Java code. The
javax.script
package consists of interfaces and classes that define Java scripting engines and a framework for the use of those interfaces and classes in Java code. Misuse of the
javax.script
API permits an attacker to execute arbitrary code on the target system.
This guideline is a specific instance of
. | private static void evalScript(String firstName) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("print('"+ firstName + "')");
}
dummy\');
var bw = new JavaImporter(java.io.BufferedWriter);
var fw = new JavaImporter(java.io.FileWriter);
with(fw) with(bw) {
bwr = new BufferedWriter(new FileWriter(\"config.cfg\"));
bwr.write(\"some text\"); bwr.close();
}
// ;
## Noncompliant Code Example
This noncompliant code example incorporates untrusted user input into a JavaScript statement that is responsible for printing the input:
#FFCCCC
private static void evalScript(String firstName) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("print('"+ firstName + "')");
}
An attacker can enter a specially crafted argument in an attempt to inject malicious JavaScript. This example shows a malicious string that contains JavaScript code that can create a file or overwrite an existing file on a vulnerable system.
ffffcc
javascript
dummy\');
var bw = new JavaImporter(java.io.BufferedWriter);
var fw = new JavaImporter(java.io.FileWriter);
with(fw) with(bw) {
bwr = new BufferedWriter(new FileWriter(\"config.cfg\"));
bwr.write(\"some text\"); bwr.close();
}
// ;
The script in this example prints
"
dummy
"
and then writes
"
some text"
to a configuration file called
config.cfg
. An actual exploit can execute arbitrary code. | private static void evalScript(String firstName) throws ScriptException {
// Allow only alphanumeric and underscore chars in firstName
// (modify if firstName may also include special characters)
if (!firstName.matches("[\\w]*")) {
// String does not match whitelisted characters
throw new IllegalArgumentException();
}
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("print('"+ firstName + "')");
}
class ACC {
private static class RestrictedAccessControlContext {
private static final AccessControlContext INSTANCE;
static {
INSTANCE = new AccessControlContext(
new ProtectionDomain[] {
new ProtectionDomain(null, null) // No permissions
});
}
}
private static void evalScript(final String firstName)
throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("javascript");
// Restrict permission using the two-argument form of doPrivileged()
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
public Object run() throws ScriptException {
engine.eval("print('" + firstName + "')");
return null;
}
},
// From nested class
RestrictedAccessControlContext.INSTANCE);
} catch (PrivilegedActionException pae) {
// Handle error
}
}
}
## Compliant Solution (Whitelisting)
The best defense against code injection vulnerabilities is to prevent the inclusion of executable user input in code. User input used in dynamic code must be sanitized, for example, to ensure that it contains only valid, whitelisted characters. Sanitization is best performed immediately after the data has been input, using methods from the data abstraction used to store and process the data. Refer to
IDS00-J. Sanitize untrusted data passed across a trust boundary
for more details. If special characters must be permitted in the name, they must be normalized before comparison with their equivalent forms for the purpose of input validation. This compliant solution uses whitelisting to prevent unsanitized input from being interpreted by the scripting engine.
#ccccff
private static void evalScript(String firstName) throws ScriptException {
// Allow only alphanumeric and underscore chars in firstName
// (modify if firstName may also include special characters)
if (!firstName.matches("[\\w]*")) {
// String does not match whitelisted characters
throw new IllegalArgumentException();
}
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("print('"+ firstName + "')");
}
## Compliant Solution (Secure Sandbox)
An alternative approach is to create a secure sandbox using a security manager (see
.) The application should prevent the script from executing arbitrary commands, such as querying the local file system. The two-argument form of
doPrivileged()
can be used to lower privileges when the application must operate with higher privileges, but the scripting engine must not. The
RestrictedAccessControlContext
reduces the permissions granted in the default policy file to those of the newly created protection domain. The effective permissions are the intersection of the permissions of the newly created protection domain and the systemwide security policy. Refer to
for more details on the two-argument form of
doPrivileged()
.
## This compliant solution illustrates the use of anAccessControlContextin the two-argument form ofdoPrivileged().
#ccccff
class ACC {
private static class RestrictedAccessControlContext {
private static final AccessControlContext INSTANCE;
static {
INSTANCE = new AccessControlContext(
new ProtectionDomain[] {
new ProtectionDomain(null, null) // No permissions
});
}
}
private static void evalScript(final String firstName)
throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("javascript");
// Restrict permission using the two-argument form of doPrivileged()
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
public Object run() throws ScriptException {
engine.eval("print('" + firstName + "')");
return null;
}
},
// From nested class
RestrictedAccessControlContext.INSTANCE);
} catch (PrivilegedActionException pae) {
// Handle error
}
}
}
This approach can be combined with whitelisting for additional security. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,536 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487536 | 3 | 0 | IDS53-J | Prevent XPath Injection | Extensible Markup Language (XML) can be used for data storage in a manner similar to a relational database. Data is frequently retrieved from such an XML document using XPaths.
XPath injection
can occur when data supplied to an XPath retrieval routine to retrieve data from an XML document is used without proper sanitization. This attack is similar to SQL injection or XML injection (see
IDS00-J. Sanitize untrusted data passed across a trust boundary
). An attacker can enter valid SQL or XML constructs in the data fields of the query in use. In typical attacks, the conditional field of the query resolves to a tautology or otherwise gives the attacker access to privileged information.
This guideline is a specific example of the broadly scoped
.
## XML Path Injection Example
Consider the following XML schema:
<users>
<user>
<username>Utah</username>
<password>e90205372a3b89e2</password>
</user>
<user>
<username>Bohdi</username>
<password>6c16b22029df4ec6</password>
</user>
<user>
<username>Busey</username>
<password>ad39b3c2a4dabc98</password>
</user>
</users>
The passwords are hashed in compliance with
. MD5 hashes are shown here for illustrative purposes; in practice, you should use a safer algorithm such as SHA-256.
Untrusted code may attempt to retrieve user details from this file with an XPath statement constructed dynamically from user input.
//users/user[username/text()='&LOGIN&' and password/text()='&PASSWORD&' ]
If an attacker knows that
Utah
is a valid user name, he or she can specify an input such as
Utah' or '1'='1
This yields the following query string.
//users/user[username/text()='Utah' or '1'='1' and password/text()='xxxx']
Because the
'1'='1'
is automatically true, the password is never validated. Consequently, the attacker is inappropriately authenticated as user
Utah
without knowing
Utah
's
password. | private boolean doLogin(String userName, char[] password)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("users.xml");
String pwd = hashPassword( password);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//users/user[username/text()='" +
userName + "' and password/text()='" + pwd + "' ]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
// Print first names to the console
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0);
System.out.println( "Authenticated: " + node.getNodeValue());
}
return (nodes.getLength() >= 1);
}
## Noncompliant Code Example
This noncompliant code example reads a user name and password from the user and uses them to construct the query string. The password is passed as a
char
array and then hashed.
This example is vulnerable to the attack described earlier. If the attack string described earlier is passed to
evaluate()
, the method call returns the corresponding node in the XML file, causing the
doLogin()
method to return
true
and bypass any authorization.
#FFcccc
private boolean doLogin(String userName, char[] password)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("users.xml");
String pwd = hashPassword( password);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//users/user[username/text()='" +
userName + "' and password/text()='" + pwd + "' ]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
// Print first names to the console
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0);
System.out.println( "Authenticated: " + node.getNodeValue());
}
return (nodes.getLength() >= 1);
} | declare variable $userName as xs:string external;
declare variable $password as xs:string external;
//users/user[@userName=$userName and @password=$password]
private boolean doLogin(String userName, String pwd)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("users.xml");
XQuery xquery = new XQueryFactory().createXQuery(new File("login.xq"));
Map queryVars = new HashMap();
queryVars.put("userName", userName);
queryVars.put("password", pwd);
NodeList nodes = xquery.execute(doc, null, queryVars).toNodes();
// Print first names to the console
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0);
System.out.println(node.getNodeValue());
}
return (nodes.getLength() >= 1);
}
## Compliant Solution (XQuery)
XPath injection can be prevented by adopting defenses similar to those used to prevent SQL injection:
Treat all user input as untrusted, and perform appropriate sanitization.
When sanitizing user input, verify the correctness of the data type, length, format, and content. For example, use a regular expression that checks for XML tags and special characters in user input. This practice corresponds to input sanitization. See
for additional details.
In a client-server application, perform validation at both the client and the server sides.
Extensively test applications that supply, propagate, or accept user input.
An effective technique for preventing the related issue of SQL injection is parameterization. Parameterization ensures that user-specified data is passed to an API as a parameter such that the data is never interpreted as executable content. Unfortunately, Java SE currently lacks an analogous interface for XPath queries. However, an XPath analog to SQL parameterization can be emulated by using an interface such as XQuery that supports specifying a query statement in a separate file supplied at runtime.
Input File: login.qry
declare variable $userName as xs:string external;
declare variable $password as xs:string external;
//users/user[@userName=$userName and @password=$password]
This compliant solution uses a query specified in a text file by reading the file in the required format and then inserting values for the user name and password in a
Map
. The
XQuery
library constructs the XML query from these inputs.
#ccccff
private boolean doLogin(String userName, String pwd)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("users.xml");
XQuery xquery = new XQueryFactory().createXQuery(new File("login.xq"));
Map queryVars = new HashMap();
queryVars.put("userName", userName);
queryVars.put("password", pwd);
NodeList nodes = xquery.execute(doc, null, queryVars).toNodes();
// Print first names to the console
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0);
System.out.println(node.getNodeValue());
}
return (nodes.getLength() >= 1);
}
Using this method, the data specified in the
userName
and
password
fields cannot be interpreted as executable content at runtime. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,534 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487534 | 3 | 0 | IDS54-J | Prevent LDAP injection | The Lightweight Directory Access Protocol (LDAP) allows an application to remotely perform operations such as searching and modifying records in directories. LDAP injection results from inadequate input sanitization and validation and allows malicious users to glean restricted information using the directory service.
A whitelist can be used to restrict input to a list of valid characters. Characters and character sequences that must be excluded from whitelists—including Java Naming and Directory Interface (JNDI) metacharacters and LDAP special characters—are listed in the following table.
Characters and Sequences to Exclude from Whitelists
Character
Name
'
and
"
Single and double quote
/
and
\
Forward slash and backslash
\\
Double slashes*
space
Space character at beginning or end of string
#
Hash character at the beginning of the string
<
and
>
Angle brackets
,
and
;
Comma and semicolon
+
and
*
Addition and multiplication operators
(
and
)
Round braces
\u0000
Unicode
NULL
character
* This is a character sequence.
## LDAP Injection Example
Consider an LDAP Data Interchange Format (LDIF) file that contains records in the following format:
dn: dc=example,dc=com
objectclass: dcobject
objectClass: organization
o: Some Name
dc: example
dn: ou=People,dc=example,dc=com
ou: People
objectClass: dcobject
objectClass: organizationalUnit
dc: example
dn: cn=Manager,ou=People,dc=example,dc=com
cn: Manager
sn: John Watson
# Several objectClass definitions here (omitted)
userPassword: secret1
mail: john@holmesassociates.com
dn: cn=Senior Manager,ou=People,dc=example,dc=com
cn: Senior Manager
sn: Sherlock Holmes
# Several objectClass definitions here (omitted)
userPassword: secret2
mail: sherlock@holmesassociates.com
A search for a valid user name and password often takes the form
(&(sn=<USERSN>)(userPassword=<USERPASSWORD>))
However, an attacker could bypass authentication by using
S*
for the
USERSN
field and
*
for the
USERPASSWORD
field. Such input would yield every record whose
USERSN
field began with
S
.
An authentication routine that permitted LDAP injection would allow unauthorized users to log in. Likewise, a search routine would allow an attacker to discover part or all of the data in the directory. | // String userSN = "S*"; // Invalid
// String userPassword = "*"; // Invalid
public class LDAPInjection {
private void searchRecord(String userSN, String userPassword) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
try {
DirContext dctx = new InitialDirContext(env);
SearchControls sc = new SearchControls();
String[] attributeFilter = {"cn", "mail"};
sc.setReturningAttributes(attributeFilter);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
// The following resolves to (&(sn=S*)(userPassword=*))
String filter = "(&(sn=" + userSN + ")(userPassword=" + userPassword + "))";
NamingEnumeration<?> results = dctx.search(base, filter, sc);
while (results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
Attributes attrs = (Attributes) sr.getAttributes();
Attribute attr = (Attribute) attrs.get("cn");
System.out.println(attr);
attr = (Attribute) attrs.get("mail");
System.out.println(attr);
}
dctx.close();
} catch (NamingException e) {
// Forward to handler
}
}
}
## Noncompliant Code Example
This noncompliant code example allows a caller of the method
searchRecord()
to search for a record in the directory using the LDAP protocol. The string
filter
is used to filter the result set for those entries that match a user name and password supplied by the caller.
#FFCCCC
// String userSN = "S*"; // Invalid
// String userPassword = "*"; // Invalid
public class LDAPInjection {
private void searchRecord(String userSN, String userPassword) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
try {
DirContext dctx = new InitialDirContext(env);
SearchControls sc = new SearchControls();
String[] attributeFilter = {"cn", "mail"};
sc.setReturningAttributes(attributeFilter);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
// The following resolves to (&(sn=S*)(userPassword=*))
String filter = "(&(sn=" + userSN + ")(userPassword=" + userPassword + "))";
NamingEnumeration<?> results = dctx.search(base, filter, sc);
while (results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
Attributes attrs = (Attributes) sr.getAttributes();
Attribute attr = (Attribute) attrs.get("cn");
System.out.println(attr);
attr = (Attribute) attrs.get("mail");
System.out.println(attr);
}
dctx.close();
} catch (NamingException e) {
// Forward to handler
}
}
}
When a malicious user enters specially crafted input, as outlined previously, this elementary authentication scheme fails to confine the output of the search query to the information for which the user has access privileges. | // String userSN = "Sherlock Holmes"; // Valid
// String userPassword = "secret2"; // Valid
// ... beginning of LDAPInjection.searchRecord()...
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
if (!userSN.matches("[\\w\\s]*") || !userPassword.matches("[\\w]*")) {
throw new IllegalArgumentException("Invalid input");
}
String filter = "(&(sn = " + userSN + ")(userPassword=" + userPassword + "))";
// ... remainder of LDAPInjection.searchRecord()...
## Compliant Solution
This compliant solution uses a whitelist to sanitize user input so that the
filter
string contains only valid characters. In this code,
userSN
may contain only letters and spaces, whereas a password may contain only alphanumeric characters.
#ccccff
// String userSN = "Sherlock Holmes"; // Valid
// String userPassword = "secret2"; // Valid
// ... beginning of LDAPInjection.searchRecord()...
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
if (!userSN.matches("[\\w\\s]*") || !userPassword.matches("[\\w]*")) {
throw new IllegalArgumentException("Invalid input");
}
String filter = "(&(sn = " + userSN + ")(userPassword=" + userPassword + "))";
// ... remainder of LDAPInjection.searchRecord()...
When a database field such as a password must include special characters, it is critical to ensure that the authentic data is stored in sanitized form in the database and also that any user input is normalized before the validation or comparison takes place. Using characters that have special meanings in JNDI and LDAP in the absence of a comprehensive normalization and whitelisting-based routine is discouraged. Special characters must be transformed to sanitized, safe values before they are added to the whitelist expression against which input will be validated. Likewise, normalization of user input should occur before the validation step. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,392 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487392 | 3 | 0 | IDS55-J | Understand how escape characters are interpreted when strings are loaded | Many classes allow inclusion of escape sequences in character and string literals; examples include
java.util.regex.Pattern
as well as classes that support XML- and SQL-based actions by passing string arguments to methods. According to the
Java Language Specification
(JLS),
§3.10.6, "Escape Sequences for Character and String Literals"
[
JLS 2013
],
The character and string escape sequences allow for the representation of some nongraphic characters as well as the single quote, double quote, and backslash characters in character literals (§3.10.4) and string literals (§3.10.5).
Correct use of escape sequences in string literals requires understanding how the escape sequences are interpreted by the Java compiler as well as how they are interpreted by any subsequent processor, such as a SQL engine. SQL statements may require escape sequences (for example, sequences containing
\t
,
\n
,
\r
) in certain cases, such as when storing raw text in a database. When representing SQL statements in Java string literals, each escape sequence must be preceded by an extra backslash for correct interpretation.
As another example, consider the
Pattern
class used in performing regular expression-related tasks. A string literal used for pattern matching is compiled into an instance of the
Pattern
type. When the pattern to be matched contains a sequence of characters identical to one of the Java escape sequences—
"\"
and
"n"
, for example—the Java compiler treats that portion of the string as a Java escape sequence and transforms the sequence into an actual newline character. To insert the newline escape sequence, rather than a literal newline character, the programmer must precede the
"\n"
sequence with an additional backslash to prevent the Java compiler from replacing it with a newline character. The string constructed from the resulting sequence,
\\n
consequently contains the correct two-character sequence
\n
and correctly denotes the escape sequence for newline in the pattern.
In general, for a particular escape character of the form
\X
, the equivalent Java representation is
\\X | public class Splitter {
// Interpreted as backspace
// Fails to split on word boundaries
private final String WORDS = "\b";
public String[] splitWords(String input) {
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
public class Splitter {
private final String WORDS;
public Splitter() throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("splitter.properties"));
WORDS = properties.getProperty("WORDS");
}
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
WORDS=\b
## Noncompliant Code Example (String Literal)
This noncompliant code example defines a method,
splitWords()
, that finds matches between the string literal (
WORDS
) and the input sequence. It is expected that
WORDS
would hold the escape sequence for matching a word boundary. However, the Java compiler treats the
"\b"
literal as a Java escape sequence, and the string
WORDS
silently compiles to a regular expression that checks for a single backspace character.
#FFCCCC
public class Splitter {
// Interpreted as backspace
// Fails to split on word boundaries
private final String WORDS = "\b";
public String[] splitWords(String input) {
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
## Noncompliant Code Example (String Property)
This noncompliant code example uses the same method,
splitWords()
. This time the
WORDS
string is loaded from an external properties file.
public class Splitter {
private final String WORDS;
public Splitter() throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("splitter.properties"));
WORDS = properties.getProperty("WORDS");
}
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
In the properties file, the
WORD
property is once again incorrectly specified as
\b
.
#FFCCCC
WORDS=\b
This is read by the
Properties.load()
method as a single character
b
, which causes the
split()
method to split strings along the letter
b
. Although the string is interpreted differently than if it were a string literal, as in the previous noncompliant code example, the interpretation is incorrect. | public class Splitter {
// Interpreted as two chars, '\' and 'b'
// Correctly splits on word boundaries
private final String WORDS = "\\b";
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
WORDS=\\b
## Compliant Solution (String Literal)
This compliant solution shows the correctly escaped value of the string literal
WORDS
that results in a regular expression designed to split on word boundaries:
#ccccff
public class Splitter {
// Interpreted as two chars, '\' and 'b'
// Correctly splits on word boundaries
private final String WORDS = "\\b";
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
## Compliant Solution (String Property)
## This compliant solution shows the correctly escaped value of theWORDSproperty:
#ccccff
WORDS=\\b | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,635 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487635 | 3 | 0 | IDS56-J | Prevent arbitrary file upload | Java applications, including web applications, that accept file uploads must ensure that an attacker cannot upload or transfer malicious files. If a restricted file containing code is executed by the target system, it can compromise application-layer defenses. For example, an application that permits HTML files to be uploaded could allow malicious code to be executed—an attacker can submit a valid HTML file with a cross-site scripting (XSS) payload that will execute in the absence of an output-escaping routine. For this reason, many applications restrict the type of files that can be uploaded.
It may also be possible to upload files with dangerous extensions such as .exe and .sh that could cause arbitrary code execution on server-side applications. An application that restricts only the Content-Type field in the HTTP header could be vulnerable to such an attack.
To support file upload, a typical Java Server Pages (JSP) page consists of code such as the following:
<s:form action="doUpload" method="POST" enctype="multipart/form-data">
<s:file name="uploadFile" label="Choose File" size="40" />
<s:submit value="Upload" name="submit" />
</s:form>
Many Java enterprise frameworks provide configuration settings intended to be used as a defense against arbitrary file upload. Unfortunately, most of them fail to provide adequate protection. Mitigation of this vulnerability involves checking file size, content type, and file contents, among other metadata attributes. | <action name="doUpload" class="com.example.UploadAction">
<interceptor-ref name="upload">
<param name="maximumSize"> 10240 </param>
<param name="allowedTypes"> text/plain,image/JPEG,text/html </param>
</interceptor-ref>
</action>
public class UploadAction extends ActionSupport {
private File uploadedFile;
// setter and getter for uploadedFile
public String execute() {
try {
// File path and file name are hardcoded for illustration
File fileToCreate = new File("filepath", "filename");
// Copy temporary file content to this file
FileUtils.copyFile(uploadedFile, fileToCreate);
return "SUCCESS";
} catch (Throwable e) {
addActionError(e.getMessage());
return "ERROR";
}
}
}
## Noncompliant Code Example
This noncompliant code example shows XML code from the upload action of a Struts 2 application. The interceptor code is responsible for allowing file uploads.
<action name="doUpload" class="com.example.UploadAction">
<interceptor-ref name="upload">
<param name="maximumSize"> 10240 </param>
<param name="allowedTypes"> text/plain,image/JPEG,text/html </param>
</interceptor-ref>
</action>
The code for file upload appears in the
UploadAction
class:
#ffcccc
java
public class UploadAction extends ActionSupport {
private File uploadedFile;
// setter and getter for uploadedFile
public String execute() {
try {
// File path and file name are hardcoded for illustration
File fileToCreate = new File("filepath", "filename");
// Copy temporary file content to this file
FileUtils.copyFile(uploadedFile, fileToCreate);
return "SUCCESS";
} catch (Throwable e) {
addActionError(e.getMessage());
return "ERROR";
}
}
}
The value of the parameter type
maximumSize
ensures that a particular
Action
cannot receive a very large file. The
allowedTypes
parameter defines the type of files that are accepted. However, this approach fails to ensure that the uploaded file conforms to the security requirements because interceptor checks can be trivially bypassed. If an attacker were to use a proxy tool to change the content type in the raw HTTP request in transit, the framework would fail to prevent the file's upload. Consequently, an attacker could upload a malicious file that has a .exe extension, for example. | public class UploadAction extends ActionSupport {
private File uploadedFile;
// setter and getter for uploadedFile
public String execute() {
try {
// File path and file name are hardcoded for illustration
File fileToCreate = new File("filepath", "filename");
boolean textPlain = checkMetaData(uploadedFile, "text/plain");
boolean img = checkMetaData(uploadedFile, "image/JPEG");
boolean textHtml = checkMetaData(uploadedFile, "text/html");
if (!textPlain && !img && !textHtml) {
return "ERROR";
}
// Copy temporary file content to this file
FileUtils.copyFile(uploadedFile, fileToCreate);
return "SUCCESS";
} catch (Throwable e) {
addActionError(e.getMessage());
return "ERROR";
}
}
public static boolean checkMetaData(
File f, String getContentType) {
try (InputStream is = new FileInputStream(f)) {
ContentHandler contenthandler = new BodyContentHandler();
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
Parser parser = new AutoDetectParser();
try {
parser.parse(is, contenthandler, metadata, new ParseContext());
} catch (SAXException | TikaException e) {
// Handle error
return false;
}
if (metadata.get(Metadata.CONTENT_TYPE).equalsIgnoreCase(getContentType)) {
return true;
} else {
return false;
}
} catch (IOException e) {
// Handle error
return false;
}
}
}
## Compliant Solution
The file upload must succeed only when the content type matches the actual content of the file. For example, a file with an image header must contain only an image and must not contain executable code. This compliant solution uses the
Apache Tika
library [
Apache 2013
] to detect and extract metadata and structured text content from documents using existing parser libraries. The
checkMetaData()
method must be called before invoking code in
execute()
that is responsible for uploading the file.
#ccccff
java
public class UploadAction extends ActionSupport {
private File uploadedFile;
// setter and getter for uploadedFile
public String execute() {
try {
// File path and file name are hardcoded for illustration
File fileToCreate = new File("filepath", "filename");
boolean textPlain = checkMetaData(uploadedFile, "text/plain");
boolean img = checkMetaData(uploadedFile, "image/JPEG");
boolean textHtml = checkMetaData(uploadedFile, "text/html");
if (!textPlain && !img && !textHtml) {
return "ERROR";
}
// Copy temporary file content to this file
FileUtils.copyFile(uploadedFile, fileToCreate);
return "SUCCESS";
} catch (Throwable e) {
addActionError(e.getMessage());
return "ERROR";
}
}
public static boolean checkMetaData(
File f, String getContentType) {
try (InputStream is = new FileInputStream(f)) {
ContentHandler contenthandler = new BodyContentHandler();
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
Parser parser = new AutoDetectParser();
try {
parser.parse(is, contenthandler, metadata, new ParseContext());
} catch (SAXException | TikaException e) {
// Handle error
return false;
}
if (metadata.get(Metadata.CONTENT_TYPE).equalsIgnoreCase(getContentType)) {
return true;
} else {
return false;
}
} catch (IOException e) {
// Handle error
return false;
}
}
}
The
AutoDetectParser
selects the best available parser on the basis of the content type of the file to be parsed. | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,670 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487670 | 2 | 17 | JNI00-J | Define wrappers around native methods | Native methods are defined in Java and written in languages such as C and C++ [
JNI 2006
]. The added extensibility comes at the cost of flexibility and portability because the code no longer conforms to the policies enforced by Java. Native methods have been used for performing platform-specific operations, interfacing with legacy library code, and improving program performance [
Bloch 2008
].
Defining a wrapper method facilitates installing appropriate security manager checks, validating arguments passed to native code, validating return values, defensively copying mutable inputs, and
sanitizing
untrusted data
. Consequently, every native method must be private and must be invoked only by a wrapper method. | public final class NativeMethod {
// Public native method
public native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method that lacks security checks and input validation
public void doOperation(byte[] data, int offset, int len) {
nativeOperation(data, offset, len);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
}
## Noncompliant Code Example
In this noncompliant code example, the
nativeOperation()
method is both native and public; consequently, untrusted callers may invoke it. Native method invocations bypass security manager checks.
This example includes the
doOperation()
wrapper method, which invokes the
nativeOperation()
native method but fails to provide input validation or security checks.
#FFcccc
public final class NativeMethod {
// Public native method
public native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method that lacks security checks and input validation
public void doOperation(byte[] data, int offset, int len) {
nativeOperation(data, offset, len);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
} | public final class NativeMethodWrapper {
// Private native method
private native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method performs SecurityManager and input validation checks
public void doOperation(byte[] data, int offset, int len) {
// Permission needed to invoke native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// Copy mutable input
data = data.clone();
// Validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation(data, offset, len);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
}
## Compliant Solution
This compliant solution declares the native method private. The
doOperation()
wrapper method checks permissions, creates a defensive copy of the mutable input array
data
, and checks the ranges of the arguments. The
nativeOperation()
method is consequently called with secure inputs. Note that the validation checks must produce outputs that conform to the input requirements of the native methods.
#ccccff
public final class NativeMethodWrapper {
// Private native method
private native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method performs SecurityManager and input validation checks
public void doOperation(byte[] data, int offset, int len) {
// Permission needed to invoke native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// Copy mutable input
data = data.clone();
// Validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation(data, offset, len);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
} | ## Risk Assessment
Failure to define wrappers around native methods can allow unprivileged callers to invoke them and
exploit
inherent
vulnerabilities
such as buffer overflows in native libraries.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI00-J
Medium
Probable
No
No
P4
L3
Automated Detection
Automated detection is not feasible in the fully general case. However, an approach similar to Design Fragments [
Fairbanks 2007
] could assist both programmers and static analysis tools.
Tool
Version
Checker
Description
JAVA.NATIVE.PUBLIC
Parasoft Jtest
CERT.JNI00.NATIW
Use wrapper methods to secure native methods
NativeJava
Full Implementation | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,334 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487334 | 2 | 17 | JNI01-J | Safely invoke standard APIs that perform tasks using the immediate caller's class loader instance (loadLibrary) | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
Many static methods in standard Java APIs vary their behavior according to the immediate caller's class. Such methods are considered to be caller-sensitive. For example, the
java.lang.System.loadLibrary(library)
method uses the immediate caller's class loader to find and dynamically load the specified library containing native method definitions. Because native code bypasses all of the security checks enforced by the Java Runtime Environment and other built-in protections provided by the Java virtual machine, only trusted code should be allowed to load native libraries. None of the loadLibrary methods in the standard APIs should be invoked on behalf of untrusted code since untrusted code may not have the necessary permissions to load the same libraries using its own class loader instance [
Oracle 2014
]. | // Trusted.java
import java.security.*;
public class Trusted {
public static void loadLibrary(final String library){
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary(library);
return null;
}
});
}
}
---------------------------------------------------------------------------------
// Untrusted.java
public class Untrusted {
private native void nativeOperation();
public static void main(String[] args) {
String library = new String("NativeMethodLib");
Trusted.loadLibrary(library);
new Untrusted.nativeOperation(); // invoke the native method
}
}
## Noncompliant Code Example
In this noncompliant example, the Trusted class has permission to load libraries while the Untrusted class does not. However, the Trusted class provides a library loading service through a public method thus allowing the Untrusted class to load any libraries it desires.
#FFcccc
// Trusted.java
import java.security.*;
public class Trusted {
public static void loadLibrary(final String library){
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary(library);
return null;
}
});
}
}
---------------------------------------------------------------------------------
// Untrusted.java
public class Untrusted {
private native void nativeOperation();
public static void main(String[] args) {
String library = new String("NativeMethodLib");
Trusted.loadLibrary(library);
new Untrusted.nativeOperation(); // invoke the native method
}
} | // Trusted.java
import java.security.*;
public class Trusted {
// load native libraries
static{
System.loadLibrary("NativeMethodLib1");
System.loadLibrary("NativeMethodLib2");
...
}
// private native methods
private native void nativeOperation1(byte[] data, int offset, int len);
private native void nativeOperation2(...)
...
// wrapper methods perform SecurityManager and input validation checks
public void doOperation1(byte[] data, int offset, int len) {
// permission needed to invoke native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// copy mutable input
data = data.clone();
// validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation1(data, offset, len);
}
public void doOperation2(...){
...
}
}
## Compliant Solution
In this compliant example, the Trusted class loads any necessary native libraries during initialization and then provides access through public native method wrappers. These wrappers perform the necessary security checks and data validation to ensure that untrusted code cannot exploit the native methods (see
JNI00-J. Define wrappers around native methods
) .
#ccccff
// Trusted.java
import java.security.*;
public class Trusted {
// load native libraries
static{
System.loadLibrary("NativeMethodLib1");
System.loadLibrary("NativeMethodLib2");
...
}
// private native methods
private native void nativeOperation1(byte[] data, int offset, int len);
private native void nativeOperation2(...)
...
// wrapper methods perform SecurityManager and input validation checks
public void doOperation1(byte[] data, int offset, int len) {
// permission needed to invoke native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// copy mutable input
data = data.clone();
// validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation1(data, offset, len);
}
public void doOperation2(...){
...
}
} | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI01-J
high
likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,633 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487633 | 2 | 17 | JNI02-J | Do not assume object references are constant or unique | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
According to [
JNI Tips
], section "Local and Global References", references in native code to the same object may have different values. Return values from the
NewGlobalRef()
function when applied to the same object may differ from each other. Consequently, object references are not necessarily constant or unique. Object references should never be compared using == or
!=
in native code. When testing for object equality, the
IsSameObject()
function should be used instead of
==
. | ## Noncompliant Code Example
This noncompliant code example shows an example where it is assumed that an object reference is constant with erroneous results.
#FFCCCC | ## Compliant Solution
In this compliant solution, in native code, object references are tested for object equality using the
IsSameObject()
function, and the object references tested are global references
.
#CCCCFF | ## Risk Assessment
If it is assumed that an object reference is constant or unique then erroneous results may be obtained that could lead to the app crashing. This, in turn, could be used to mount a denial-of-service attack.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI02-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,624 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487624 | 2 | 17 | JNI03-J | Do not use direct pointers to Java objects in JNI code | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
To allow for the proper operation of the garbage collector in Java, the JVM must keep track of all Java objects passed to native code. Consequently, JNI uses
local references
and
global references
, see [
JNISpec 2014
]
Chapter 2: Design Overview
. While at least one local or global reference to a Java object exists, the object cannot be removed by the garbage collector. However, if the object is moved in memory by the garbage collector then the reference to the object remains valid. Local references are freed automatically when the function in which the local reference is defined returns (although a user may free a local reference before the function returns if they wish). Global references maintain a valid reference to the Java object until they are explicitly freed by the user. (JNI also uses
weak global references
which are similar to global references but allow the referenced object to be removed by the garbage collector, see: [
JNISpec 2014
]
Chapter 4: JNI Functions
.)
Attempting to use a direct pointer to a Java object in native code, rather than a local, global or weak global reference, may have erroneous results because the Java object may be moved or removed by the garbage collector while the direct pointer still exists. | ## Noncompliant Code Example
## This noncompliant code example shows an example where a direct pointer to a Java object is used with erroneous results.
#FFCCCC | ## Compliant Solution
## In this compliant solution ...
#CCCCFF | ## Risk Assessment
If a direct pointer to a Java object is used then erroneous results may be obtained that could lead to the code crashing. This, in turn, could be used to mount a denial of service attack. In some circumstances, the direct pointer could become a "dangling pointer" which could result in sensitive information being leaked or malicious execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI02-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,626 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487626 | 2 | 17 | JNI04-J | Do not assume that Java strings are null-terminated | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
According to [
JNI Tips
], section "UTF-8 and UTF-16 Strings", Java uses UTF-16 strings that are not null-terminated. UTF-16 strings may contain \u0000 in the middle of the string, so it is necessary to know the length of the string when working on Java strings in native code.
JNI does provide methods that work with Modified UTF-8 (see [
API 2013
], Interface DataInput, section "Modified UTF-8"). The advantage of working with Modified UTF-8 is that it encodes \u0000 as 0xc0 0x80 instead of 0x00. This allows the use of C-style null-terminated strings that can be handled by C standard library string functions. However, arbitrary UTF-8 data cannot be expected to work correctly in JNI. Data passed to the
NewStringUTF()
function must be in Modified UTF-8 format. Character data read from a file or stream cannot be passed to the
NewStringUTF()
function without being filtered to convert the high-ASCII characters to Modified UTF-8. In other words, character data must be normalized to Modified UTF-8 before being passed to the
NewStringUTF()
function. (For more information about string normalization see
. Note, however, that that rule is mainly about UTF-16 normalization whereas what is of concern here is Modified UTF-8 normalization.) | ## Noncompliant Code Example
This noncompliant code example shows an example where the wrong type of character encoding is used with erroneous results.
#FFCCCC | ## Compliant Solution
## In this compliant solution ...
#CCCCFF | ## Risk Assessment
If character data is not normalized before being passed to the
NewStringUTF()
function then erroneous results may be obtained.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI04-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,798 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487798 | 2 | 9 | LCK00-J | Use private final lock objects to synchronize classes that may interact with untrusted code | There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization. Methods declared as synchronized and blocks that synchronize on the
this
reference both use the object as a
monitor
(that is, its intrinsic lock). An attacker can manipulate the system to trigger contention and deadlock by obtaining and indefinitely holding the intrinsic lock of an accessible class, consequently causing a denial of service (DoS).
One technique for preventing this vulnerability is the
private lock object
idiom [
Bloch 2001
]. This idiom uses the intrinsic lock associated with the instance of a private final
java.lang.Object
declared within the class instead of the intrinsic lock of the object itself. This idiom requires the use of synchronized blocks within the class's methods rather than the use of synchronized methods. Lock contention between the class's methods and those of a hostile class becomes impossible because the hostile class cannot access the private final lock object.
Static methods and state also share this vulnerability. When a static method is declared
synchronized
, it acquires the intrinsic lock of the class object before any statements in its body are executed, and it releases the intrinsic lock when the method completes. Untrusted code that has access to an object of the class, or of a subclass, can use the
getClass()
method to gain access to the class object and consequently manipulate the class object's intrinsic lock. Protect static data by locking on a private static final
Object
. Reducing the accessibility of the class to package-private provides further protection against untrusted callers.
The private lock object idiom is also suitable for classes that are designed for inheritance. When a superclass requests a lock on the object's monitor, a subclass can interfere with its operation. For example, a subclass may use the superclass object's intrinsic lock for performing unrelated operations, causing lock contention and deadlock. Separating the locking strategy of the superclass from that of the subclass ensures that they do not share a common lock and also permits fine-grained locking by supporting the use of multiple lock objects for unrelated operations. This increases the overall responsiveness of the application.
Objects that require synchronization must use the private lock object idiom rather than their own intrinsic lock in any case where untrusted code could:
Subclass the class.
Create an object of the class or of a subclass.
Access or acquire an object instance of the class or of a subclass.
Subclasses whose superclasses use the private lock object idiom must themselves use the idiom. However, when a class uses intrinsic synchronization on the class object without documenting its locking policy, subclasses must not use intrinsic synchronization on their own class object. When the superclass documents its policy by stating that client-side locking is supported, the subclasses have the option to choose between intrinsic locking and using the private lock object idiom. Subclasses must document their locking policy regardless of which locking option is chosen. See rule
for related information.
When any of these restrictions are violated, the object's intrinsic lock cannot be trusted. But when these restrictions are obeyed, the private lock object idiom fails to add any additional security. Consequently, objects that comply with
all
of the restrictions are permitted to synchronize using their own intrinsic lock. However, block synchronization using the private lock object idiom is superior to method synchronization for methods that contain nonatomic operations that could either use a more fine-grained locking scheme involving multiple private final lock objects or that lack a requirement for synchronization. Nonatomic operations can be decoupled from those that require synchronization and can be executed outside the synchronized block. Both for this reason and for simplification of maintenance, block synchronization using the private lock object idiom is generally preferred over intrinsic synchronization. | public class SomeObject {
// Locks on the object's monitor
public synchronized void changeValue() {
// ...
}
public static SomeObject lookup(String name) {
// ...
}
}
// Untrusted code
String name = // ...
SomeObject someObject = SomeObject.lookup(name);
if (someObject == null) {
// ... handle error
}
synchronized (someObject) {
while (true) {
// Indefinitely lock someObject
Thread.sleep(Integer.MAX_VALUE);
}
}
public class SomeObject {
public Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
}
public class SomeObject {
private volatile Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
public void setLock(Object lockValue) {
lock = lockValue;
}
}
public class SomeObject {
public final Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
}
public class SomeObject {
//changeValue locks on the class object's monitor
public static synchronized void changeValue() {
// ...
}
}
// Untrusted code
synchronized (SomeObject.class) {
while (true) {
Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
}
}
## Noncompliant Code Example (Method Synchronization)
## This noncompliant code example exposes instances of theSomeObjectclass to untrusted code.
#FFCCCC
public class SomeObject {
// Locks on the object's monitor
public synchronized void changeValue() {
// ...
}
public static SomeObject lookup(String name) {
// ...
}
}
// Untrusted code
String name = // ...
SomeObject someObject = SomeObject.lookup(name);
if (someObject == null) {
// ... handle error
}
synchronized (someObject) {
while (true) {
// Indefinitely lock someObject
Thread.sleep(Integer.MAX_VALUE);
}
}
The untrusted code attempts to acquire a lock on the object's monitor and, upon succeeding, introduces an indefinite delay that prevents the synchronized
changeValue()
method from acquiring the same lock. Furthermore, the object locked is publicly available via the
lookup()
method.
Alternatively, an attacker could create a private
SomeObject
object and make it available to trusted code to use it before the attacker code grabs and holds the lock.
Note that in the untrusted code, the attacker intentionally violates rule
.
## Noncompliant Code Example (Public Non-final Lock Object)
This noncompliant code example locks on a public nonfinal object in an attempt to use a lock other than {{SomeObject}}'s intrinsic lock.
#FFcccc
public class SomeObject {
public Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
}
This change fails to protect against malicious code. For example, untrusted or malicious code could disrupt proper synchronization by changing the value of the lock object.
## Noncompliant Code Example (Publicly Accessible Non-final Lock Object)
This noncompliant code example synchronizes on a publicly accessible but nonfinal field. The
lock
field is declared volatile so that changes are visible to other threads.
#FFcccc
public class SomeObject {
private volatile Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
public void setLock(Object lockValue) {
lock = lockValue;
}
}
Any thread can modify the field's value to refer to a different object in the presence of an accessor such as
setLock()
. That modification might cause two threads that intend to lock on the same object to lock on different objects, thereby permitting them to execute two critical sections in an unsafe manner. For example, if the lock were changed when one thread was in its critical section, a second thread would lock on the new object instead of the old one and would enter its critical section erroneously.
A class that lacks accessible methods to change the lock is secure against untrusted manipulation. However, it remains susceptible to inadvertent modification by the programmer.
## Noncompliant Code Example (Public Final Lock Object)
## This noncompliant code example uses a public final lock object.
#FFcccc
public class SomeObject {
public final Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
}
## This noncompliant code example also violates rule.
## Noncompliant Code Example (Static)
## This noncompliant code example exposes the class object ofSomeObjectto untrusted code.
#FFCCCC
public class SomeObject {
//changeValue locks on the class object's monitor
public static synchronized void changeValue() {
// ...
}
}
// Untrusted code
synchronized (SomeObject.class) {
while (true) {
Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
}
}
The untrusted code attempts to acquire a lock on the class object''s monitor and, upon succeeding, introduces an indefinite delay that prevents the synchronized
changeValue()
method from acquiring the same lock. | public class SomeObject {
private final Object lock = new Object(); // private final lock object
public void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
public class SomeObject {
private static final Object lock = new Object();
public static void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
## Compliant Solution (Private Final Lock Object)
Thread-safe public classes that may interact with untrusted code must use a private final lock object. Existing classes that use intrinsic synchronization must be refactored to use block synchronization on such an object. In this compliant solution, calling
changeValue()
obtains a lock on a private final
Object
instance that is inaccessible to callers that are outside the class's scope.
#ccccff
public class SomeObject {
private final Object lock = new Object(); // private final lock object
public void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
A private final lock object can be used only with block synchronization. Block synchronization is preferred over method synchronization because operations without a requirement for synchronization can be moved outside the synchronized region, reducing lock contention and blocking. Note that it is unnecessary to declare the
lock
field volatile because of the strong visibility semantics of final fields. When granularity issues require the use of multiple locks, declare and use multiple private final lock objects to satisfy the granularity requirements rather than using a mutable reference to a lock object along with a setter method.
## A compliant solution must also comply with rule.In the untrusted code, the attacker intentionally violates rule.
## Compliant Solution (Static)
Thread-safe public classes that both use intrinsic synchronization over the class object and may interact with untrusted code must be refactored to use a static private final lock object and block synchronization.
#ccccff
public class SomeObject {
private static final Object lock = new Object();
public static void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
## In this compliant solution,changeValue()obtains a lock on a private staticObjectthat is inaccessible to the caller. | ## Risk Assessment
Exposing the lock object to untrusted code can result in DoS.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
LCK00-J
low
probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.