Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

From a security point of view, Java's €™s garbage-collection feature provides significant benefits over traditional languages such as C and C++non-garbage-collected languages. The garbage collector (GC) is designed to automatically reclaim unreachable memory and thus to avoid memory leaks. While it Although the GC is quite adept at performing this task, a malicious attacker can nevertheless launch a Denial denial-of Service -service (DoS) attack against the GC, such as by inducing abnormal object heap memory allocation as well as or abnormally prolonged object retention. For example, some versions of the GC will could need to halt all executing threads in order to keep up with the incoming allocation requests that command trigger increased heap management in terms of space allocationactivity. 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 source perform memory allocations in a way that keeps resource increases the consumption of resources (such as CPU, battery power, and memory) high without triggering an OutOfMemoryError. Writing garbage collection friendly -collection–friendly code helps restrict many attack avenues. The best practices have been collated and enumerated below.

Use Short-

...

Lived Immutable Objects

Since Beginning with JDK 1.2, the new generational garbage collector GC has eased out reduced memory allocation related costs, in many cases to minimal levels , even lesser lower than in C /or C++. Deallocation has also become cheaper wherein 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]. Improved garbage-collection algorithms have reduced the cost of garbage collection has become commensurate with so that it is proportional to the number of live objects in the younger generation and not rather than to the total number of objects allocated since the last run. Very few garbage collection.

Note that objects in the younger generation that persist for longer durations are tenured and are moved to the tenured generation. Few younger-younger generation objects continue to live through to the next garbage-collection cycle; the . The rest become ready to be collected in the impending collection cycle [Oracle 2010a].

That said, with With generational GCs it is advantageous to , use of short-lived immutable objects instead is generally more efficient than use of long-lived mutable objects. Object pools are examples of the latter and should thus be avoided to increase the garbage collector, such as object pools. Avoiding object pools improves the GC's efficiency. Moreover, object pools Object pools bring additional costs and risks: they can create synchronization problems , deallocations have to be managed explicitly leading to dangers of dangling pointers and the size of the pool also takes a dominant role in critical code. Exceptions to this recommendation can be made when the allocation takes longer in comparison, such as while performing multiple joins across databases or while using objects that represent scarce resources such as thread pools and database connections.

Wiki Markup
The code fragment below (adopted from \[[Goetz 04|AA. Java References#Goetz 04]\]) shows two containers, {{MutableHolder}} and {{ImmutableHolder}}. In {{MutableHolder}}, the instance field {{value}} can be updated to reference a new value which makes it long-term. On the other hand, when {{value}} is assigned in {{ImmutableHolder}}'s constructor, it is a younger object that is referencing an older one ({{Object o}}). The latter case is a much better position to be in as far as the garbage collector is concerned.

Code Block

public class MutableHolder {
  private Object value;
  public Object getValue() { return value; }
  public void setValue(Object o) { value = o; }
}

public class ImmutableHolder {
  private final Object value;
  public ImmutableHolder(Object o) { value = o; }
  public Object getValue() { return value; }
}
Avoid Large Objects

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 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.

Avoid Large Objects

The allocation of large objects is expensive, in part because the cost to initialize their fields is proportional to their size. Additionally, frequent allocation of The allocation for large objects is expensive and initializing (zeroing) also takes time. Sometimes large objects of different sizes can cause fragmentation issues or non compacting collect.

Nulling References

Reference nulling to "help the garbage collector" is not necessary at all. In fact, it just adds clutter to the code and may lead to bugs. Assigning null to local variables is also not very useful as JIT can equivalently do a liveness analysis. Perhaps the worst one can do is to use a finalizer to null out references, thereby befriending a huge performance hit.

Code Block

int[] buffer = new int[100];
doSomething(buffer);
buffer = null  // no need for explicitly assigning null

Array based data structures such as ArrayLists are an exception since the programmer has to explicitly set only a few of the array elements to null to indicate their demisecompacting collect operations.

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 runs the garbage collector,", € there is no guarantee on as to when the garbage collector would or whether the GC will actually run since . In fact, the call only suggests a run. Other reasons include,merely suggests that the GC 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() does forces an explicit garbage collection. Sometimes these Such calls are can be buried deep within libraries and are hard , so they may be difficult to trace. To ignore the call in such cases, use the flag -XX:+DisableExplicitGC. To avoid long pauses while doing performing a full GCgarbage collection, a less demanding concurrent cycle can may be invoked by specifying the flag -XX:ExplicitGCInvokedConcurrent.

Applicability

Misusing garbage-collection utilities can cause severe performance degradation resulting in a DoS attack.

When an One exception to this rule may exist. The garbage collector can be explicitly called when the application goes through several phases like the , such as an initialization and the a ready phase. The heap needs to be compacted between these phases and given an uneventful period, , it could require heap compaction between phases. The System.gc() method may be explicitly invoked.

Risk Assessment

Misusing some garbage collection utilities can cause Denial Of Service (DoS) related issues and severe performance degradation.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ05-J

low

likely

high

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class {{System}}
\[[Commes 07|AA. Java References#Commes 07]\] Garbage Collection Concepts and Programming Tips
\[[Goetz 04|AA. Java References#Goetz 04]\] 
\[[Lo 05|AA. Java References#Lo 05]\] 
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 405|http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)" 

invoked in such cases, provided a suitable uneventful period occurs between phases.

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

 

...

Image Added Image Added Image AddedOBJ04-J. Encapsulate the absence of an object by using a Null Object      06. Object Orientation (OBJ)      06. Object Orientation (OBJ)