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,895
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487895
2
9
LCK01-J
Do not synchronize on objects that may be reused
Misuse of synchronization primitives is a common source of concurrency issues. Synchronizing on objects that may be reused can result in deadlock and nondeterministic behavior. Consequently, programs must never synchronize on objects that may be reused.
private final Boolean initialized = Boolean.FALSE; public void doSomething() { synchronized (initialized) { // ... } } private int count = 0; private final Integer Lock = count; // Boxed primitive Lock is shared public void doSomething() { synchronized (Lock) { count++; // ... } } private final ...
private int count = 0; private final Integer Lock = new Integer(count); public void doSomething() { synchronized (Lock) { count++; // ... } } private final String lock = new String("LOCK"); public void doSomething() { synchronized (lock) { // ... } } private final Object lock = new Object(); pu...
## Risk Assessment A significant number of concurrency vulnerabilities arise from locking on the wrong kind of object. It is important to consider the properties of the lock object rather than simply scavenging for objects on which to synchronize. Rule Severity Likelihood Detectable Repairable Priority Level LCK01-J me...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,849
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487849
2
9
LCK02-J
Do not synchronize on the class object returned by getClass()
Synchronizing on the return value of the Object.getClass() method can lead to unexpected behavior. Whenever the implementing class is subclassed, the subclass locks on the subclass's type. The Class object of the subclass is entirely distinct from the Class object of the parent class. According to The Java Language Spe...
class Base { static DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public Date parse(String str) throws ParseException { synchronized (getClass()) { return format.parse(str); } } } class Derived extends Base { public Date doSomethingAndParse(String str) throws ParseExce...
class Base { static DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public Date parse(String str) throws ParseException { synchronized (Base.class) { return format.parse(str); } } } // ... class Base { static DateFormat format = DateFormat.getDateInstance(DateForm...
## Risk Assessment Synchronizing on the class object returned by getClass() can result in undesired behavior. Rule Severity Likelihood Detectable Repairable Priority Level LCK02-J Medium Probable Yes No P8 L2 Automated Detection Some static analysis tools can detect violations of this rule Tool Version Checker Descript...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,850
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487850
2
9
LCK03-J
Do not synchronize on the intrinsic locks of high-level concurrency objects
Instances of classes that implement either or both of the Lock and Condition interfaces of the java.util.concurrent.locks package are known as high-level concurrency objects. Using the intrinsic locks of such objects is a questionable practice even in cases where the code may appear to function correctly. Code that use...
private final Lock lock = new ReentrantLock(); public void doSomething() { synchronized(lock) { // ... } } ## Noncompliant Code Example (ReentrantLock) The doSomething() method in this noncompliant code example synchronizes on the intrinsic lock of an instance of ReentrantLock rather than on the reentrant mut...
private final Lock lock = new ReentrantLock(); public void doSomething() { lock.lock(); try { // ... } finally { lock.unlock(); } } ## Compliant Solution (lock()andunlock()) ## This compliant solution uses thelock()andunlock()methods provided by theLockinterface. #ccccff private final Lock lock = new ...
## Risk Assessment Synchronizing on the intrinsic lock of high-level concurrency utilities can cause nondeterministic behavior resulting from inconsistent locking policies. Rule Severity Likelihood Detectable Repairable Priority Level LCK03-J medium probable Yes No P8 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,846
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487846
2
9
LCK04-J
Do not synchronize on a collection view if the backing collection is accessible
The Java Tutorials, Wrapper Implementations [ Java Tutorials ], warns about the consequences of failing to synchronize on an accessible collection object when iterating over its view: It is imperative that the user manually synchronize on the returned Map when iterating over any of its Collection views rather than sync...
private final Map<Integer, String> mapView = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> setView = mapView.keySet(); public Map<Integer, String> getMap() { return mapView; } public void doSomething() { synchronized (setView) { // Incorrectly synchronizes on setView...
private final Map<Integer, String> mapView = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> setView = mapView.keySet(); public Map<Integer, String> getMap() { return mapView; } public void doSomething() { synchronized (mapView) { // Synchronize on map, rather than set...
## Risk Assessment Synchronizing on a collection view instead of the collection object can cause nondeterministic behavior. Rule Severity Likelihood Detectable Repairable Priority Level LCK04-J Low Probable Yes No P4 L3 Automated Detection Some static analysis tools are capable of detecting violations of this rule. Too...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,905
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487905
2
9
LCK05-J
Synchronize access to static fields that can be modified by untrusted code
Methods that can both modify a static field and be invoked from untrusted code must synchronize access to the static field. Even when client-side locking is a specified requirement of the method, untrusted clients can fail to synchronize (whether inadvertently or maliciously). Because the static field is shared by all ...
/* This class is not thread-safe */ public final class CountHits { private static int counter; public void incrementCounter() { counter++; } } ## Noncompliant Code Example ## This noncompliant code example fails to synchronize access to the staticcounterfield: #FFCCCC /* This class is not thread-safe */ pub...
/* This class is thread-safe */ public final class CountHits { private static int counter; private static final Object lock = new Object(); public void incrementCounter() { synchronized (lock) { counter++; } } } ## Compliant Solution This compliant solution uses a static private final lock to pr...
## Risk Assessment Failure to internally synchronize access to static fields that can be modified by untrusted code risks incorrect synchronization because the author of the untrusted code can inadvertently or maliciously ignore the synchronization policy. Rule Severity Likelihood Detectable Repairable Priority Level L...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,833
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487833
2
9
LCK06-J
Do not use an instance lock to protect shared static data
Programs must not use instance locks to protect static shared data because instance locks are ineffective when two or more instances of the class are created. Consequently, failure to use a static lock object leaves the shared state unprotected against concurrent access. Lock objects for classes that can interact with ...
public final class CountBoxes implements Runnable { private static volatile int counter; // ... private final Object lock = new Object(); @Override public void run() { synchronized (lock) { counter++; // ... } } public static void main(String[] args) { for (int i = 0; i < 2; i++) {...
public class CountBoxes implements Runnable { private static int counter; // ... private static final Object lock = new Object(); public void run() { synchronized (lock) { counter++; // ... } } // ... } ## Compliant Solution (Static Lock Object) ## This compliant solution ensures the a...
## Risk Assessment Using an instance lock to protect static shared data can result in nondeterministic behavior. Rule Severity Likelihood Detectable Repairable Priority Level LCK06-J Medium Probable Yes No P8 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,703
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487703
2
9
LCK07-J
Avoid deadlock by requesting and releasing locks in the same order
To avoid data corruption in multithreaded Java programs, shared data must be protected from concurrent modifications and accesses. Locking can be performed at the object level using synchronized methods, synchronized blocks, or the java.util.concurrent dynamic lock objects. However, excessive use of locking can result ...
final class BankAccount { private double balanceAmount; // Total amount in bank account BankAccount(double balance) { this.balanceAmount = balance; } // Deposits the amount from this object instance // to BankAccount instance argument ba private void depositAmount(BankAccount ba, double amount) { ...
final class BankAccount { private double balanceAmount; // Total amount in bank account private static final Object lock = new Object(); BankAccount(double balance) { this.balanceAmount = balance; } // Deposits the amount from this object instance // to BankAccount instance argument ba private void...
## Risk Assessment Acquiring and releasing locks in the wrong order can result in deadlock . Rule Severity Likelihood Detectable Repairable Priority Level LCK07-J Low Likely No No P3 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,697
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487697
2
9
LCK08-J
Ensure actively held locks are released on exceptional conditions
An exceptional condition can circumvent the release of a lock, leading to deadlock . According to the Java API [ API 2014 ]: A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by anot...
public final class Client { private final Lock lock = new ReentrantLock(); public void doSomething(File file) { InputStream in = null; try { in = new FileInputStream(file); lock.lock(); // Perform operations on the open file lock.unlock(); } catch (FileNotFoundException x) { ...
public final class Client { private final Lock lock = new ReentrantLock(); public void doSomething(File file) { InputStream in = null; lock.lock(); try { in = new FileInputStream(file); // Perform operations on the open file } catch (FileNotFoundException fnf) { // Forward to hand...
## Risk Assessment Failure to release locks on exceptional conditions could lead to thread starvation and deadlock . Rule Severity Likelihood Detectable Repairable Priority Level LCK08-J Low Likely Yes Yes P9 L2 Automated Detection Some static analysis tools are capable of detecting violations of this rule. Tool Versio...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,777
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487777
2
9
LCK09-J
Do not perform operations that can block while holding a lock
Holding locks while performing time-consuming or blocking operations can severely degrade system performance and can result in starvation . Furthermore, deadlock can result if interdependent threads block indefinitely. Blocking operations include network, file, and console I/O (for example, Console.readLine() ) and obj...
public synchronized void doSomething(long time) throws InterruptedException { // ... Thread.sleep(time); } // Class Page is defined separately. // It stores and returns the Page name via getName() Page[] pageBuff = new Page[MAX_PAGE_SIZE]; public synchronized boolean sendPage(Socket sock...
public synchronized void doSomething(long timeout) throws InterruptedException { // ... while (<condition does not hold>) { wait(timeout); // Immediately releases the current monitor } } // No synchronization public boolean sendPage(Socket socket, String pageName) { Page ...
## Risk Assessment Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or unresponsive system. Rule Severity Likelihood Detectable Repairable Priority Level LCK09-J Low Probable No No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,915
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487915
2
9
LCK10-J
Use a correct form of the double-checked locking idiom
The double-checked locking idiom is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion without actually acquiring the lock. Double-checked locking improves performance by limiting synchronization to the rare case of computing the field's value or constructin...
// Double-checked locking idiom final class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(); } } } return helper; } // Other methods and members... } public...
// Works with acquire/release semantics for volatile // Broken under JDK 1.4 and earlier final class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(); } } } ...
## Risk Assessment Using incorrect forms of the double-checked locking idiom can lead to synchronization problems and can expose partially initialized objects. Rule Severity Likelihood Detectable Repairable Priority Level LCK10-J Low Probable Yes No P4 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,661
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487661
2
9
LCK11-J
Avoid client-side locking when using classes that do not commit to their locking strategy
According to Goetz and colleagues [ Goetz 2006 ]: Client-side locking entails guarding client code that uses some object X with the lock X uses to guard its own state. In order to use client-side locking, you must know what lock X uses. While client-side locking is acceptable when the thread-safe class commits to and c...
final class Book { // Could change its locking policy in the future // to use private final locks private final String title; private Calendar dateIssued; private Calendar dateDue; Book(String title) { this.title = title; } public synchronized void issue(int days) { dateIssued = Calendar.getIn...
public final class BookWrapper { private final Book book; private final Object lock = new Object(); BookWrapper(Book book) { this.book = book; } public void issue(int days) { synchronized(lock) { book.issue(days); } } public Calendar getDueDate() { synchronized(lock) { retur...
## Risk Assessment Using client-side locking when the thread-safe class fails to commit to its locking strategy can cause data inconsistencies and deadlock . Rule Severity Likelihood Detectable Repairable Priority Level LCK11-J Low Probable No No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK)
java
88,487,758
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487758
2
6
MET00-J
Validate method arguments
Validate method arguments to ensure that they fall within the bounds of the method's intended design. This practice ensures that operations on the method's parameters yield valid results. Failure to validate method arguments can result in incorrect calculations, runtime exceptions, violation of class invariants , and i...
private Object myState = null; // Sets some internal state in the library void setState(Object state) { myState = state; } // Performs some action using the state passed earlier void useState() { // Perform some action here } ## Noncompliant Code Example In this noncompliant code example, setState() and useState...
private Object myState = null; // Sets some internal state in the library void setState(Object state) { if (state == null) { // Handle null state } // Defensive copy here when state is mutable if (isInvalidState(state)) { // Handle invalid state } myState = state; } // Performs some action using...
## Risk Assessment Failure to validate method arguments can result in inconsistent computations, runtime exceptions, and control flow vulnerabilities . Rule Severity Likelihood Detectable Repairable Priority Level MET00-J High Likely No No P9 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,453
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487453
2
6
MET01-J
Never use assertions to validate method arguments
Never use assertions to validate arguments of public methods. The Java Language Specification , §14.10, "The assert Statement" [ JLS 2015 ], states that assertions should not be used for argument checking in public methods. Argument checking is typically part of the contract of a method, and this contract must be uphel...
public static int getAbsAdd(int x, int y) { return Math.abs(x) + Math.abs(y); } getAbsAdd(Integer.MIN_VALUE, 1); public static int getAbsAdd(int x, int y) { assert x != Integer.MIN_VALUE; assert y != Integer.MIN_VALUE; int absX = Math.abs(x); int absY = Math.abs(y); assert (absX <= Integer.MAX_VALUE - absY...
public static int getAbsAdd(int x, int y) { if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) { throw new IllegalArgumentException(); } int absX = Math.abs(x); int absY = Math.abs(y); if (absX > Integer.MAX_VALUE - absY) { throw new IllegalArgumentException(); } return absX + absY; } ## Compl...
## Risk Assessment Using assertions to validate method arguments can result in inconsistent computations, runtime exceptions, and control flow vulnerabilities . Rule Severity Likelihood Detectable Repairable Priority Level MET01-J Medium Probable No Yes P8 L2 Automated Detection Tool Version Checker Description JAVA.AS...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,913
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487913
2
6
MET02-J
Do not use deprecated or obsolete classes or methods
Never use deprecated fields, methods, or classes in new code. Java provides an @deprecated annotation to indicate the deprecation of specific fields, methods, and classes. For example, many methods of java.util.Date , such as Date.getYear() , have been explicitly deprecated. describes issues that can result from using ...
null
null
## Risk Assessment Using deprecated or obsolete classes or methods in program code can lead to erroneous behavior. Rule Severity Likelihood Detectable Repairable Priority Level MET02-J Low Unlikely Yes No P2 L3 Automated Detection Detecting uses of deprecated methods is straightforward. Obsolete methods have no automat...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,765
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487765
2
6
MET03-J
Methods that perform a security check must be declared private or final
Nonfinal member methods that perform security checks can be compromised when a malicious subclass overrides the methods and omits the checks. Consequently, such methods must be declared private or final to prevent overriding.
public void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } } ## Noncompliant Code Example This ...
public final void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } } private void readSensitiveFi...
## Risk Assessment Failure to declare a class's method private or final affords the opportunity for a malicious subclass to bypass the security checks performed in the method. Rule Severity Likelihood Detectable Repairable Priority Level MET03-J Medium Probable No No P4 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,389
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487389
2
6
MET04-J
Do not increase the accessibility of overridden or hidden methods
Increasing the accessibility of overridden or hidden methods permits a malicious subclass to offer wider access to the restricted method than was originally intended. Consequently, programs must override methods only when necessary and must declare methods final whenever possible to prevent malicious subclassing. When ...
class Super { protected void doLogic() { System.out.println("Super invoked"); } } public class Sub extends Super { public void doLogic() { System.out.println("Sub invoked"); // Do sensitive operations } } ## Noncompliant Code Example This noncompliant code example demonstrates how a malicious subc...
class Super { protected final void doLogic() { // Declare as final System.out.println("Super invoked"); // Do sensitive operations } } ## Compliant Solution ## This compliant solution declares thedoLogic()method final to prevent malicious overriding: #ccccff class Super { protected final void doLogic() { /...
## Risk Assessment Subclassing allows weakening of access restrictions, which can compromise the security of a Java application. Rule Severity Likelihood Detectable Repairable Priority Level MET04-J Medium Probable Yes No P8 L2 Automated Detection Detecting violations of this rule is straightforward. Tool Version Check...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,667
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487667
2
6
MET05-J
Ensure that constructors do not call overridable methods
According to The Java Language Specification , §12.5, "Creation of New Class Instances" [ JLS 2015 ]: Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being ini...
class SuperClass { public SuperClass () { doLogic(); } public void doLogic() { System.out.println("This is superclass!"); } } class SubClass extends SuperClass { private String color = "red"; public void doLogic() { System.out.println("This is subclass! The color is :" + color); // ... ...
class SuperClass { public SuperClass() { doLogic(); } public final void doLogic() { System.out.println("This is superclass!"); } } ## Compliant Solution ## This compliant solution declares thedoLogic()method as final so that it cannot be overridden: #ccccff class SuperClass { public SuperClass() { doL...
## Risk Assessment Allowing a constructor to call overridable methods can provide an attacker with access to the this reference before an object is fully initialized, which could lead to a vulnerability . Rule Severity Likelihood Detectable Repairable Priority Level MET05-J Medium Probable Yes No P8 L2 Automated Detect...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,921
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487921
2
6
MET06-J
Do not invoke overridable methods in clone()
Calling overridable methods from the clone() method is insecure. First, a malicious subclass could override the method and affect the behavior of the clone() method. Second, a trusted subclass could observe (and potentially modify) the cloned object in a partially initialized state before its construction has concluded...
class CloneExample implements Cloneable { HttpCookie[] cookies; CloneExample(HttpCookie[] c) { cookies = c; } public Object clone() throws CloneNotSupportedException { final CloneExample clone = (CloneExample) super.clone(); clone.doSomething(); // Invokes overridable method clone.cookies = cl...
class CloneExample implements Cloneable { final void doSomething() { // ... } final HttpCookie[] deepCopy() { // ... } // ... } ## Compliant Solution This compliant solution declares both the doSomething() and the deepCopy() methods final, preventing overriding of these methods: #ccccff class CloneE...
## Risk Assessment Calling overridable methods on the clone under construction can expose class internals to malicious code or violate class invariants by exposing the clone to trusted code in a partially initialized state, affording the opportunity to corrupt the state of the clone, the object being cloned, or both. R...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,431
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487431
2
6
MET07-J
Never declare a class method that hides a method declared in a superclass or superinterface
When a class declares a static method m , the declaration of m hides any method m ', where the signature of m is a subsignature of the signature of m ' and the declaration of m ' is both in the superclasses and superinterfaces of the declaring class and also would otherwise be accessible to code in the declaring class ...
class GrantAccess { public static void displayAccountStatus() { System.out.println("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { public static void displayAccountStatus() { System.out.println("Account details for user: XX"); } } public class StatMethod { public st...
class GrantAccess { public void displayAccountStatus() { System.out.print("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { @Override public void displayAccountStatus() { System.out.print("Account details for user: XX"); } } public class StatMethod { public static v...
## Risk Assessment Confusing overriding and hiding can produce unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level MET07-J Low Unlikely Yes No P2 L3 Automated Detection Automated detection of violations of this rule is straightforward. Automated determination of cases in which method hidin...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,427
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487427
2
6
MET08-J
Preserve the equality contract when overriding the equals() method
Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, someti...
public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); } this.s = s; } // This method violates symmetry public boolean equals(Object o) { if (o instanceof CaseInsensitiveString) { re...
public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); } this.s = s; } public boolean equals(Object o) { return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equ...
## Risk Assessment Violating the general contract when overriding the equals() method can lead to unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level MET08-J Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description JAVA.COMPARE.CTO.ASSYM JAVA.IDEF.NOEQUALS JAVA.IDEF.CT...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,404
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487404
2
6
MET09-J
Classes that define an equals() method must also define a hashCode() method
Classes that override the Object.equals() method must also override the Object.hashCode() method. The java.lang.Object class requires that any two objects that compare equal using the equals() method must produce the same integer result when the hashCode() method is invoked on the objects [ API 2014 ]. The equals() met...
public final class CreditCard { private final int number; public CreditCard(int number) { this.number = number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return c...
public final class CreditCard { private final int number; public CreditCard(int number) { this.number = number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return...
## Risk Assessment Overriding the equals() method without overriding the hashCode() method can lead to unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level MET09-J Low Unlikely Yes No P2 L3 Automated Detection Automated detection of classes that override only one of equals() and hashcode() ...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,771
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487771
2
6
MET10-J
Follow the general contract when implementing the compareTo() method
Choosing to implement the Comparable interface represents a commitment that the implementation of the compareTo() method adheres to the general contract for that method regarding how the method is to be called. Library classes such as TreeSet and TreeMap accept Comparable objects and use the associated compareTo() meth...
class GameEntry implements Comparable { public enum Roshambo {ROCK, PAPER, SCISSORS} private Roshambo value; public GameEntry(Roshambo value) { this.value = value; } public int compareTo(Object that) { if (!(that instanceof GameEntry)) { throw new ClassCastException(); } GameEntry t = ...
class GameEntry { public enum Roshambo {ROCK, PAPER, SCISSORS} private Roshambo value; public GameEntry(Roshambo value) { this.value = value; } public int beats(Object that) { if (!(that instanceof GameEntry)) { throw new ClassCastException(); } GameEntry t = (GameEntry) that; retu...
## Risk Assessment Violating the general contract when implementing the compareTo() method can cause unexpected results, possibly leading to invalid comparisons and information disclosure. Rule Severity Likelihood Detectable Repairable Priority Level MET10-J Medium Unlikely No No P2 L3 Automated Detection Automated det...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,869
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487869
2
6
MET11-J
Ensure that keys used in comparison operations are immutable
Objects that serve as keys in ordered sets and maps should be immutable. When some fields must be mutable, the equals() , hashCode() , and compareTo() methods must consider only immutable state when comparing objects. Violations of this rule can produce inconsistent orderings in collections. The documentation of java.u...
// Mutable class Employee class Employee { private String name; private double salary; Employee(String empName, double empSalary) { this.name = empName; this.salary = empSalary; } public void setEmployeeName(String empName) { this.name = empName; } public void setSalary(double empSalary) { ...
// Mutable class Employee class Employee { private String name; private double salary; private final long employeeID; // Unique for each Employee Employee(String name, double salary, long empID) { this.name = name; this.salary = salary; this.employeeID = empID; } // ... @Override public ...
## Risk Assessment Failure to ensure that the keys used in a comparison operation are immutable can lead to nondeterministic behavior. Rule Severity Likelihood Detectable Repairable Priority Level MET11-J Low Probable Yes No P4 L3 Automated Detection Some available static analysis tools can detect instances where the c...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,650
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487650
2
6
MET12-J
Do not use finalizers
The garbage collector invokes object finalizer methods after it determines that the object is unreachable but before it reclaims the object's storage. Execution of the finalizer provides an opportunity to release resources such as open streams, files, and network connections that might not otherwise be released automat...
class MyFrame extends JFrame { private byte[] buffer = new byte[16 * 1024 * 1024]; // Persists for at least two GC cycles } class BaseClass { protected void finalize() throws Throwable { System.out.println("Superclass finalize!"); doLogic(); } public void doLogic() throws Throwable { System.out....
class MyFrame { private JFrame frame; private byte[] buffer = new byte[16 * 1024 * 1024]; // Now decoupled } ## Compliant Solution (Superclass's finalizer) When a superclass defines a finalize() method, make sure to decouple the objects that can be immediately garbage collected from those that must depend on the f...
## Risk Assessment Improper use of finalizers can result in resurrection of garbage-collection-ready objects and result in denial-of-service vulnerabilities. Rule Severity Likelihood Detectable Repairable Priority Level MET12-J Medium Probable Yes No P8 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,819
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487819
2
6
MET13-J
Do not assume that reassigning method arguments modifies the calling environment
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 Leaking sensitive information outside a trust boundary is not a good idea. Rule Severity Likelihood Detectable Repairable Priority Level MET13-J Medium Likely No No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 06. Methods (MET)
java
88,487,498
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487498
3
6
MET50-J
Avoid ambiguous or confusing uses of overloading
Method and constructor overloading allows declaration of methods or constructors with the same name but with different parameter lists. The compiler inspects each call to an overloaded method or constructor and uses the declared types of the method parameters to decide which method to invoke. In some cases, however, co...
class Con { public Con(int i, String s) { // Initialization Sequence #1 } public Con(String s, int i) { // Initialization Sequence #2 } public Con(Integer i, String s) {  // Initialization Sequence #3 } } class OverLoader extends HashMap<Integer,Integer> { HashMap<Integer,Integer> hm; p...
public static Con createCon1(int i, String s) { /* Initialization Sequence #1 */ } public static Con createCon2(String s, int i) { /* Initialization Sequence #2 */ } public static Con createCon3(Integer i, String s) {  /* Initialization Sequence #3 */ } public Integer getDataByIndex(int i) { // No longer ove...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,555
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487555
3
6
MET51-J
Do not use overloaded methods to differentiate between runtime types
Java supports overloading methods and can distinguish between methods with different signatures. Consequently, with some qualifications, methods within a class can have the same name if they have different parameter lists. In method overloading, the method to be invoked at runtime is determined at compile time. Consequ...
public class Overloader { private static String display(ArrayList<Integer> arrayList) { return "ArrayList"; } private static String display(LinkedList<String> linkedList) { return "LinkedList"; } private static String display(List<?> list) { return "List is not recognized"; } public static ...
public class Overloader { private static String display(List<?> list) { return ( list instanceof ArrayList ? "Arraylist" : (list instanceof LinkedList ? "LinkedList" : "List is not recognized") ); } public static void main(String[] args) { // Single ArrayList System.out.printl...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,571
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487571
3
6
MET52-J
Do not use the clone() method to copy untrusted method parameters
Making defensive copies of mutable method parameters mitigates against a variety of security vulnerabilities; see OBJ06-J. Defensively copy mutable inputs and mutable internal components for additional information. However, inappropriate use of the clone() method can allow an attacker to exploit vulnerabilities by prov...
private Boolean validateValue(long time) { // Perform validation return true; // If the time is valid } private void storeDateInDB(java.util.Date date) throws SQLException { final java.util.Date copy = (java.util.Date)date.clone(); if (validateValue(copy.getTime())) { Connection con = DriverManager.getCon...
private void storeDateInDB(java.util.Date date) throws SQLException { final java.util.Date copy = new java.util.Date(date.getTime()); if (validateValue(copy.getTime())) { Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://<HOST>:1433","<UID>","<PWD>"); PreparedStatement pstmt = con.pre...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,446
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487446
3
6
MET53-J
Ensure that the clone() method calls super.clone()
Cloning a subclass a nonfinal class that defines a clone() method that fails to call super.clone() will produce an object of the wrong class. The Java API [ API 2013 ] for the clone() method says: By convention, the returned object should be obtained by calling super.clone . If a class and all of its superclasses (exce...
class Base implements Cloneable { public Object clone() throws CloneNotSupportedException { return new Base(); } protected void doLogic() { System.out.println("Superclass doLogic"); } } class Derived extends Base { public Object clone() throws CloneNotSupportedException { return super.clone(); ...
class Base implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } protected void doLogic() { System.out.println("Superclass doLogic"); } } class Derived extends Base { public Object clone() throws CloneNotSupportedException { return super.clone(...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,598
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487598
3
6
MET54-J
Always provide feedback about the resulting value of a method
Methods should be designed to return a value that allows the developer to learn about the current state of the object and/or the result of an operation. This advice is consistent with EXP00-J. Do not ignore values returned by methods . The returned value should be representative of the last known state and should be ch...
public void updateNode(int id, int newValue) { Node current = root; while (current != null) { if (current.getId() == id) { current.setValue(newValue); break; } current = current.next; } } ## Noncompliant Code Example The updateNode() method in this noncompliant code example modifies a n...
public boolean updateNode(int id, int newValue) { Node current = root; while (current != null) { if (current.getId() == id) { current.setValue(newValue); return true; // Node successfully updated } current = current.next; } return false; } public Node updateNode(int id, int newValue) ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,463
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487463
3
6
MET55-J
Return an empty array or collection instead of a null value for methods that return an array or collection
Some APIs intentionally return a null reference to indicate that instances are unavailable. This practice can lead to denial-of-service vulnerabilities when the client code fails to explicitly handle the null return value case. A null value is an example of an in-band error indicator, which is discouraged by . For meth...
class Inventory { private final Hashtable<String, Integer> items; public Inventory() { items = new Hashtable<String, Integer>(); } public List<String> getStock() { List<String> stock = new ArrayList<String>(); Enumeration itemKeys = items.keys(); while (itemKeys.hasMoreElements()) { Obje...
class Inventory { private final Hashtable<String, Integer> items; public Inventory() { items = new Hashtable<String, Integer>(); } public List<String> getStock() { List<String> stock = new ArrayList<String>(); Integer noOfItems; // Number of items left in the inventory Enumeration itemKeys = i...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,584
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487584
3
6
MET56-J
Do not use Object.equals() to compare cryptographic keys
The method java.lang.Object.equals() , by default, is unable to compare composite objects such as cryptographic keys. Most Key classes fail to provide an equals() implementation that overrides Object.equals() . In such cases, the components of the composite object must be compared individually to ensure correctness.
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } return false; } ## Noncompliant Code Example This noncompliant code example compares two keys using the equals() method. The keys may compare unequal even when they represent the same value. #FFCCCC private static ...
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) { return true; } // More code for different types of keys here // For example, the following code can check whether // an RSAPrivateKey and an R...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 06. Methods (MET)
java
88,487,828
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487828
2
49
MSC00-J
Use SSLSocket rather than Socket for secure data exchange
Programs must use the javax.net.ssl.SSLSocket class rather than the java.net.Socket class when transferring sensitive data over insecure communication channels. The class SSLSocket provides security protocols such as Secure Sockets Layer/Transport Layer Security (SSL/TLS) to ensure that the channel is not vulnerable to...
// Exception handling has been omitted for the sake of brevity class EchoServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); PrintWriter out = new PrintWri...
// Exception handling has been omitted for the sake of brevity class EchoServer { public static void main(String[] args) throws IOException { SSLServerSocket sslServerSocket = null; try { SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault...
## Risk Assessment Use of plain sockets fails to provide any guarantee of the confidentiality and integrity of data transmitted over those sockets. Rule Severity Likelihood Detectable Repairable Priority Level MSC00-J Medium Likely No No P6 L2 Automated Detection The general case of automated detection appears to be in...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,575
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487575
2
49
MSC01-J
Do not use an empty infinite loop
An infinite loop with an empty body consumes CPU cycles but does nothing. Optimizing compilers and just-in-time systems (JITs) are permitted to (perhaps unexpectedly) remove such a loop. Consequently, programs must not include infinite loops with empty bodies.
public int nop() { while (true) {} } ## Noncompliant Code Example This noncompliant code example implements an idle task that continuously executes a loop without executing any instructions within the loop. An optimizing compiler or JIT could remove the while loop in this example. #FFCCCC public int nop() { while (t...
public final int DURATION=10000; // In milliseconds public void nop() throws InterruptedException { while (true) { // Useful operations Thread.sleep(DURATION); } } public void nop() { while (true) { Thread.yield(); } } ## Compliant Solution (Thread.sleep()) This compliant solution avoids use of a...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level MSC01-J Low Unlikely Yes Yes P3 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,841
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487841
2
49
MSC02-J
Generate strong random numbers
Pseudorandom number generators (PRNGs) use deterministic mathematical algorithms to produce a sequence of numbers with good statistical properties. However, the sequences of numbers produced fail to achieve true randomness. PRNGs usually start with an arithmetic seed value. The algorithm uses this seed to generate an o...
import java.util.Random; // ... Random number = new Random(123L); //... for (int i = 0; i < 20; i++) { // Generate another random integer in the range [0, 20] int n = number.nextInt(21); System.out.println(n); } ## Noncompliant Code Example This noncompliant code example uses the insecure java.util.Random class...
import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; // ... public static void main (String args[]) { SecureRandom number = new SecureRandom(); // Generate 20 integers 0..20 for (int i = 0; i < 20; i++) { System.out.println(number.nextInt(21)); } } import java.security.SecureR...
## Risk Assessment Predictable random number sequences can weaken the security of critical applications such as cryptography. Rule Severity Likelihood Detectable Repairable Priority Level MSC02-J High Probable No No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,738
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487738
2
49
MSC03-J
Never hard code sensitive information
Hard coding sensitive information, such as passwords, server IP addresses, and encryption keys can expose the information to attackers. Anyone who has access to the class files can decompile them and discover the sensitive information. Leaking data protected by International Traffic in Arms Regulations (ITAR) or the He...
class IPaddress { String ipAddress = new String("172.16.254.1"); public static void main(String[] args) { //... } } Compiled from "IPaddress.java" class IPaddress extends java.lang.Object{ java.lang.String ipAddress; IPaddress(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/O...
class IPaddress { public static void main(String[] args) throws IOException { char[] ipAddress = new char[100]; int offset = 0; int charsRead = 0; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader( new FileInputStream("serveripaddress.txt"))); w...
## Risk Assessment Hard coding sensitive information exposes that information to attackers. The severity of this rule can vary depending on the kind of information that is disclosed. Frequently, the information disclosed is password or key information, which can lead to remote exploitation. Consequently, a high severit...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,651
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487651
2
49
MSC04-J
Do not leak memory
Programming errors can prevent garbage collection of objects that are no longer relevant to program operation. The garbage collector collects only unreachable objects; consequently, the presence of reachable objects that remain unused indicates memory mismanagement. Consumption of all available heap space can cause an ...
public class Leak { static Vector vector = new Vector(); public void useVector(int count) { for (int n = 0; n < count; n++) { vector.add(Integer.toString(n)); } // ... for (int n = count - 1; n > 0; n--) { // Free the memory vector.removeElementAt(n); } } public static void ...
public void useVector(int count) { int n = 0; try { for (; n < count; n++) { vector.add(Integer.toString(n)); } // ... } finally { for (n = n - 1; n >= 0; n--) { vector.removeElementAt(n); } } } public void useVector(int count) { try { for (int n = 0; n < count; n++) { ...
## Risk Assessment Memory leaks in Java applications may be exploited in a DoS attack. Rule Severity Likelihood Detectable Repairable Priority Level MSC04-J Low Unlikely No No P1 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,861
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487861
2
49
MSC05-J
Do not exhaust heap space
A Java OutofMemoryError occurs when the program attempts to use more heap space than is available. Among other causes, this error may result from the following: A memory leak (see ) An infinite loop Limited amounts of default heap memory available Incorrect implementation of common data structures (hash tables, vectors...
class ReadNames { private Vector<String> names = new Vector<String>(); private final InputStreamReader input; private final BufferedReader reader; public ReadNames(String filename) throws IOException { this.input = new FileReader(filename); this.reader = new BufferedReader(input); } public void ad...
class ReadNames { // ... Other methods and variables public static final int fileSizeLimit = 1000000; public ReadNames(String filename) throws IOException { long size = Files.size( Paths.get( filename)); if (size > fileSizeLimit) { throw new IOException("File too large"); } else if (size == 0L...
## Risk Assessment Assuming infinite heap space can result in denial of service . Rule Severity Likelihood Detectable Repairable Priority Level MSC05-J Low Probable No No P2 L3 Related Vulnerabilities The Apache Geronimo bug described by GERONIMO-4224 results in an OutOfMemoryError exception thrown by the WebAccessLogV...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,806
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487806
2
49
MSC06-J
Do not modify the underlying collection when an iteration is in progress
According to the Java API documentation [ API 2014 ] for the Iterator.remove() method: The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. Concurrent modification in single-threaded programs is usually a res...
class BadIterate { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); Iterator iter = list.iterator(); while (iter.hasNext()) { String s = (String)iter.next(); if (s.equals("one")) { list.remove(s); ...
// ... if (s.equals("one")) { iter.remove(); } // ... List<Widget> widgetList = Collections.synchronizedList(new ArrayList<Widget>()); public void widgetOperation() { synchronized (widgetList) { // Client-side locking for (Widget w : widgetList) { doSomething(w); } } } List<Widget> widgetLis...
## Risk Assessment Modifying a Collection while iterating over it results in undefined behavior. Rule Severity Likelihood Detectable Repairable Priority Level MSC06-J Low Probable No No P2 L3 Automated Detection Some static analysis tools can detect cases where an iterator is being used after the source container of th...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,675
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487675
2
49
MSC07-J
Prevent multiple instantiations of singleton objects
The singleton design pattern's intent is succinctly described by the seminal work of Gamma and colleagues [ Gamma 1995 ]: Ensure a class only has one instance, and provide a global point of access to it. Because there is only one singleton instance, "any instance fields of a Singleton will occur only once per class, ju...
class MySingleton { private static MySingleton instance; protected MySingleton() { instance = new MySingleton(); } public static MySingleton getInstance() { return instance; } } class MySingleton { private static MySingleton instance; private MySingleton() { // Private construc...
class MySingleton { private static final MySingleton instance = new MySingleton(); private MySingleton() { // Private constructor prevents instantiation by untrusted callers } public static MySingleton getInstance() { return instance; } } class MySingleton { private static MySingleton ins...
## Risk Assessment Using improper forms of the Singleton design pattern may lead to creation of multiple instances of the singleton and violate the expected contract of the class. Rule Severity Likelihood Detectable Repairable Priority Level MSC07-J Low Unlikely Yes No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,652
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487652
2
49
MSC08-J
Do not store nonserializable objects as attributes in an HTTP session
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 nonserializable objects are stored as attributes in an HTTP session then ... Rule Severity Likelihood Detectable Repairable Priority Level MSC08-J Low Probable No No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,366
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487366
2
49
MSC09-J
For OAuth, ensure (a) [relying party receiving user's ID in last step] is same as (b) [relying party the access token was granted to].
Under Construction This guideline is under construction. For OAuth, ensure the relying party receiving the user's ID in the last protocol step is the same as the relying party that the access token was granted to .
TBD ## Noncompliant Code Example ## This noncompliant code example shows an application that #FFCCCC TBD
TBD ## Compliant Solution ## In this compliant solution the application #CCCCFF TBD
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level DRD26-J Medium Probable No No P4 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,365
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487365
2
49
MSC10-J
Do not use OAuth 2.0 implicit grant (unmodified) for authentication
Do not use OAuth 2.0 implicit grant (unmodified) for authentication. It can be used to securely authorize, but not to authenticate. Under Construction This guideline is under construction.
TBD ## Noncompliant Code Example ## This noncompliant code example shows an application that #FFCCCC TBD
TBD ## Compliant Solution ## In this compliant solution the application #CCCCFF TBD
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level DRD28-J High Unlikely No No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,641
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487641
2
49
MSC11-J
Do not let session information leak within a servlet
Java servlets often must store information associated with each client that connects to them. Using member fields in the javax.servlet.http.HttpServlet to store information specific to individual clients is a common, simple practice. However, doing so is a mistake for the following reasons: In any Java servlet containe...
public class SampleServlet extends HttpServlet { private String lastAddr = "nobody@nowhere.com"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.prin...
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 emailAddr = request.getP...
## Risk Assessment Use of nonstatic member fields in a servlet can result in information leakage. Rule Severity Likelihood Detectable Repairable Priority Level MSC11-J Medium Likely No No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 49. Miscellaneous (MSC)
java
88,487,797
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487797
3
49
MSC50-J
Minimize the scope of the @SuppressWarnings annotation
When the compiler detects potential type-safety issues arising from mixing raw types with generic code, it issues unchecked warnings , including unchecked cast warnings, unchecked method invocation warnings, unchecked generic array creation warnings , and unchecked conversion warnings [ Bloch 2008 ]. It is permissible ...
@SuppressWarnings("unchecked") class Legacy { Set s = new HashSet(); public final void doLogic(int a, char c) { s.add(a); s.add(c); // Type-unsafe operation, ignored } } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) { // Produces unchecked warning   return (T...
class Legacy { @SuppressWarnings("unchecked") Set s = new HashSet(); public final void doLogic(int a,char c) { s.add(a); // Produces unchecked warning s.add(c); // Produces unchecked warning } } // ... @SuppressWarnings("unchecked") T[] result = (T[]) Arrays.copyOf(elements, size, a.getClass()); return...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,456
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487456
3
49
MSC51-J
Do not place a semicolon immediately following an if, for, or while condition
Do not use a semicolon after an if , for , or while condition because it typically indicates programmer error and can result in unexpected behavior. Noncompliant Code Example
if (a == b); { /* ... */ } if (a == b) { /* ... */ } ## In this noncompliant code example, a semicolon is used immediately following anifcondition: #FFcccc if (a == b); { /* ... */ } The statements in the apparent body of the if statement are always evaluated regardless of the result of the condition expression. ...
null
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,892
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487892
3
49
MSC52-J
Finish every set of statements associated with a case label with a break statement
A switch block comprises several case labels and an optional but highly recommended default label. Statements that follow each case label must end with a break statement, which is responsible for transferring the control to the end of the switch block. When omitted, the statements in the subsequent case label are execu...
int card = 11; switch (card) { /* ... */ case 11: System.out.println("Jack"); case 12: System.out.println("Queen"); break; case 13: System.out.println("King"); break; default: System.out.println("Invalid Card"); break; } ## Noncompliant Code Example In this noncompliant co...
int card = 11; switch (card) { /* ... */ case 11: System.out.println("Jack"); break; case 12: System.out.println("Queen"); break; case 13: System.out.println("King"); break; default: System.out.println("Invalid Card"); break; } ## Compliant Solution ## This compliant s...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,748
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487748
3
49
MSC53-J
Carefully design interfaces before releasing them
Interfaces are used to group all the methods that a class promises to publicly expose. The implementing classes are obliged to provide concrete implementations for all of these methods. Interfaces are a necessary ingredient of most public APIs; once released, flaws can be hard to fix without breaking any code that impl...
public interface User { boolean authenticate(String username, char[] password); void subscribe(int noOfDays); void freeService(); // Introduced after the class is publicly released } public interface User { boolean authenticate(String username, char[] password); void subscribe(int noOfDays); void freeServi...
public interface User { boolean authenticate(String username, char[] password); } public interface PremiumUser extends User { void subscribe(int noOfDays); } public interface FreeUser { void freeService(); } class Client implements User { public void freeService() { throw new AbstractMethodError(); } ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,785
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487785
3
49
MSC54-J
Avoid inadvertent wrapping of loop counters
Unless coded properly, a while or for loop may execute forever or until the counter wraps around and reaches its final value. (See NUM00-J. Detect or prevent integer overflow .) This problem may result from incrementing or decrementing a loop counter by more than one and then testing for equality to a specified value t...
for (i = 1; i != 10; i += 2) { // ... } for (i = 1; i != 10; i += 5) { // ... } for (i = 1; i <= Integer.MAX_VALUE; i++) { // ... } for (i = 0; i <= Integer.MAX_VALUE - 1; i += 2) { // ... } ## Noncompliant Code Example ## This noncompliant code example appears to iterate five times: #FFCCCC for (i = 1; i !...
for (i = 1; i == 11; i += 2) { // ... } for (i = 1; i <= 10; i += 2) { // ... } for (i = 1; i != Integer.MAX_VALUE; i++) { // ... } i = 0; do { i++ // ... } while (i != Integer.MAX_VALUE); for (i = 0; i <= Integer.MAX_VALUE - 2; i += 2) { // ... } ## Compliant Solution One solution is to simply ensure ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,379
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487379
3
49
MSC55-J
Use comments consistently and in a readable fashion
Mixing the use of traditional or block comments (starting with /* and ending with */ ) and end-of-line comments (from // to the end of the line) can lead to misleading and confusing code, which may result in errors.
// */ /* Comment, not syntax error */ f = g/**//h; /* Equivalent to f = g / h; */ /*//*/ l(); /* Equivalent to l(); */ m = n//**/o + p; /* Equivalent to m = n + p; */ a = b //*divisor:*/c + d; /* Equivalent to a = b + d; */ /* Comment with ...
// Nice simple comment int i; // Counter if (false) { /* Use of critical security method no * longer necessary, for now */ /* NOTREACHED */ security_critical_method(); /* Some other comment */ } ## Compliant Solution Use a consistent style of commenting: #ccccff // Nice simple comment int i; //...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,668
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487668
3
49
MSC56-J
Detect and remove superfluous code and values
Superfluous code and values may occur in the form of dead code, code that has no effect, and unused values in program logic. Code that is never executed is known as dead code . Typically, the presence of dead code indicates that a logic error has occurred as a result of changes to a program or to the program's environm...
public int func(boolean condition) { int x = 0; if (condition) { x = foo(); /* Process x */ return x; } /* ... */ if (x != 0) { /* This code is never executed */ } return x; } public int string_loop(String str) { for (int i=0; i < str.length(); i++) { /* ... */ if (i == str.leng...
int func(boolean condition) { int x = 0; if (condition) { x = foo(); /* Process x */ } /* ... */ if (x != 0) { /* This code is now executed */ } return 0; } public int string_loop(String str) { for (int i=0; i < str.length(); i++) { /* ... */ if (i == str.length()-1) { /* This...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,567
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487567
3
49
MSC57-J
Strive for logical completeness
`Software vulnerabilities can result when a programmer fails to consider all possible data states.
if (a == b) { /* ... */ } else if (a == c) { /* ... */ } switch(x) { case 0: foo(); break; case 1: bar(); break; } final static int ORIGIN_YEAR = 1980; /* Number of days since January 1, 1980 */ public void convertDays(long days){ int year = ORIGIN_YEAR; /* ... */ while (days > 365) { if (IsLe...
if (a == b) { /* ... */ } else if (a == c) { /* ... */ } else { /* Handle error condition */ } switch(x) { case 0: foo(); break; case 1: bar(); break; default: /* Handle error */ break; } final static int ORIGIN_YEAR = 1980; /* Number of days since January 1, 1980 */ public void convertDays(long days){ ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,863
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487863
3
49
MSC58-J
Prefer using iterators over enumerations
According to the Java API Interface Enumeration<E> documentation [ API 2013 ], An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. As an example, the following code uses an Enumeration to ...
class BankOperations { private static void removeAccount(Vector<String> v, String name) { Enumeration e = v.elements(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equals(name)) { v.remove(name); // Second Harry is not removed } } // ...
class BankOperations { private static void removeAccount(Vector v, String name) { Iterator i = v.iterator(); while (i.hasNext()) { String s = (String) i.next(); if (s.equals(name)) { i.remove(); // Correctly removes all instances of the name Harry } } // Display curre...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,916
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487916
3
49
MSC59-J
Limit the lifetime of sensitive data
Sensitive data in memory can be vulnerable to compromise. An adversary who can execute code on the same system as an application may be able to access such data if the application Uses objects to store sensitive data whose contents are not cleared or garbage-collected after use Has memory pages that can be swapped out ...
class Password { public static void main (String args[]) throws IOException { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String username = c.readLine("Enter your user name: "); String password = c.readLine("Enter your password: ...
class Password { public static void main (String args[]) throws IOException { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String username = c.readLine("Enter your user name: "); char[] password = c.readPassword("Enter your p...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,376
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487376
3
49
MSC60-J
Do not use assertions to verify the absence of runtime errors
Diagnostic tests can be incorporated into programs by using the assert statement. Assertions are primarily intended for use during debugging and are often turned off before code is deployed by using the -disableassertions (or -da ) Java runtime switch. Consequently, assertions should be used to protect against incorrec...
BufferedReader br; // Set up the BufferedReader br String line; // ... line = br.readLine(); assert line != null; ## Noncompliant Code Example ## This noncompliant code example uses theassertstatement to verify that input was available: #FFcccc BufferedReader br; // Set up the BufferedReader br String line; // .....
BufferedReader br; // Set up the BufferedReader br String line; // ... line = br.readLine(); if (line == null) { // Handle error } ## Compliant Solution ## This compliant solution demonstrates the recommended way to detect and handle unavailability of input: #ccccff BufferedReader br; // Set up the BufferedRead...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,812
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487812
3
49
MSC61-J
Do not use insecure or weak cryptographic algorithms
Security-intensive applications must avoid use of insecure or weak cryptographic primitives to protect sensitive information. The computational capacity of modern computers permits circumvention of such cryptography via brute-force attacks. For example, the Data Encryption Standard (DES) encryption algorithm is conside...
SecretKey key = KeyGenerator.getInstance("DES").generateKey(); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); // Encode bytes as UTF8; strToBeEncrypted contains // the input string that is to be encrypted byte[] encoded = strToBeEncrypted.getBytes("UTF8"); // Perform encryptio...
import java.util.Arrays; import javax.crypto.*; import javax.crypto.spec.*; import java.security.*; class Msc61 { public static final int GCM_TAG_LENGTH = 16; public static final int GCM_IV_LENGTH = 12; public static SecretKey generateKey() { try { KeyGenerator kgen = KeyGenerator.getI...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,605
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487605
3
49
MSC62-J
Store passwords using a hash function
Programs that store passwords as cleartext (unencrypted text data) risk exposure of those passwords in a variety of ways. Although programs generally receive passwords from users as cleartext, they should ensure that the passwords are not stored as cleartext. An acceptable technique for limiting the exposure of passwor...
public final class Password { private void setPassword(byte[] pass) throws Exception { // Arbitrary encryption scheme byte[] encrypted = encrypt(pass); clearArray(pass); // Encrypted password to password.bin saveBytes(encrypted,"password.bin"); clearArray(encrypted); } boolean checkP...
## Compliant Solution ## First, this compliant solution usesbytearray to store the password. In both the setPassword() and checkPassword() methods, the cleartext representation of the password is erased immediately after it is converted into a hash value. Consequently, attackers must work harder to retrieve the clearte...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,659
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487659
3
49
MSC63-J
Ensure that SecureRandom is properly seeded
Random number generation depends on a source of entropy such as signals, devices, or hardware inputs. Secure random number generation is also addressed by . The java.security.SecureRandom class is widely used for generating cryptographically strong random numbers. According to the java.security file present in the Java...
SecureRandom random = new SecureRandom(String.valueOf(new Date().getTime()).getBytes()); ## Noncompliant Code Example ## This noncompliant code example constructs a secure random number generator that is seeded with the specified seed bytes: #ffcccc java SecureRandom random = new SecureRandom(String.valueOf(new Date()...
byte[] randomBytes = new byte[128]; SecureRandom random = new SecureRandom(); random.nextBytes(randomBytes); ## Compliant Solution Prefer the no-argument constructor of SecureRandom that uses the system-specified seed value to generate a 128-byte-long random number. #ccccff java byte[] randomBytes = new byte[128]; Sec...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 49. Miscellaneous (MSC)
java
88,487,740
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487740
2
3
NUM00-J
Detect or prevent integer overflow
Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to The Java Language Specification (JLS), §4.2.2, "Integer Operations" [ JLS 2015 ]: The built-in integer operators do not indicate overflow or underflow in any way. Integer operators c...
public static int multAccum(int oldAcc, int newVal, int scale) { // May result in overflow return oldAcc + (newVal * scale); } class InventoryManager { private final AtomicInteger itemsInInventory = new AtomicInteger(100); //... public final void nextItem() { itemsInInventory.getAndIncrement(); } } #...
public static int multAccum(int oldAcc, int newVal, int scale) { return safeAdd(oldAcc, safeMultiply(newVal, scale)); } public static int multAccum(int oldAcc, int newVal, int scale) { return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale)); } public static long intRangeCheck(long value) { if ((value < ...
## Risk Assessment Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior. Rule Severity Likelihood Detectable Repairable Priority Level NUM00-J Medium Unlikely No No P2 L3 Automated Detection Automated detection of ...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,399
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487399
2
3
NUM01-J
Do not perform bitwise and arithmetic operations on the same data
Integer variables are frequently intended to represent either a numeric value or a bit collection. Numeric values must be exclusively operated on using arithmetic operations, whereas bit collections must be exclusively operated on using bitwise operations. Bitwise operators include the unary operator ~ and the binary o...
int compute(int x) { x += (x << 2) + 1; return x; } // ... int x = compute(50); int compute(int x) { int y = x << 2; x += y + 1; return x; } // ... int x = compute(50); int compute(int x) { x >>>= 2; return x; } // ... int x = compute(-50); int compute(int x) { x >>= 2; return x; } // ... int x...
int compute(int x) { return 5 * x + 1; } // ... int x = compute(50); int compute(int x) { x /= 4 return x; } // ... int x = compute(-50); byte[] b = new byte[] {-1, -1, -1, -1}; int result = 0; for (int i = 0; i < 4; i++) { result = ((result << 8) | (b[i] & 0xff)); } ## Compliant Solution (Left Shift) In t...
## Risk Assessment Performing bitwise manipulation and arithmetic operations on the same variable obscures the programmer's intentions and reduces readability. Consequently, it is more difficult for a security auditor or maintainer to determine which checks must be performed to eliminate security flaws and ensure data ...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,433
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487433
2
3
NUM02-J
Ensure that division and remainder operations do not result in divide-by-zero errors
Division and remainder operations performed on integers are susceptible to divide-by-zero errors. Consequently, the divisor in a division or remainder operation on integer types must be checked for zero prior to the operation. Division and remainder operations performed on floating-point numbers are not subject to this...
long num1, num2, result; /* Initialize num1 and num2 */ result = num1 / num2; long num1, num2, result; /* Initialize num1 and num2 */ result = num1 % num2; ## Noncompliant Code Example (Division) The result of the / operator is the quotient from the division of the first arithmetic operand by the second arithmeti...
long num1, num2, result; /* Initialize num1 and num2 */ if (num2 == 0) { // Handle error } else { result = num1 / num2; } long num1, num2, result; /* Initialize num1 and num2 */ if (num2 == 0) { // Handle error } else { result = num1 % num2; } ## Compliant Solution (Division) ## This compliant solution te...
## Risk Assessment A division or remainder by zero can result in abnormal program termination and denial-of-service (DoS). Rule Severity Likelihood Detectable Repairable Priority Level NUM02-J Low Likely No Yes P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,757
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487757
2
3
NUM03-J
Use integer types that can fully represent the possible range of unsigned data
The only unsigned primitive integer type in Java is the 16-bit char data type; all of the other primitive integer types are signed. To interoperate with native languages, such as C or C++, that use unsigned types extensively, any unsigned values must be read and stored into a Java integer type that can fully represent ...
public static int getInteger(DataInputStream is) throws IOException { return is.readInt(); } ## Noncompliant Code Example This noncompliant code example uses a generic method for reading integer data without considering the signedness of the source. It assumes that the data read is always signed and treats the most...
public static long getInteger(DataInputStream is) throws IOException { return is.readInt() & 0xFFFFFFFFL; // Mask with 32 one-bits } ## Compliant Solution This compliant solution requires that the values read are 32-bit unsigned integers. It reads an unsigned integer value using the readInt() method. The readInt() m...
## Risk Assessment Treating unsigned data as though it were signed produces incorrect values and can lead to lost or misinterpreted data. Rule Severity Likelihood Detectable Repairable Priority Level NUM03-J Low Unlikely No No P1 L3 Automated Detection Automated detection is infeasible in the general case.
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,676
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487676
2
3
NUM04-J
Do not use floating-point numbers if precise computation is required
Deprecated This rule may be deprecated and replaced by a similar guideline. 06/28/2014 -- Version 1.0 The Java language provides two primitive floating-point types, float and double , which are associated with the single-precision 32-bit and double-precision 64-bit format values and operations specified by IEEE 754 [ I...
double dollar = 1.00; double dime = 0.10; int number = 7; System.out.println( "A dollar less " + number + " dimes is $" + (dollar - number * dime)  ); A dollar less 7 dimes is $0.29999999999999993 ## Noncompliant Code Example ## This noncompliant code example performs some basic currency calculations: #FFcccc doubl...
int dollar = 100; int dime = 10; int number = 7; System.out.println( "A dollar less " + number + " dimes is $0." + (dollar - number * dime) ); A dollar less 7 dimes is $0.30 import java.math.BigDecimal; BigDecimal dollar = new BigDecimal("1.0"); BigDecimal dime = new BigDecimal("0.1"); int number = 7; System.out.p...
## Risk Assessment Using floating-point representations when precise computation is required can result in a loss of precision and incorrect values. Rule Severity Likelihood Detectable Repairable Priority Level NUM04-J Low Probable No No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,875
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487875
2
3
NUM07-J
Do not attempt comparisons with NaN
According to The Java Language Specification (JLS), §4.2.3, "Floating-Point Types, Formats, and Values" [ JLS 2015 ]: NaN (not-a-number) is unordered, so the numerical comparison operators < , <= , > , and >= return false if either or both operands are NaN . The equality operator == returns false if either operand is N...
public class NaNComparison { public static void main(String[] args) { double x = 0.0; double result = Math.cos(1/x); // Returns NaN if input is infinity if (result == Double.NaN) { // Comparison is always false! System.out.println("result is NaN"); } } } ## Noncompliant Code Example This nonc...
public class NaNComparison { public static void main(String[] args) { double x = 0.0; double result = Math.cos(1/x); // Returns NaN when input is infinity if (Double.isNaN(result)) { System.out.println("result is NaN"); } } } ## Compliant Solution ## This compliant solution uses the metho...
## Risk Assessment Comparisons with NaN can lead to unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level NUM07-J Low Probable Yes Yes P6 L2 Automated Detection Automated detection of comparison with NaN is straightforward. Sound determination of whether the possibility of an unordered resul...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,866
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487866
2
3
NUM08-J
Check floating-point inputs for exceptional values
Floating-point numbers can take on three exceptional values: infinity , -infinity , and NaN (not-a-number). These values are produced as a result of exceptional or otherwise unresolvable floating-point operations, such as division by zero. These exceptional values can also be obtained directly from user input through m...
double currentBalance; // User's cash balance void doDeposit(String userInput) { double val = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { // Handle input format error } if (val >= Double.MAX_VALUE - currentBalance) { // Handle range error } currentBalance +...
double currentBalance; // User's cash balance void doDeposit(String userInput){ double val = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { // Handle input format error } if (Double.isInfinite(val)){ // Handle infinity error } if (Double.isNaN(val)) { // H...
## Risk Assessment Incorrect or missing validation of floating-point input can result in miscalculations and unexpected results, possibly leading to inconsistent program behavior and denial of service . Rule Severity Likelihood Detectable Repairable Priority Level NUM08-J Low Probable No Yes P4 L3 Automated Detection A...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,688
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487688
2
3
NUM09-J
Do not use floating-point variables as loop counters
Floating-point variables must not be used as loop counters. Limited-precision IEEE 754 floating-point types cannot represent All simple fractions exactly. All decimals precisely, even when the decimals can be represented in a small number of digits. All digits of large values, meaning that incrementing a large floating...
for (float x = 0.1f; x <= 1.0f; x += 0.1f) { System.out.println(x); } for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { /* ... */ } ## Noncompliant Code Example This noncompliant code example uses a floating-point variable as a loop counter. The decimal number 0.1 cannot be precisely represented as a f...
for (int count = 1; count <= 10; count += 1) { float x = count/10.0f; System.out.println(x); } for (int count = 1; count <= 10; count += 1) { double x = 100000000.0 + count; /* ... */ } ## Compliant Solution ## This compliant solution uses an integer loop counter from which the desired floating-point value is...
## Risk Assessment Using floating-point loop counters can lead to unexpected behavior. Rule Severity Likelihood Detectable Repairable Priority Level NUM09-J Low Probable Yes No P4 L3 Automated Detection Automated detection of floating-point loop counters is straightforward. Tool Version Checker Description JAVA.LOOP.CT...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,827
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487827
2
3
NUM10-J
Do not construct BigDecimal objects from floating-point literals
Literal decimal floating-point numbers cannot always be precisely represented as an IEEE 754 floating-point value. Consequently, the BigDecimal(double val) constructor must not be passed a floating-point literal as an argument when doing so results in an unacceptable loss of precision.
// Prints 0.1000000000000000055511151231257827021181583404541015625 // when run in FP-strict mode System.out.println(new BigDecimal(0.1)); ## Noncompliant Code Example This noncompliant code example passes a double value to the BigDecimal constructor. Because the decimal literal 0.1 cannot be precisely represented b...
// Prints 0.1 // when run in FP-strict mode System.out.println(new BigDecimal("0.1")); ## Compliant Solution This compliant solution passes the decimal literal as a String so that the BigDecimal(String val) constructor is invoked and the precision is preserved: #ccccff // Prints 0.1 // when run in FP-strict mode Syst...
## Risk Assessment Using the BigDecimal(double val) constructor with decimal floating-point literals can lead to loss of precision. Rule Severity Likelihood Detectable Repairable Priority Level NUM10-J Low Probable Yes Yes P6 L2 Automated Detection Automated detection is straightforward. Tool Version Checker Descriptio...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,693
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487693
2
3
NUM11-J
Do not compare or inspect the string representation of floating-point values
String representations of floating-point numbers should not be compared or inspected. If they are used, significant care needs to be taken to ensure expected behavior.
int i = 1; String s = Double.valueOf(i / 10000.0).toString(); if (s.equals("0.0001")) { // ... } ## Noncompliant Code Example (String Comparison) This noncompliant code example incorrectly compares the decimal string literal generated by 1/10000.0 . The string produced is not 0.0001 but rather 1.0E-4 . #FFCCCC int i...
int i = 1; BigDecimal d = new BigDecimal(Double.valueOf(i / 10000.0).toString()); if (d.compareTo(new BigDecimal("0.0001")) == 0) { // ... } ## Compliant Solution (String Comparison) This compliant solution uses the BigDecimal class to avoid the conversion into scientific notation. It then performs a numeric compari...
## Risk Assessment Comparing or inspecting the string representation of floating-point values may have unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level NUM11-J Low Likely Yes Yes P9 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,454
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487454
2
3
NUM12-J
Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data
Conversions of numeric types to narrower types can result in lost or misinterpreted data if the value of the wider type is outside the range of values of the narrower type. Consequently, all narrowing conversions must be guaranteed safe by range-checking the value before conversion. Java provides 22 possible narrowing ...
class CastAway { public static void main(String[] args) { int i = 128; workWith(i); } public static void workWith(int i) { byte b = (byte) i; // b has value -128 // Work with b } } float i = Float.MIN_VALUE; float j = Float.MAX_VALUE; short b = (short) i; short c = (short) j; double i = Doub...
class CastAway { public static void workWith(int i) { // Check whether i is within byte range if ((i < Byte.MIN_VALUE) || (i > Byte.MAX_VALUE)) { throw new ArithmeticException("Value is out of range"); } byte b = (byte) i; // Work with b } } class CastAway { public static void workW...
## Risk Assessment Casting a numeric value to a narrower type can result in information loss related to the sign and magnitude of the numeric value. As a result, data can be misrepresented or interpreted incorrectly. Rule Severity Likelihood Detectable Repairable Priority Level NUM12-J Low Unlikely Yes Yes P3 L3 Automa...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,723
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487723
2
3
NUM13-J
Avoid loss of precision when converting primitive integers to floating-point
The following 19 specific conversions on primitive types are called the widening primitive conversions : byte to short , int , long , float , or double short to int , long , float , or double char to int , long , float , or double int to long , float , or double long to float or double float to double Conversion from i...
strictfp class WideSample { public static int subFloatFromInt(int op1, float op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subFloatFromInt(1234567890, 1234567890); // This prints -46, not 0, as may be expected System.out.println(result); } } ## Noncomp...
strictfp class WideSample { public static int subFloatFromInt(int op1, float op2) { return op1 - (int)op2; } public static void main(String[] args) throws ArithmeticException { int op1 = 1234567890; int op2 = 1234567890; // Check op2 before implicit cast to float. The float significand can store...
## Risk Assessment Converting integer values to floating-point types whose mantissa has fewer bits than the original integer value can result in a rounding error. Rule Severity Likelihood Detectable Repairable Priority Level NUM13-J Low Unlikely No No P1 L3 Automated Detection Automatic detection of casts that can lose...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,381
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487381
2
3
NUM14-J
Use shift operators correctly
The shift operators in Java have the following properties, according to The Java Language Specification (JLS), §15.19, "Shift Operators" [ JLS 2015 ]: The >> right shift is an arithmetic shift; the >>> right shift is a logical shift. The types boolean , float , and double cannot use the bit-shifting operators. When the...
public int doOperation(int exp) { // Compute 2^exp int temp = 1 << exp; // Do other processing return temp; } ## This noncompliant code example fails to perform explicit range-checking to avoid truncation of the shift distance: #ffcccc public int doOperation(int exp) { // Compute 2^exp int temp = 1 << exp; // ...
public int doOperation(int exp) throws ArithmeticException { if ((exp < 0) || (exp >= 32)) { throw new ArithmeticException("Exponent out of range"); } // Safely compute 2^exp int temp = 1 << exp; // Do other processing return temp; } int i = 0; while ((-1 << i) != 0) { i++; } for (int val = -1; val ...
## Risk Assessment Incorrect use of shift operators can lead to unanticipated results, causing erratic control flow or unanticipated program behavior. Rule Severity Likelihood Detectable Repairable Priority Level NUM14-J Low Probable No No P2 L3 Automated Detection Tool Version Checker Description PVS-Studio V6034
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 03. Numeric Types and Operations (NUM)
java
88,487,682
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487682
3
3
NUM50-J
Convert integers to floating point for floating-point operations
Incautious use of integer arithmetic to calculate a value for assignment to a floating-point variable can lead to loss of information. For example, integer arithmetic always produces integral results, discarding information about any possible fractional remainder. Furthermore, there can be loss of precision when conver...
short a = 533; int b = 6789; long c = 4664382371590123456L; float d = a / 7; // d is 76.0 (truncated) double e = b / 30; // e is 226.0 (truncated) double f = c * 2; // f is -9.1179793305293046E18 // because of integer overflow int a = 60070; int b = 57750; double value = Math.ceil(a/b); ##...
short a = 533; int b = 6789; long c = 4664382371590123456L; float d = a / 7.0f; // d is 76.14286 double e = b / 30.; // e is 226.3 double f = (double)c * 2; // f is 9.328764743180247E18 short a = 533; int b = 6789; long c = 4664382371590123456L; float d = a; double e = b; double f = c; d /= 7; // d is ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 03. Numeric Types and Operations (NUM)
java
88,487,844
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487844
3
3
NUM51-J
Do not assume that the remainder operator always returns a nonnegative result for integral operands
The Java Language Specification (JLS), §15.17.3, "Remainder Operator %" [ JLS 2013 ], states, The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a . This identity holds even in the special case that the dividend is t...
private int SIZE = 16; public int[] hash = new int[SIZE]; public int lookup(int hashKey) { return hash[hashKey % SIZE]; } ## Noncompliant Code Example ## This noncompliant code example uses the integerhashKeyas an index into thehasharray. #FFcccc private int SIZE = 16; public int[] hash = new int[SIZE]; public in...
// Method imod() gives nonnegative result private int SIZE = 16; public int[] hash = new int[SIZE]; private int imod(int i, int j) { int temp = i % j; return (temp < 0) ? -temp : temp; // Unary minus will succeed without overflow // because temp cannot be Integer.MIN_VALUE } public int lookup(int hashKey)...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 03. Numeric Types and Operations (NUM)
java
88,487,568
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487568
3
3
NUM52-J
Be aware of numeric promotion behavior
Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. When using arithmetic operators with mixed operand sizes, narrower operands are promoted to the type of the wider operand. ## Promotion Rules The Java Language Specification (JLS), §5.6, "Nu...
int big = 1999999999; float one = 1.0f; // Binary operation, loses precision because of implicit cast System.out.println(big * one); byte[] b = new byte[4]; int result = 0; for (int i = 0; i < 4; i++) { result = (result << 8) | b[i]; } int x = 2147483642; // 0x7ffffffa x += 1.0f; // x contains 2147483647...
int big = 1999999999; double one = 1.0d; // Double instead of float System.out.println(big * one); byte[] b = new byte[4]; int result = 0; for (int i = 0; i < 4; i++) { result = (result << 8) | (b[i] & 0xff); } double x = 2147483642; // 0x7ffffffa x += 1.0; // x contains 2147483643.0 (0x7ffffffb.0) as expected i...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 03. Numeric Types and Operations (NUM)
java
88,487,805
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487805
3
3
NUM53-J
Use the strictfp modifier for floating-point calculation consistency across platforms
The Java language allows platforms to use available floating-point hardware that can provide extended floating-point support with exponents that contain more bits than the standard Java primitive type double (in the absence of the strictfp modifier). Consequently, these platforms can represent a superset of the values ...
class Example { public static void main(String[] args) { double d = Double.MAX_VALUE; System.out.println("This value \"" + ((d * 1.1) / 1.1) + "\" cannot be represented as double."); } } class Example { double d = 0.0; public void example() { float f = Float.MAX_VALUE; float g = Float.MAX_VALU...
strictfp class Example { public static void main(String[] args) { double d = Double.MAX_VALUE; System.out.println("This value \"" + ((d * 1.1) / 1.1) + "\" cannot be represented as double."); } } strictfp class Example { double d = 0.0; public void example() { float f = Float.MAX_VALUE; float ...
## Risk Assessment Failure to use the strictfp modifier can result in nonportable, implementation-defined behavior with respect to the behavior of floating-point operations. Rule Severity Likelihood Detectable Repairable Priority Level NUM53-J Low Unlikely No No P1 L3
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 03. Numeric Types and Operations (NUM)
java
88,487,390
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487390
3
3
NUM54-J
Do not use denormalized numbers
Java uses the IEEE 754 standard for floating-point representation. In this representation, floats are encoded using 1 sign bit, 8 exponent bits, and 23 mantissa bits. Doubles are encoded and used exactly the same way, except they use 1 sign bit, 11 exponent bits, and 52 mantissa bits. These bits encode the values of s,...
float x = 1/3.0f; System.out.println("Original : " + x); x = x * 7e-45f; System.out.println("Denormalized: " + x); x = x / 7e-45f; System.out.println("Restored : " + x); Original : 0.33333334 Denormalized: 2.8E-45 Restored : 0.4 ## Noncompliant Code Example This noncompliant code example attempts to reduc...
double x = 1/3.0; System.out.println("Original : " + x); x = x * 7e-45; System.out.println("Normalized: " + x); x = x / 7e-45; System.out.println("Restored : " + x); Original : 0.3333333333333333 Normalized: 2.333333333333333E-45 Restored : 0.3333333333333333 ## Compliant Solution Do not use code that could use d...
## Risk Assessment Floating-point numbers are an approximation; denormalized floating-point numbers are a less precise approximation. Use of denormalized numbers can cause unexpected loss of precision, possibly leading to incorrect or unexpected results. Although the severity for violations of this rule is low, applica...
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 03. Numeric Types and Operations (NUM)
java
88,487,726
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487726
2
5
OBJ01-J
Limit accessibility of fields
Invariants cannot be enforced for public nonfinal fields or for final fields that reference a mutable object. A protected member of an exported (non-final) class represents a public commitment to an implementation detail. Attackers can manipulate such fields to violate class invariants , or they may be corrupted by mul...
public class Widget { public int total; // Number of elements void add() { if (total < Integer.MAX_VALUE) { total++; // ... } else { throw new ArithmeticException("Overflow"); } } void remove() { if (total > 0) { total--; // ... } else { th...
public class Widget { private int total; // Declared private public int getTotal () { return total; } // Definitions for add() and remove() remain the same } private static final HashMap<Integer, String> hm = new HashMap<Integer, String>(); public static String getElement(int key) { return hm.get(key...
## Risk Assessment Failing to limit field accessibility can defeat encapsulation, allow attackers to manipulate fields to violate class invariants , or allow these fields to be corrupted as the result of concurrent accesses from multiple threads. Rule Severity Likelihood Detectable Repairable Priority Level OBJ01-J Med...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,814
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487814
2
5
OBJ02-J
Preserve dependencies in subclasses when changing superclasses
Developers often separate program logic across multiple classes or files to modularize code and to increase reusability. When developers modify a superclass (during maintenance, for example), the developer must ensure that changes in superclasses preserve all the program invariants on which the subclasses depend. Failu...
class Account { // Maintains all banking-related data such as account balance private double balance = 100; boolean withdraw(double amount) { if ((balance - amount) >= 0) { balance -= amount; System.out.println("Withdrawal successful. The balance is : " + balance); ...
class BankAccount extends Account { // ... @Override boolean overdraft() { // Override throw new IllegalAccessException(); } } // The CalendarImplementation object is a concrete implementation // of the abstract Calendar class // Class ForwardingCalendar public class ForwardingCalendar { private final Cale...
## Risk Assessment Modifying a superclass without considering the effect on subclasses can introduce vulnerabilities . Subclasses that are developed with an incorrect understanding of the superclass implementation can be subject to erratic behavior, resulting in inconsistent data state and mismanaged control flow. Also...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,793
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487793
2
5
OBJ03-J
Prevent heap pollution
Heap pollution occurs when a variable of a parameterized type references an object that is not of that parameterized type. (For more information on heap pollution, see The Java Language Specification (JLS), §4.12.2, "Variables of Reference Type" [ JLS 2015 ].) Mixing generically typed code with raw typed code is one co...
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 } } class ...
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)); } } class ListUtility {...
## Risk Assessment Mixing generic and nongeneric code can produce unexpected results and exceptional conditions. Rule Severity Likelihood Detectable Repairable Priority Level OBJ03-J Low Probable Yes No P4 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,893
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487893
2
5
OBJ04-J
Provide mutable classes with copy functionality to safely allow passing instances to untrusted code
Mutable classes allow code external to the class to alter their instance or class fields. Provide means for creating copies of mutable classes so that disposable instances of such classes can be passed to untrusted code . This functionality is useful when methods in other classes must create copies of the particular cl...
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } } ## Noncompliant Code Example In this noncompliant code example, MutableClass uses a mutable field date...
public final class MutableClass { // Copy constructor private final Date date; public MutableClass(MutableClass mc) { this.date = new Date(mc.date.getTime()); } public MutableClass(Date d) { this.date = new Date(d.getTime()); // Make defensive copy } public Date getDate() { return (Date) da...
## Risk Assessment Creating a mutable class without providing copy functionality can result in the data of its instance becoming corrupted when the instance is passed to untrusted code . Rule Severity Likelihood Detectable Repairable Priority Level OBJ04-J Low Likely No No P3 L3 Automated Detection Sound automated dete...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,737
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487737
2
5
OBJ05-J
Do not return references to private mutable class members
Returning references to internal mutable members of a class can compromise an application's security, both by breaking encapsulation and by providing the opportunity to corrupt the internal state of the class (whether accidentally or maliciously). As a result, programs must not return references to private mutable clas...
class MutableClass { private Date d; public MutableClass() { d = new Date(); } public Date getDate() { return d; } } class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for (int i = 0; i < date.length; i++) { date[i] = new Date(); } } p...
public Date getDate() { return (Date)d.clone(); } class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for(int i = 0; i < date.length; i++) { date[i] = new Date(); } } public Date[] getDate() { Date[] dates = new Date[date.length]; for (int i = 0;...
## Risk Assessment Returning references to internal object state (mutable or immutable) can render an application susceptible to information leaks and corruption of its objects' states, which consequently violates class invariants . Control flow can also be affected in some cases. Rule Severity Likelihood Detectable Re...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,709
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487709
2
5
OBJ06-J
Defensively copy mutable inputs and mutable internal components
A mutable input has the characteristic that its value may vary; that is, multiple accesses may see differing values. This characteristic enables potential attacks that exploit race conditions . For example, a time-of-check, time-of-use (TOCTOU) vulnerability may result when a field contains a value that passes validati...
public final class MutableDemo { // java.net.HttpCookie is mutable public void useMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // Check whether cookie has expired if (cookie.hasExpired()) { // Cookie is no longer valid; handle condition by...
public final class MutableDemo { // java.net.HttpCookie is mutable public void useMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // Create copy cookie = (HttpCookie)cookie.clone(); // Check whether cookie has expired if (cookie.hasExpired(...
## Risk Assessment Failing to create a copy of a mutable input may result in a TOCTOU vulnerability or expose internal mutable components to untrusted code . Rule Severity Likelihood Detectable Repairable Priority Level OBJ06-J Medium Probable No No P4 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,742
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487742
2
5
OBJ07-J
Sensitive classes must not let themselves be copied
Classes containing private, confidential, or otherwise sensitive data are best not copied. If a class is not meant to be copied, then failing to define copy mechanisms, such as a copy constructor, is insufficient to prevent copying. Java's object cloning mechanism allows an attacker to manufacture new instances of a cl...
class SensitiveClass { private char[] filename; private Boolean shared = false; SensitiveClass(String filename) { this.filename = filename.toCharArray(); } final void replace() { if (!shared) { for(int i = 0; i < filename.length; i++) { filename[i]= 'x' ;} } } final String get() ...
final class SensitiveClass { // ... } class SensitiveClass { // ... public final SensitiveClass clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } ## Compliant Solution (Final Class) The easiest way to prevent malicious subclasses is to d...
## Risk Assessment Failure to make sensitive classes noncopyable can permit violations of class invariants and provide malicious subclasses with the opportunity to exploit the code to create new instances of objects, even in the presence of the default security manager (in the absence of custom security checks). Rule S...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,719
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487719
2
5
OBJ08-J
Do not expose private members of an outer class from within a nested class
A nested class is any class whose declaration occurs within the body of another class or interface [ JLS 2015 ]. The use of a nested class is error prone unless the semantics are well understood. A common notion is that only the nested class may access the contents of the outer class. Not only does the nested class hav...
class Coordinates { private int x; private int y; public class Point { public void getPoint() { System.out.println("(" + x + "," + y + ")"); } } } class AnotherClass { public static void main(String[] args) { Coordinates c = new Coordinates(); Coordinates.Point p = c.new Point(); p...
class Coordinates { private int x; private int y; private class Point { private void getPoint() { System.out.println("(" + x + "," + y + ")"); } } } class AnotherClass { public static void main(String[] args) { Coordinates c = new Coordinates(); Coordinates.Point p = c.new Point(); ...
## Risk Assessment The Java language system weakens the accessibility of private members of an outer class when a nested inner class is present, which can result in an information leak. Rule Severity Likelihood Detectable Repairable Priority Level OBJ08-J Medium Probable No No P4 L3 Automated Detection Automated detect...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,800
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487800
2
5
OBJ09-J
Compare classes and not class names
In a Java Virtual Machine (JVM), "Two classes are the same class (and consequently the same type) if they are loaded by the same class loader and they have the same fully qualified name" [ JVMSpec 1999 ]. Two classes with the same name but different package names are distinct, as are two classes with the same fully qua...
// Determine whether object auth has required/expected class object if (auth.getClass().getName().equals( "com.application.auth.DefaultAuthenticationHandler")) { // ... } // Determine whether objects x and y have the same class name if (x.getClass().getName().equals(y.getClass().getName())) { // Objects ha...
// Determine whether object auth has required/expected class name if (auth.getClass() == com.application.auth.DefaultAuthenticationHandler.class) { // ... } // Determine whether objects x and y have the same class if (x.getClass() == y.getClass()) { // Objects have the same class } ## Compliant Solution This co...
## Risk Assessment Comparing classes solely using their names can allow a malicious class to bypass security checks and gain access to protected resources. Rule Severity Likelihood Detectable Repairable Priority Level OBJ09-J High Unlikely Yes No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,770
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487770
2
5
OBJ10-J
Do not use public static nonfinal fields
Client code can trivially access public static fields because access to such fields are not checked by a security manager. Furthermore, new values cannot be validated programmatically before they are stored in these fields. In the presence of multiple threads, nonfinal public static fields can be modified in inconsiste...
package org.apache.xpath.compiler; public class FunctionTable { public static FuncLoader m_functions; } FunctionTable.m_functions = new_table; class DataSerializer implements Serializable { public static long serialVersionUID = 1973473122623778747L; // ... } ## Noncompliant Code Example This noncompliant code...
public static final FuncLoader m_functions; // Initialize m_functions in a static initialization block class DataSerializer implements Serializable { private static final long serialVersionUID = 1973473122623778747L; } ## Compliant Solution ## This compliant solution declares theFuncLoaderstatic field final and tre...
## Risk Assessment Unauthorized modifications of public static variables can result in unexpected behavior and violation of class invariants . Furthermore, because static variables can be visible to code loaded by different class loaders when those class loaders are in the same delegation chain, such variables can be u...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,789
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487789
2
5
OBJ11-J
Be wary of letting constructors throw exceptions
An object is partially initialized if a constructor has begun building the object but has not finished. As long as the object is not fully initialized, it must be hidden from other classes. Other classes might access a partially initialized object from concurrently running threads. This rule is a specific instance of b...
public class BankOperations { public BankOperations() { if (!performSSNVerification()) { throw new SecurityException("Access Denied!"); } } private boolean performSSNVerification() { return false; // Returns true if data entered is valid, else false // Assume that the attacker...
public final class BankOperations { // ... } public class BankOperations { public final void finalize() { // Do nothing } } /* This is an example of a finalizer attack in serialization (deserialization of cyclic references) */ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io....
## Risk Assessment Allowing access to a partially initialized object can provide an attacker with an opportunity to resurrect the object before or during its finalization; as a result, the attacker can bypass security checks. Rule Severity Likelihood Detectable Repairable Priority Level OBJ11-J High Probable Yes No P12...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,382
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487382
2
5
OBJ12-J
Respect object-based annotations
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 object-based annotations are not respected then ... Rule Severity Likelihood Detectable Repairable Priority Level OBJ12-J Low Probable No No P2 L3
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,511
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487511
2
5
OBJ13-J
Ensure that references to mutable objects are not exposed
Do not expose references to mutable objects to client code. Never initialize such a field to a client-provided object reference or return the object reference from an accessor. Exposing a public static final object allows clients to modify the contents of the object (although they will not be able to change the object ...
public static final SomeType [] SOMETHINGS = { ... }; private static final SomeType [] SOMETHINGS = { ... }; public static final getSomethings() {return SOMETHINGS;} ## Noncompliant Code Example Suppose that SomeType is immutable. #FFCCCC public static final SomeType [] SOMETHINGS = { ... }; Even though SomeType is ...
private static final SomeType [] SOMETHINGS = { ... }; public static final SomeType [] somethings() { return SOMETHINGS.clone(); } private static final SomeType [] THE_THINGS = { ... }; public static final List<SomeType> SOMETHINGS = Collections.unmodifiableList(Arrays.asList(THE_THINGS)); ## Compliant Solution (...
## Risk Assessment Having a public static final array is a potential security risk because the array elements may be modified by a client. Rule Severity Likelihood Detectable Repairable Priority Level OBJ13-J Medium Likely Yes No P12 L1 Automated Detection Tool Version Checker Description Parasoft Jtest CERT.OBJ13.RMO ...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,820
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487820
2
5
OBJ14-J
Do not use an object that has been freed.
This rule is a stub. It was generated by a tool that warned about using a resource after a method is invoked on the resource which invalidates it.
## 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 OBJ14-J Medium Likely No No P6 L2
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 05. Object Orientation (OBJ)
java
88,487,851
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487851
3
5
OBJ50-J
Never confuse the immutability of a reference with that of the referenced object
Deprecated This guideline has been deprecated.  It has been merged with: OBJ01-J. Limit accessibility of fields 06/15/2015 -- Version 1.0 Similarly, a final method parameter obtains an immutable copy of the object reference . Again, this has no effect on the mutability of the referenced data.
class Point { private int x; private int y; Point(int x, int y) { this.x = x; this.y = y; } void set_xy(int x, int y) { this.x = x; this.y = y; } void print_xy() { System.out.println("the value x is: " + this.x); System.out.println("the value y is: " + this.y); } } public class...
class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } void print_xy() { System.out.println("the value x is: " + this.x); System.out.println("the value y is: " + this.y); } // set_xy(int x, int y) no longer possible } final public class P...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,717
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487717
3
5
OBJ51-J
Minimize the accessibility of classes and their members
Classes and class members (classes, interfaces, fields, and methods) are access-controlled in Java. The access is indicated by an access modifier ( public , protected , or private ) or by the absence of an access modifier (the default access, also called package-private access ). The following table presents a simplifi...
public final class Point { private final int x; private final int y; public Point(int x, int y) { this.x = x; this.y = y; } public void getPoint() { System.out.println("(" + x + "," + y + ")"); } } public final class Point { private static final int x = 1; private static final int y ...
final class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } public void getPoint() { System.out.println("(" + x + "," + y + ")"); } } class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; ...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,743
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487743
3
5
OBJ52-J
Write garbage-collection-friendly code
Java'€™s garbage-collection feature provides significant benefits over non-garbage-collected languages. The garbage collector (GC) is designed to automatically reclaim unreachable memory and to avoid memory leaks. Although the GC is quite adept at performing this task, a malicious attacker can nevertheless launch a den...
null
null
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,617
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487617
3
5
OBJ53-J
Do not use direct buffers for short-lived, infrequently used objects
The new I/O (NIO) classes 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 of heap-based nondirect buffers because direct buffers are managed u...
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocateDirect(8192); // Use rarelyUsedBuffer once ByteBuffer heavilyUsedBuffer = ByteBuffer.allocateDirect(8192); // Use heavilyUsedBuffer many times ## Noncompliant Code Example This noncompliant code example uses both a short-lived local object, rarelyUsedBuffer , and a lon...
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocate(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 hea...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,618
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487618
3
5
OBJ54-J
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 make maintenance difficult. Java just-in-time compilers (JITs) can perform an equivalent liveness analysis, and most implementations do so. A related bad practice is use of a finalizer to null...
{ // Local scope int[] buffer = new int[100]; doSomething(buffer); buffer = null; } ## 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 ...
{ // Limit the scope of buffer int[] buffer = new int[100]; doSomething(buffer); } ## Compliant Solution 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...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,616
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487616
3
5
OBJ55-J
Remove short-lived objects from long-lived container 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 likelihood of memory leaks. Similarly, use of array-based data structures such as Array...
class DataElement { private boolean dead = false; // Other fields public boolean isDead() { return dead; } public void killMe() { dead = true; } } // ... Elsewhere List<DataElement> longLivedList = new ArrayList<DataElement>(); // Processing that renders an element irrelevant // Kill the element that i...
class DataElement { // Dead flag removed // Other fields } // Elsewhere List<DataElement> longLivedList = new ArrayList<DataElement>(); // Processing that renders an element irrelevant // Set the reference to the irrelevant DataElement to null longLivedList.set(someIndex, null); class DataElement { public s...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,409
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487409
3
5
OBJ56-J
Provide sensitive mutable classes with unmodifiable wrappers
Immutability of fields prevents inadvertent modification as well as malicious tampering so that defensive copying while accepting input or returning values is unnecessary. However, some sensitive classes cannot be immutable. Fortunately, read-only access to mutable classes can be granted to untrusted code using unmodif...
class Mutable { private int[] array = new int[10]; public int[] getArray() { return array; } public void setArray(int[] i) { array = i; } } // ... private Mutable mutable = new Mutable(); public Mutable getMutable() {return mutable;} class MutableProtector extends Mutable { @Ov...
class MutableProtector extends Mutable { @Override public int[] getArray() { return super.getArray().clone(); } @Override public void setArray(int[] i) { throw new UnsupportedOperationException(); } } // ... private Mutable mutable = new MutableProtector(); // May be safely invoked by untrusted c...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,634
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487634
3
5
OBJ57-J
Do not rely on methods that can be overridden by untrusted code
Untrusted code can misuse APIs provided by trusted code to override methods such as Object.equals() , Object.hashCode() , and Thread.run() . These methods are valuable targets because they are commonly used behind the scenes and may interact with components in a way that is not easily discernible. By providing overridd...
public class LicenseManager { Map<LicenseType, String> licenseMap = new HashMap<LicenseType, String>(); public LicenseManager() { LicenseType type = new LicenseType(); type.setType("demo-license-key"); licenseMap.put(type, "ABC-DEF-PQR-XYZ"); } public Object getLicenseKey(Li...
public class LicenseManager { Map<LicenseType, String> licenseMap = new IdentityHashMap<LicenseType, String>(); // ... } public class DemoClient { public static void main(String[] args) { LicenseManager licenseManager = new LicenseManager(); LicenseType type = new LicenseType(); type...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,796
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487796
3
5
OBJ58-J
Limit the extensibility of classes and methods with invariants
Java classes and methods may have invariants . An invariant is a property that is assumed to be true at certain points during program execution but is not formally specified as true. Invariants may be used in assert statements or may be informally specified in comments. Method invariants can include guarantees made abo...
// Malicious subclassing of java.math.BigInteger class BigInteger extends java.math.BigInteger { private byte[] ba; public BigInteger(String str) { super(str); ba = (new java.math.BigInteger(str)).toByteArray(); } public BigInteger(byte[] ba) { super(ba); this.ba = ba; }  public void setVa...
package java.math; // ... final class BigInteger { // ... } package java.math; // ... public class BigInteger { public BigInteger(String str) { this(str, check()); } private BigInteger(String str, boolean dummy) { // Regular construction goes here } private static boolean check() { securi...
null
SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 05. Object Orientation (OBJ)
java
88,487,678
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487678
2
15
SEC00-J
Do not allow privileged blocks to leak sensitive information across a trust boundary
The java.security.AccessController class is part of Java's security mechanism; it is responsible for enforcing the applicable security policy. This class's static doPrivileged() method executes a code block with a relaxed security policy . The doPrivileged() method stops permissions from being checked further down the ...
public class PasswordManager { public static void changePassword() throws FileNotFoundException { FileInputStream fin = openPasswordFile(); // Test old password with password in file contents; change password, // then close the password file } public static FileInputStream openPasswordFile() ...
public class PasswordManager { public static void changePassword() throws FileNotFoundException { // ... } private static FileInputStream openPasswordFile() throws FileNotFoundException { // ... } } class PasswordManager { public static void changePassword() { FileInputStream fin = openPa...
## Risk Assessment Returning references to sensitive resources from within a doPrivileged() block can break encapsulation and confinement and can leak capabilities. Any caller who can invoke the privileged code directly and obtain a reference to a sensitive resource or field can maliciously modify its elements. Rule Se...
SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC)