Java's s garbage-collection feature provides significant benefits from a security perspective over non-garbage-collected languages such as C and C++. The garbage collector (GC) is designed to automatically reclaim unreachable memory and to avoid memory leaks. Although it the GC is quite adept at performing this task, a malicious attacker can nevertheless launch a denial-of-service (DoS) attack , for example, against the GC, such as by inducing abnormal heap memory allocation or abnormally prolonged object retention. For example, some versions of the GC could need to halt all executing threads to keep up with incoming allocation requests that trigger increased heap management activity. System throughput rapidly diminishes in this scenario.
Real-time systems, in particular, are vulnerable to a more subtle slow-heap-exhaustion DoS attack, perpetrated by stealing CPU cycles. An attacker can perform memory allocations in a way that increases the consumption of resources (such as CPU, battery power, and memory) without triggering an OutOfMemoryError
. Writing garbage-collection-friendly collection–friendly code helps restrict many attack avenues.
Use Short-Lived Immutable Objects
Since JDK Beginning with JDK 1.2, the generational garbage collector GC has reduced memory allocation costs to low levels, in many cases to levels lower than in C or C++. Generational garbage collection reduces garbage -collection costs by grouping objects into generations. The _younger generation_ consists of short-lived objects. The GC performs a minor collection on the younger generation when it fills up with dead objects \ [[Oracle 2010a|AA. Bibliography#Oracle 10]\]. Improved garbage -collection algorithms have reduced the cost of garbage collection so that it is proportional to the number of live objects in the younger generation rather than to the total number of objects allocated since the last garbage collection.unmigrated-wiki-markup Wiki Markup
Note that objects in the younger generation that persist for longer durations are _tenured_ and are moved to the _tenured generation_. Few younger -generation objects continue to live through to the next garbage -collection cycle. The rest become ready to be collected in the impending collection cycle \[ [Oracle 2010a|AA. Bibliography#Oracle 10]\].
With generational GCs, use of short-lived immutable objects is generally more efficient than use of long-lived mutable objects, such as object pools. Avoiding object pools improves the garbage collectorGC's efficiency. Object pools bring additional costs and risks: they can create synchronization problems and can require explicit management of deallocations, possibly creating problems with dangling pointers. Further, determining the correct amount of memory to reserve for an object pool can be difficult, especially for mission-critical code. Use of long-lived mutable objects remains appropriate in cases where when allocation of objects is particularly expensive (for example, when performing multiple joins across databases). Similarly, object pools are an appropriate design choice when the objects represent scarce resources, such as thread pools and database connections.
The rules "FIO00-J. Defensively copy mutable inputs and mutable internal components" and "OBJ09-J. Defensively copy private mutable class members before returning their references" promote GC-friendly code.
Avoid Large Objects
The allocation of large objects is expensive, and in part because the cost to initialize their fields is proportional to their size. Additionally, frequent allocation of large objects of different sizes can cause fragmentation issues or non- compacting collect operations.
Do Not Use Direct Buffers for Short Lived, Infrequently Used Objects
The new I/O classes (NIO) in java.nio
allow the creation and use of direct buffers. These buffers tremendously increase throughput for repeated I/O activities. However, their creation and reclamation is more expensive than the creation and reclamation for heap-based non-direct buffers because direct buffers are managed using OS-specific native code. This added management cost makes direct buffers a poor choice for single-use or infrequently used cases. Direct buffers are also not subject to Java's garbage collector, which can cause memory leaks. Frequent allocation of large direct buffers can cause an OutOfMemoryError
.
Noncompliant Code Example
This noncompliant code example uses both a short-lived local object rarelyUsedBuffer
and a long-lived heavily used object heavilyUsedBuffer
. Both are allocated in non-heap memory and are not garbage collected.
Code Block | ||
---|---|---|
| ||
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocateDirect(8192);
// use rarelyUsedBuffer once
ByteBuffer heavilyUsedBuffer = ByteBuffer.allocateDirect(8192);
// use heavilyUsedBuffer many times
|
Compliant Solution
This compliant solution uses an indirect buffer to allocate the short-lived, infrequently used object. The heavily used buffer appropriately continues to use a non-heap, non-garbage-collected direct buffer.
Code Block | ||
---|---|---|
| ||
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocate(8192);
// use rarelyUsedBuffer once
ByteBuffer heavilyUsedBuffer = ByteBuffer.allocateDirect(8192);
// use heavilyUsedBuffer many times
|
Do Not Attempt to "Help the Garbage Collector" by Setting Local Reference Variables to Null
Setting local reference variables to null
to "help the garbage collector" is unnecessary. It adds clutter to the code and can introduce subtle bugs. Java Just-In-Time compilers (JITs) can perform an equivalent liveness analysis; in fact, most implementations do this. A related bad practice is use of a finalizer to null
out references. See rule "MET18-J. Avoid using finalizers" for additional details.
Noncompliant Code Example
In this noncompliant code example, buffer
is a local variable that holds a reference to a temporary array. The programmer attempts to "help the garbage collector" by assigning null
to the buffer
array when it is no longer needed.
Code Block | ||
---|---|---|
| ||
int[] buffer = new int[100];
doSomething(buffer);
buffer = null // No need to explicitly assign null
|
Compliant Solution
Wiki Markup |
---|
Program logic occasionally requires tight control over the lifetime of an object referenced from a local variable. In the unusual cases where such control is necessary, use a lexical block to limit the scope of the variable because the garbage collector can collect the object immediately when it goes out of scope \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
This compliant solution uses a lexical block to control the scope - and, consequently, the lifetime - of the buffer
object.
Code Block | ||
---|---|---|
| ||
{ // limit the scope of buffer
int[] buffer = new int[100];
doSomething(buffer);
}
|
Long-Lived Objects Containing Short-Lived Objects
Always remove short-lived objects from long-lived container objects when the task is over. For example, objects attached to a java.nio.channels.SelectionKey
object must be removed when they are no longer needed. Doing so reduces the possibility of memory leaks. Similarly, use of array-based data structures such as ArrayLists
can introduce a requirement to indicate the absence of an entry by explicitly setting its individual array element to null
.
Noncompliant Code Example (Removing Short-Lived Objects)
In this noncompliant code example, a long-lived ArrayList
contains references to both long- and short-lived elements. The programmer marks elements that have become irrelevant by setting a "dead" flag in the object.
Code Block | ||
---|---|---|
| ||
class DataElement {
private boolean dead = false;
// other fields
public boolean isDead() { return dead; }
public void killMe() { dead = true; }
}
// elsewhere
ArrayList longLivedList = new ArrayList<DataElement>(...);
// processing that renders an element irrelevant
// Kill the element that is now irrelevant
longLivedList.get(someIndex).killMe();
|
The garbage collector cannot collect the dead DataElement
object until it becomes unreferenced. Note that all methods that operate on objects of class DataElement
must check whether the instance in hand is dead.
Compliant Solution (Set Reference to null)
In this compliant solution, rather than use a dead flag, the programmer assigns null
to ArrayList
elements that have become irrelevant.
Code Block | ||
---|---|---|
| ||
class DataElement {
// dead flag removed
// other fields
}
// elsewhere
ArrayList longLivedList = new ArrayList<DataElement>(...);
// processing that renders an element irrelevant
// set the reference to the irrelevant DataElement to null
longLivedList.set(someIndex, null);
|
Note that all code that operates on the longLivedList
must now check for list entries that are null.
Compliant Solution (Use Null Object Pattern)
This compliant solution avoids the problems associated with intentionally null references by use of a singleton sentinel object. This is known as the Null Object pattern (also known as the Sentinel pattern). When feasible, programmers should choose this design pattern over the explicit null reference values.
Code Block | ||
---|---|---|
| ||
class DataElement {
public static final DataElement NULL = createSentinel();
// dead flag removed
// other fields
private static final DataElement createSentinel() {
// allocate a sentinel object, setting all its fields
// to carefully chosen "do nothing" values
}
}
// elsewhere
ArrayList longLivedList = new ArrayList<DataElement>(...);
// processing that renders an element irrelevant
// set the reference to the irrelevant DataElement to
// the NULL object
longLivedList.set(someIndex, NULL);
|
When using this pattern, the Null object must be a singleton and must be final. It may be either public or private, depending on the overall design of the {{DataElement}} class. The state of the Null object should be immutable after creation; this can be enforced either by use of final fields or by explicit code in the methods of the {{DataElement}} class. See \[[Grand 2002|AA. Bibliography#Grand 02]\] "Chapter 8, Behavioral patterns, the Null Object" for additional information on this design pattern. Wiki Markup
Do Not Explicitly Invoke the Garbage Collector
The garbage collector GC can be explicitly invoked by calling the System.gc()
method. Even though the documentation says that it "runs the garbage collector," there is no guarantee as to when or whether the garbage collector GC will actually run. In fact, the call only merely suggests that the GC will should subsequently execute; the JVM is free to ignore this suggestion.
Irresponsible use of this feature can severely degrade system performance by triggering garbage collection at inopportune moments rather than waiting until ripe periods when it is safe to garbage-collect without significant interruption of the program'
...
s execution.
In the Java Hotspot VM (default since JDK 1.2), System.gc()
forces an explicit garbage collection. Such calls can be buried deep within libraries, so they may be difficult to trace. To ignore the call in such cases, use the flag -XX:+DisableExplicitGC
. To avoid long pauses while performing a full GCgarbage collection, a less demanding concurrent cycle may be invoked by specifying the flag -XX:ExplicitGCInvokedConcurrent
.
...
Applicability
Misusing garbage-collection utilities can cause severe performance degradation resulting in a DoS attack.
OBJ11-EX1: When an application goes through several phases, such as an initialization and a ready phase, it could require heap compaction between phases. Given an uneventful period, The System.gc()
method may be invoked in such cases, provided that there is a suitable uneventful period occurs between phases.
OBJ11-EX2: System.gc()
may be invoked as a last resort in a catch
block that is attempting to recover from an OutOfMemoryError
.
Risk Assessment
Misusing garbage collection utilities can cause severe performance degradation resulting in a denial of service (DoS).
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ11-J | low | likely | high | P3 | L3 |
Related Vulnerabilities
Related Guidelines
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="72b717be-4cca-404b-a2ff-deff61f63a30"><ac:plain-text-body><![CDATA[ | [[MITRE 2009 | AA. Bibliography#MITRE 09]] | [CWE-405 | http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)" | ]]></ac:plain-text-body></ac:structured-macro> |
Bibliography
Related Vulnerabilities
The Apache Geronimo and Tomcat vulnerability GERONIMO-4574, reported in March 2009, resulted from PolicyContext
handler data objects being set in a thread and never released, causing these data objects to remain in memory longer than necessary.
Bibliography
[API 2013] | ||||
Item 6, "Eliminate Obsolete Object References" | ||||
"Garbage Collection Concepts and Programming Tips" | ||||
Java Theory and Practice: Garbage Collection and Performance | ||||
[Lo 2005] | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="02e5f388-4db9-40d4-b29d-1a1bb8d2b4fa"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | Class | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="806b0e7d-0a7b-4d17-8ea3-c7b11098316e"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 6: "Eliminate obsolete object references" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4f4fa1ad-09b4-4816-b26b-c07af2d88f38"><ac:plain-text-body><![CDATA[ | [[Coomes 2007 | AA. Bibliography#Coomes 07]] | Garbage Collection Concepts and Programming Tips | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e117aa19-5bf2-456f-a7dc-b9e89ce3917e"><ac:plain-text-body><![CDATA[ | [[Goetz 2004 | AA. Bibliography#Goetz 04]] | Java theory and practice: Garbage collection and performance | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4d2e2f08-4a26-47da-a3da-90141a13660d"><ac:plain-text-body><![CDATA[ | [[Lo 2005 | AA. Bibliography#Lo 05]] | ]]></ac:plain-text-body></ac:structured-macro> | |
[Oracle 2010a] | Java SE 6 HotSpot™ Virtual Machine Garbage Collection Tuning |
...
OBJ10-J. Do not mix generic with non-generic raw types in new code 04. Object Orientation (OBJ) OBJ12-J. Do not leak references to inner class objects when the outer class object maintains sensitive data