language large_string | page_id int64 | page_url large_string | chapter int64 | section int64 | rule_id large_string | title large_string | intro large_string | noncompliant_code large_string | compliant_solution large_string | risk_assessment large_string | breadcrumb large_string |
|---|---|---|---|---|---|---|---|---|---|---|---|
java | 88,487,763 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487763 | 3 | 18 | CON50-J | Do not assume that declaring a reference volatile guarantees safe publication of the members of the referenced object | According to the
Java Language Specification
,
§8.3.1.4, "
volatile
Fields"
[
JLS 2013
],
A field may be declared
volatile
, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (
§17.4
).
This safe publication guarantee applies only to primitive fields and object referen... | final class Foo {
private volatile int[] arr = new int[20];
public int getFirst() {
return arr[0];
}
public void setFirst(int n) {
arr[0] = n;
}
// ...
}
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some use... | final class Foo {
private final AtomicIntegerArray atomicArray =
new AtomicIntegerArray(20);
public int getFirst() {
return atomicArray.get(0);
}
public void setFirst(int n) {
atomicArray.set(0, 10);
}
// ...
}
final class Foo {
private int[] arr = new int[20];
public synchronized int ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,832 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487832 | 3 | 18 | CON51-J | Do not assume that the sleep(), yield(), or getState() methods provide synchronization semantics | According to the
Java Language Specification
,
§17.3, "Sleep and Yield"
[
JLS 2013
],
It is important to note that neither
Thread.sleep
nor
Thread.yield
have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to
Thread.sleep
or... | final class ControlledStop implements Runnable {
private boolean done = false;
@Override public void run() {
while (!done) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Reset interrupted status
Thread.currentThread().interrupt(); }
}
}
public voi... | final class ControlledStop implements Runnable {
private volatile boolean done = false;
@Override public void run() {
//...
}
// ...
}
final class ControlledStop implements Runnable {
@Override public void run() {
// Record current thread, so others can interrupt it
myThread = currentThread();... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,842 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487842 | 3 | 18 | CON52-J | Document thread-safety and use annotations where applicable | The Java language annotation facility is useful for documenting design intent. Source code annotation is a mechanism for associating metadata with a program element and making it available to the compiler, analyzers, debuggers, or Java Virtual Machine (JVM) for examination. Several annotations are available for documen... | null | null | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 18. Concurrency (CON) |
java | 88,487,756 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487756 | 2 | 1 | DCL00-J | Prevent class initialization cycles | According to
The Java Language Specification
(JLS),
§12.4, "Initialization of Classes and Interfaces"
[
JLS 2005
]:
Initialization of a class consists of executing its
static
initializers and the initializers for
static
fields (class variables) declared in the class.
Therefore, the presence of a static field triggers t... | public class Cycle {
private final int balance;
private static final Cycle c = new Cycle();
private static final int deposit = (int) (Math.random() * 100); // Random deposit
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.pr... | public class Cycle {
private final int balance;
private static final int deposit = (int) (Math.random() * 100); // Random deposit
private static final Cycle c = new Cycle(); // Inserted after initialization of required fields
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public... | ## Risk Assessment
Initialization cycles may lead to unexpected results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL00-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,448 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487448 | 2 | 1 | DCL01-J | Do not reuse public identifiers from the Java Standard Library | Do not reuse the names of publicly visible identifiers, public utility classes, interfaces, or packages in the Java Standard Library.
When a developer uses an identifier that has the same name as a public class, such as
Vector
, a subsequent maintainer might be unaware that this identifier does not actually refer to
ja... | class Vector {
private int val = 1;
public boolean isEmpty() {
if (val == 1) { // Compares with 1 instead of 0
return true;
} else {
return false;
}
}
// Other functionality is same as java.util.Vector
}
// import java.util.Vector; omitted
public class VectorUser {
public static vo... | class MyVector {
//Other code
}
## Compliant Solution (Class Name)
This compliant solution uses a different name for the class, preventing any potential
shadowing
of the class from the Java Standard Library:
#ccccff
class MyVector {
//Other code
}
When the developer and organization control the original shadowed cla... | ## Risk Assessment
Public identifier reuse decreases the readability and maintainability of code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL01-J
Low
Unlikely
Yes
No
P2
L3
Automated Detection
An automated tool can easily detect reuse of the set of names representing public classes or interfaces fr... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,681 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487681 | 2 | 1 | DCL02-J | Do not modify the collection's elements during an enhanced for statement | The enhanced
for
statement is designed for iteration through
Collections
and
arrays
.
The Java Language Specification
(JLS) provides the following example of the enhanced
for
statement in
§14.14.2, "The Enhanced
for
Statement"
[
JLS 2014
]:
The enhanced for statement is equivalent to a basic for statement of the form:
... | List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15});
boolean first = true;
System.out.println("Processing list...");
for (Integer i: list) {
if (first) {
first = false;
i = new Integer(99);
}
System.out.println(" New item: " + i);
// Process i
}
System.out.println("Modified list?");
for (In... | // ...
for (final Integer i: list) {
if (first) {
first = false;
i = new Integer(99); // compiler error: variable i might already have been assigned
}
// ...
// ...
for (final Integer i: list) {
Integer item = i;
if (first) {
first = false;
item = new Integer(99);
}
System.out.println(" N... | ## Risk Assessment
Assignments to the loop variable of an enhanced
for
loop (
for-each
idiom) fail to affect the overall iteration order or the iterated collection or array. This can lead to programmer confusion, and can leave data in a fragile or inconsistent state.
Rule
Severity
Likelihood
Detectable
Repairable
Prior... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
java | 88,487,660 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487660 | 3 | 1 | DCL50-J | Use visually distinct identifiers | Use visually distinct identifiers that are unlikely to be misread during development and review of code. Depending on the fonts used, certain characters are visually similar or even identical and can be misinterpreted. Consider the examples in the following table.
Misleading characters
Intended Character
Could Be Mista... | int stem; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111l);
}
}
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2... | int bow; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
public class Visual {
public static void main(String[] args) {
System.out.println(11111 + 1111L);
}
}
int[] array = new int[3];
void exampleFunction() {
array[0] = 2719;
array[1] = 4435;
array[2... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,396 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487396 | 3 | 1 | DCL51-J | Do not shadow or obscure identifiers in subscopes | Reuse of identifier names in subscopes leads to obscuration or shadowing. Reused identifiers in the current scope can render those defined elsewhere inaccessible. Although the
Java Language Specification
(JLS) [
JLS 2013
] clearly resolves any syntactic ambiguity arising from obscuring or shadowing, such ambiguity burd... | class MyVector {
private int val = 1;
private void doLogic() {
int val;
//...
}
}
class MyVector {
private int i = 0;
private void doLogic() {
for (i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
}
## Noncompliant Code Example (Field Shadowing)
## This noncom... | class MyVector {
private int val = 1;
private void doLogic() {
int newValue;
//...
}
}
class MyVector {
private void doLogic() {
for (int i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
}
## Compliant Solution (Field Shadowing)
This compliant solution eliminate... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,521 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487521 | 3 | 1 | DCL52-J | Do not declare more than one variable per declaration | Declaring multiple variables in a single declaration could cause confusion about the types of variables and their initial values. In particular, do not declare any of the following in a single declaration:
Variables of different types
A mixture of initialized and uninitialized variables
In general, you should declare e... | int i, j = 1;
public class Example<T> {
private T a, b, c[], d;
public Example(T in) {
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
}
public String toString() {
return a.toString() + b.toString() +
c.toString() + d.toString();
}
// Correct functional implementation
public St... | int i = 1; // Purpose of i...
int j = 1; // Purpose of j...
int i = 1, j = 1;
public class Example<T> {
private T a; // Purpose of a...
private T b; // Purpose of b...
private T[] c; // Purpose of c[]...
private T d; // Purpose of d...
public Example(T in){
a = in;
b = in;
c = (T[]) new... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,517 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487517 | 3 | 1 | DCL53-J | Minimize the scope of variables | Scope minimization helps developers avoid common programming errors, improves code readability by connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed. It may also allow objects to be recovered by the garbage collector more q... | public class Scope {
public static void main(String[] args) {
int i = 0;
for (i = 0; i < 10; i++) {
// Do operations
}
}
}
public class Foo {
private int count;
private static final int MAX_COUNT = 10;
public void counter() {
count = 0;
while (condition()) {
/* ... */
i... | public class Scope {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) { // Contains declaration
// Do operations
}
}
}
public class Foo {
private static final int MAX_COUNT = 10;
public void counter() {
int count = 0;
while (condition()) {
/* ... */
if (c... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,464 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487464 | 3 | 1 | DCL54-J | Use meaningful symbolic constants to represent literal values in program logic | Java supports the use of various types of literals, such as integers (5, 2), floating-point numbers (2.5, 6.022e+23), characters (
'a'
,
'\n'
), Booleans (
true
,
false
), and strings (
"Hello\n"
). Extensive use of literals in a program can lead to two problems. First, the meaning of the literal is often obscured or u... | double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
return 4.19 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 6.28 * radius;
}
double area(double radius) {
return 3.14 * radius * radius;
}
double volume(double radius) {
retur... | private static final double PI = 3.14;
double area(double radius) {
return PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * PI * radius;
}
double area(double radius) {
return Math.PI * radius ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,528 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487528 | 3 | 1 | DCL55-J | Properly encode relationships in constant definitions | The definitions of constant expressions should be related
exactly
when the values they express are also related. | public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = 20;
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = VOTING_AGE + 3;
## Noncompliant Code Example
In this noncompliant code example,
OUT_STR_LEN
must always be exactly two greater than
IN_STR_LEN
. These defin... | public static final int IN_STR_LEN = 18;
public static final int OUT_STR_LEN = IN_STR_LEN + 2;
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = 21;
## Compliant Solution
## In this compliant solution, the relationship between the two values is represented in the definitions:
#ccccff
publ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,623 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487623 | 3 | 1 | DCL56-J | Do not attach significance to the ordinal associated with an enum | Java language enumeration types have an
ordinal()
method that returns the numerical position of each enumeration constant in its class declaration.
According to the Java API,
Class Enum<E extends Enum<E>>
[
API 2011
],
public final int ordinal()
returns the ordinal of the enumeration constant (its position in its enum ... | enum Hydrocarbon {
METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
HEXANE, HEPTANE, OCTANE, NONANE, DECANE;
public int getNumberOfCarbons() {
return ordinal() + 1;
}
}
## Noncompliant Code Example
This noncompliant code example declares
enum Hydrocarbon
and uses its
ordinal()
method to provide the result of th... | enum Hydrocarbon {
METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5),
HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9),
DECANE(10);
private final int numberOfCarbons;
Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; }
public int getNumberOfCarbons() {
return numberOfCarbons;
... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,795 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487795 | 3 | 1 | DCL57-J | Avoid ambiguous overloading of variable arity methods | The
variable arity (varargs)
feature was introduced in JDK v1.5.0 to support methods that accept a variable numbers of arguments.
According to the Java SE 6 documentation [
Oracle 2011b
],
As an API designer, you should use [variable arity methods] sparingly, only when the benefit is truly compelling. Generally speakin... | class Varargs {
private static void displayBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayBooleans(boolean bool1, boolean bool2) {
System.out.println("Ove... | class Varargs {
private static void displayManyBooleans(boolean... bool) {
System.out.print("Number of arguments: " + bool.length + ", Contents: ");
for (boolean b : bool)
System.out.print("[" + b + "]");
}
private static void displayTwoBooleans(boolean bool1, boolean bool2) {
System.out.print... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,794 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487794 | 3 | 1 | DCL58-J | Enable compile-time type checking of variable arity parameter types | A variable arity (aka
varargs
) method is a method that can take a variable number of arguments. The method must contain at least one fixed argument. When processing a variable arity method call, the Java compiler checks the types of all arguments, and all of the variable actual arguments must match the variable formal... | double sum(Object... args) {
double result = 0.0;
for (Object arg : args) {
if (arg instanceof Byte) {
result += ((Byte) arg).byteValue();
} else if (arg instanceof Short) {
result += ((Short) arg).shortValue();
} else if (arg instanceof Integer) {
result += ((Integer) arg).int... | double sum(Number... args) {
// ...
}
<T extends Number> double sum(T... args) {
// ...
}
## Compliant Solution (Number)
This compliant solution defines the same method but uses the
Number
type. This abstract class is general enough to encompass all numeric types, yet specific enough to exclude nonnumeric types.
... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,460 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487460 | 3 | 1 | DCL59-J | Do not apply public final to constants whose value might change in later releases | The
final
keyword can be used to specify constant values (that is, values that cannot change during program execution). However, constants that can change over the lifetime of a program should not be declared public final.
The Java Language Specification
(JLS) [
JLS 2013
] allows implementations to insert the value of ... | class Foo {
public static final int VERSION = 1;
// ...
}
class Bar {
public static void main(String[] args) {
System.out.println("You are using version " + Foo.VERSION);
}
}
You are using version 1
You are using version 1
## Noncompliant Code Example
In this noncompliant code example, class
Foo... | class Foo {
private static int version = 1;
public static final int getVersion() {
return version;
}
// ...
}
class Bar {
public static void main(String[] args) {
System.out.println(
"You are using version " + Foo.getVersion());
}
}
## Compliant Solution
According to
§13.4.9, "
final
Fields... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,472 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487472 | 3 | 1 | DCL60-J | Avoid cyclic dependencies between packages | Both
The Elements of Java Style
[
Vermeulen 2000
] and the JPL Java Coding Standard [
Havelund 2010
] require that the dependency structure of a package must never contain cycles; that is, it must be representable as a directed acyclic graph (DAG).
Eliminating cycles between packages has several advantages:
Testing and... | package account;
import user.User;
public class AccountHolder {
private User user;
public void setUser(User newUser) {user = newUser;}
synchronized void depositFunds(String username, double amount) {
// Use a utility method of User to check whether username exists
if (user.exists(username)) {
//... | package bank;
public interface BankApplication {
void depositFunds(BankApplication ba, String username, double amount);
double getBalance(String accountNumber);
double getUserBalance(String accountNumber);
boolean exists(String username);
}
package account;
import bank.BankApplication; // Import from a th... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,369 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487369 | 3 | 1 | DCL61-J | Do not use raw types | Under Construction
This guideline is under construction.
Mixing generically typed code with raw typed code is one common source of heap pollution. Prior to Java 5, all code used raw types. Allowing mixing enabled developers to preserve compatibility between non-generic legacy code and newer generic code. Using raw type... | 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
}
}
## Non... | class ListUtility {
private static void addToList(List<String> list, String str) {
list.add(str); // No warning generated
}
public static void main(String[] args) {
List<String> list = new ArrayList<String> ();
addToList(list, "42");
System.out.println(list.get(0));
}
}
## Compliant Soluti... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 01. Declarations and Initialization (DCL) |
java | 88,487,809 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487809 | 2 | 16 | ENV00-J | Do not sign code that performs only unprivileged operations | Java uses code signing as a requirement for granting elevated privileges to code. Many
security policies
permit signed code to operate with elevated privileges. For example, Java applets can escape the default sandbox restrictions when signed. Consequently, users can grant explicit permissions either to a particular co... | null | null | ## Risk Assessment
Signing unprivileged code violates the principle of least privilege because it can circumvent security restrictions defined by the security policies of applets and JNLP applications, for example.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV00-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,914 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487914 | 2 | 16 | ENV01-J | Place all security-sensitive code in a single JAR and sign and seal it | In Java SE 6 and later, privileged code must either use the
AccessController
mechanism or be signed by an owner (or provider) whom the user trusts. Attackers could link privileged code with malicious code if the privileged code directly or indirectly invokes code from another package. Trusted JAR files often contain co... | package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException, FileNotFoundException {
final FileInputSt... | package trusted;
public class MixMatch {
// ...
}
// In the same signed & sealed JAR file:
package trusted;
class RetValue {
int getValue() {
return 1;
}
}
Name: trusted/ // Package name
Sealed: true // Sealed attribute
## Compliant Solution
This compliant solution combines all security-sensitive code... | ## Risk Assessment
Failure to place all privileged code together in one package and seal the package can lead to mix-and-match attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV01-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,852 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487852 | 2 | 16 | ENV02-J | Do not trust the values of environment variables | Deprecated
This guideline has been deprecated.
Both environment variables and system properties provide user-defined mappings between keys and their corresponding values and can be used to communicate those values from the environment to a process. According to the Java API [
API 2014
]
java.lang.System
class documenta... | String username = System.getenv("USER");
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Please supply a user name as the argument");
return;
}
String user = args[0];
ProcessBuilder pb = new ProcessBuilder();
pb.command("/usr/bin/printenv");
Map<String,String> e... | String username = System.getProperty("user.name");
## Compliant Solution
This compliant solution obtains the user name using the
user.name
system property. The Java Virtual Machine (JVM), upon initialization, sets this system property to the correct user name, even when the
USER
environment variable has been set to an... | ## Risk Assessment
Untrusted environment variables can provide data for injection and other attacks if not properly
sanitized
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV02-J
Low
Likely
Yes
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,671 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487671 | 2 | 16 | ENV03-J | Do not grant dangerous combinations of permissions | Certain combinations of permissions can produce significant capability increases and should not be granted. Other permissions should be granted only to special code.
AllPermission
The permission
java.security.AllPermission
grants all possible permissions to code. This facility was included to reduce the burden of manag... | // Grant the klib library AllPermission
grant codebase "file:${klib.home}/j2se/home/klib.jar" {
permission java.security.AllPermission;
};
protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
pc.add(new ReflectPermission("suppressAccessChecks"));... | grant codeBase
"file:${klib.home}/j2se/home/klib.jar", signedBy "Admin" {
permission java.io.FilePermission "/tmp/*", "read";
permission java.io.SocketPermission "*", "connect";
};
// Security manager check
FilePermission perm =
new java.io.FilePermission("/tmp/JavaFile", "read");
AccessController.checkPe... | ## Risk Assessment
Granting
AllPermission
to
untrusted code
allows it to perform privileged operations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV03-J
High
Likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,890 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487890 | 2 | 16 | ENV04-J | Do not disable bytecode verification | When Java source code is compiled, it is converted into bytecode, saved in one or more class files, and executed by the Java Virtual Machine (JVM). Java class files may be compiled on one machine and executed on another machine. A properly generated class file is said to be
conforming
. When the JVM loads a class file,... | java -Xverify:none ApplicationName
## Noncompliant Code Example
The bytecode verification process runs by default. The
-Xverify:none
flag on the JVM command line suppresses the verification process. This noncompliant code example uses the flag to disable bytecode verification:
#FFcccc
java -Xverify:none ApplicationNam... | java -Xverify:all ApplicationName
## Compliant Solution
Most JVM implementations perform bytecode verification by default; it is also performed during dynamic class loading.
Specifying the
-Xverify:all
flag on the command line requires the JVM to enable bytecode verification (even when it would otherwise have been sup... | ## Risk Assessment
Bytecode verification ensures that the bytecode contains many of the security checks mandated by the
Java Language Specification
. Omitting the verification step could permit execution of insecure Java code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV04-J
High
Likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,615 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487615 | 2 | 16 | ENV05-J | Do not deploy an application that can be remotely monitored | Java provides several APIs that allow external programs to monitor a running Java program. These APIs also permit the Java program to be monitored remotely by programs on distinct hosts. Such features are convenient for debugging the program or fine-tuning its performance. However, if a Java program is deployed in prod... | ${JDK_PATH}/bin/java -agentlib:libname=options ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_shmem,
address=mysharedmemory ApplicationName
${JDK_PATH}/bin/java
-Dcom.sun.management.jmxremote.port=8000 ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=y,ad... | ${JDK_PATH}/bin/java -Djava.security.manager ApplicationName
${JDK_PATH}/bin/java -agentlib:jdwp=transport=dt_socket,
server=n,address=9000 ApplicationName
## Compliant Solution
This compliant solution starts the JVM without any agents enabled. Avoid using the
-agentlib
,
-Xrunjdwp
, and
-Xdebug
command-line arg... | ## Risk Assessment
Deploying a Java application with the JVMTI, JPDA, or remote monitoring enabled can allow an attacker to monitor or modify its behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV05-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,339 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487339 | 2 | 16 | ENV06-J | Production code must not contain debugging entry points | According to
J2EE Bad Practices: Leftover Debug Code
[
Hewlett-Packard 2015
]:
A common development practice is to add "back door" code specifically designed for debugging or testing purposes that is not intended to be shipped or deployed with the application. When this sort of debug code is accidentally left in the ap... | class Stuff {
private static final bool DEBUG = False;
// Other fields and methods
public static void main(String args[]) {
Stuff.DEBUG = True;
Stuff stuff = new Stuff();
// Test stuff
}
}
## Noncompliant Code Example
In this noncompliant code example, the
Stuff
class has a
main()
function that tes... | ## Compliant Solution
## A compliant solution simply removes themain()method from theStuffclass, depriving attackers of this entry point. | ## Risk Assessment
Leaving extra entry points into production code could allow an attacker to gain special access to the program.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ENV06-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 16. Runtime Environment (ENV) |
java | 88,487,876 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487876 | 2 | 7 | ERR00-J | Do not suppress or ignore checked exceptions | Programmers often suppress checked exceptions by catching exceptions with an empty or trivial
catch
block. Each
catch
block must ensure that the program continues only with valid
invariants
. Consequently, the
catch
block must either recover from the exceptional condition, rethrow the exception to allow the next neares... | try {
//...
} catch (IOException ioe) {
ioe.printStackTrace();
}
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
## Noncompliant Code Example
## This noncompliant code example simply prints the exception's... | boolean validFlag = false;
do {
try {
// ...
// If requested file does not exist, throws FileNotFoundException
// If requested file exists, sets validFlag to true
validFlag = true;
} catch (FileNotFoundException e) {
// Ask the user for a different file name
}
} while (validFlag != true);
// U... | ## Risk Assessment
Ignoring or suppressing exceptions can result in inconsistent program state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR00-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,679 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487679 | 2 | 7 | ERR01-J | Do not allow exceptions to expose sensitive information | Failure to filter sensitive information when propagating exceptions often results in information leaks that can assist an attacker's efforts to develop further exploits. An attacker may craft input arguments to expose internal structures and mechanisms of the application. Both the exception message text and the type of... | class ExceptionExample {
public static void main(String[] args) throws FileNotFoundException {
// Linux stores a user's home directory path in
// the environment variable $HOME, Windows in %APPDATA%
FileInputStream fis =
new FileInputStream(System.getenv("APPDATA") + args[0]);
}
}
try {
Fi... | class ExceptionExample {
public static void main(String[] args) {
File file = null;
try {
file = new File(System.getenv("APPDATA") +
args[0]).getCanonicalFile();
if (!file.getPath().startsWith("c:\\homepath")) {
System.out.println("Invalid file");
return;
}
... | ## Risk Assessment
Exceptions may inadvertently reveal sensitive information unless care is taken to limit the information disclosure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR01-J
Medium
Probable
No
Yes
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,839 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487839 | 2 | 7 | ERR02-J | Prevent exceptions while logging data | Exceptions that are thrown while logging is in progress can prevent successful logging unless special care is taken. Failure to account for exceptions during the logging process can cause security
vulnerabilities
, such as allowing an attacker to conceal critical security exceptions by preventing them from being logged... | try {
// ...
} catch (SecurityException se) {
System.err.println(se);
// Recover from exception
}
## Noncompliant Code Example
## This noncompliant code example writes a critical security exception to the standard error stream:
#FFcccc
try {
// ...
} catch (SecurityException se) {
System.err.println(se);
// Reco... | try {
// ...
} catch(SecurityException se) {
logger.log(Level.SEVERE, se);
// Recover from exception
}
## Compliant Solution
This compliant solution uses
java.util.logging.Logger
, the default logging API provided by JDK 1.4 and later. Use of other compliant logging mechanisms, such as log4j, is also permitted.
... | ## Risk Assessment
Exceptions thrown during data logging can cause loss of data and can conceal security problems.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR02-J
Medium
Likely
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,753 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487753 | 2 | 7 | ERR03-J | Restore prior object state on method failure | Objects in general should—and security-critical objects
must
—be maintained in a consistent state even when exceptional conditions arise. Common techniques for maintaining object consistency include
Input validation (on method arguments, for example)
Reordering logic so that code that can result in the exceptional cond... | class Dimensions {
private int length;
private int width;
private int height;
static public final int PADDING = 2;
static public final int MAX_DIMENSION = 10;
public Dimensions(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
protected ... | // ...
} catch (Throwable t) {
MyExceptionReporter mer = new MyExceptionReporter();
mer.report(t); // Sanitize
length -= PADDING; width -= PADDING; height -= PADDING; // Revert
return -1;
}
protected int getVolumePackage(int weight) {
length += PADDING;
width += PADDING;
height += PADDING;
... | ## Risk Assessment
Failure to restore prior object state on method failure can leave the object in an inconsistent state and can violate required state
invariants
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR03-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,685 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487685 | 2 | 7 | ERR04-J | Do not complete abruptly from a finally block | Never use
return
,
break
,
continue
, or
throw
statements within a
finally
block. When program execution enters a
try
block that has a
finally
block, the
finally
block always executes regardless of whether the
try
block (or any associated
catch
blocks) executes to normal completion. Statements that cause the
finally
bl... | class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
return true;
}
}
}
## Noncompliant Code Example
## In this noncompliant code example, thefinallyblock completes abruptly because of areturnstate... | class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
System.out.println("logic done");
}
// Any return statements must go here;
// applicable only when exception is thrown conditionally
}
}
## Compliant Solution
## This complian... | ## Risk Assessment
Abrupt completion of a
finally
block masks any exceptions thrown inside the associated
try
and
catch
blocks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR04-J
Low
Probable
Yes
Yes
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,445 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487445 | 2 | 7 | ERR05-J | Do not let checked exceptions escape from a finally block | Methods invoked from within a
finally
block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire
try
block. Abrupt termination causes any exception thrown in the
try
block to be lost, preventing any possible recovery method from handling that specific probl... | public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
reader.close();
//... | public class Operation {
public static void doOperation(String some_file) {
// ... Code to check or set character encoding ...
try {
BufferedReader reader =
new BufferedReader(new FileReader(some_file));
try {
// Do operations
} finally {
try {
reader.clo... | ## Risk Assessment
Failure to handle an exception in a
finally
block may have unexpected results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR05-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,873 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487873 | 2 | 7 | ERR06-J | Do not throw undeclared checked exceptions | Java requires that each method address every checked exception that can be thrown during its execution either by handling the exception within a
try-catch
block or by declaring that the exception can propagate out of the method (via the
throws
clause). Unfortunately, there are a few techniques that permit undeclared ch... | public class NewInstance {
private static Throwable throwable;
private NewInstance() throws Throwable {
throw throwable;
}
public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
thro... | public static synchronized void undeclaredThrow(Throwable throwable) {
// These exceptions should not be passed
if (throwable instanceof IllegalAccessException ||
throwable instanceof InstantiationException) {
// Unchecked, no declaration required
throw new IllegalArgumentException();
}
NewInsta... | ## Risk Assessment
Failure to document undeclared checked exceptions can result in checked exceptions that the caller is unprepared to handle, consequently violating the safety property.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR06-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,928 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487928 | 2 | 7 | ERR07-J | Do not throw RuntimeException, Exception, or Throwable | Methods must not throw
RuntimeException
,
Exception
, or
Throwable
. Handling these exceptions requires catching
RuntimeException
, which is disallowed by
. Moreover, throwing a
RuntimeException
can lead to subtle errors; for example, a caller cannot examine the exception to determine why it was thrown and consequently... | boolean isCapitalized(String s) {
if (s == null) {
throw new RuntimeException("Null String");
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
private voi... | boolean isCapitalized(String s) {
if (s == null) {
throw new NullPointerException();
}
if (s.equals("")) {
return true;
}
String first = s.substring(0, 1);
String rest = s.substring(1);
return (first.equals(first.toUpperCase()) &&
rest.equals(rest.toLowerCase()));
}
private void doSomet... | ## Risk Assessment
Throwing
RuntimeException
,
Exception
, or
Throwable
prevents classes from catching the intended exceptions without catching other unintended exceptions as well.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR07-J
Low
Likely
Yes
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,929 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487929 | 2 | 7 | ERR08-J | Do not catch NullPointerException or any of its ancestors | Programs must not catch
java.lang.NullPointerException
. A
NullPointerException
exception thrown at runtime indicates the existence of an underlying
null
pointer dereference that must be fixed in the application code (see
for more information). Handling the underlying null pointer dereference by catching the
NullPointe... | boolean isName(String s) {
try {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
} catch (NullPointerException e) {
return false;
}
}
public interface Log {
void write(String messageToLog);
}
public... | boolean isName(String s) {
if (s == null) {
return false;
}
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
boolean isName(String s) /* Throws NullPointerException */ {
String names[] = s.split(" ");
if (name... | ## Risk Assessment
Catching
NullPointerException
may mask an underlying null dereference, degrade application performance, and result in code that is hard to understand and maintain. Likewise, catching
RuntimeException
,
Exception
, or
Throwable
may unintentionally trap other exception types and prevent them from being... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,663 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487663 | 2 | 7 | ERR09-J | Do not allow untrusted code to terminate the JVM | Invocation of
System.exit()
terminates the Java Virtual Machine (JVM), consequently terminating all running programs and threads. This can result in
denial-of-service (DoS) attacks
. For example, a call to
System.exit()
that is embedded in Java Server Pages (JSP) code can cause a web server to terminate, preventing fur... | public class InterceptExit {
public static void main(String[] args) {
// ...
System.exit(1); // Abrupt exit
System.out.println("This never executes");
}
}
## Noncompliant Code Example
This noncompliant code example uses
System.exit()
to forcefully shut down the JVM and terminate the running process.... | class PasswordSecurityManager extends SecurityManager {
private boolean isExitAllowedFlag;
public PasswordSecurityManager(){
super();
isExitAllowedFlag = false;
}
public boolean isExitAllowed(){
return isExitAllowedFlag;
}
@Override
public void checkExit(int status) {
if (!isE... | ## Risk Assessment
Allowing unauthorized calls to
System.exit()
may lead to
denial of service
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR09-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 07. Exceptional Behavior (ERR) |
java | 88,487,825 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487825 | 3 | 7 | ERR50-J | Use exceptions only for exceptional conditions | Exceptions should be used only to denote exceptional conditions; they should not be used for ordinary control flow purposes. Catching a generic object such as
Throwable
is likely to catch unexpected errors; see
ERR08-J. Do not catch NullPointerException or any of its ancestors
for examples. When a program catches a spe... | public String processSingleString(String string) {
// ...
return string;
}
public String processStrings(String[] strings) {
String result = "";
int i = 0;
try {
while (true) {
result = result.concat(processSingleString(strings[i]));
i++;
}
} catch (ArrayIndexOutOfBoundsException e)... | public String processStrings(String[] strings) {
String result = "";
for (int i = 0; i < strings.length; i++) {
result = result.concat( processSingleString( strings[i]));
}
return result;
}
## Compliant Solution
## This compliant solution uses a standardforloop to concatenate the strings.
#ccccff
public St... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,451 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487451 | 3 | 7 | ERR51-J | Prefer user-defined exceptions over more general exception types | Because an exception is caught by its type, it is better to define exceptions for specific purposes than to use the general exception types for multiple purposes. Throwing general exception types makes code hard to understand and maintain and defeats much of the advantage of the Java exception-handling mechanism. | try {
doSomething();
} catch (Throwable e) {
String msg = e.getMessage();
switch (msg) {
case "file not found":
// Handle error
break;
case "connection timeout":
// Handle error
break;
case "security violation":
// Handle error
break;
default: throw e;
}
}
... | public class TimeoutException extends Exception {
TimeoutException () {
super();
}
TimeoutException (String msg) {
super(msg);
}
}
// ...
try {
doSomething();
} catch (FileNotFoundException e) {
// Handle error
} catch (TimeoutException te) {
// Handle error
} catch (SecurityException se) {
... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,499 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487499 | 3 | 7 | ERR52-J | Avoid in-band error indicators | An in-band error indicator is a value returned by a method that indicates either a legitimate return value or an illegitimate value that indicates an error. Some common examples of in-band error indicators include
A valid object or a null reference.
An integer indicating a positive value, or −1 to indicate that an erro... | static final int MAX = 21;
static final int MAX_READ = MAX - 1;
static final char TERMINATOR = '\\';
int read;
char [] chBuff = new char [MAX];
BufferedReader buffRdr;
// Set up buffRdr
read = buffRdr.read(chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;
## Noncompliant Code Example
This noncompliant code example at... | public static int readSafe(BufferedReader buffer, char[] cbuf,
int off, int len) throws IOException {
int read = buffer.read(cbuf, off, len);
if (read == -1) {
throw new EOFException();
} else {
return read;
}
}
// ...
BufferedReader buffRdr;
// Set up buffRdr
try {
r... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,487 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487487 | 3 | 7 | ERR53-J | Try to gracefully recover from system errors | According to the Java Language Specification,
§11.1.1, "The Kinds of Exceptions"
[
JLS 2013
],
The unchecked exceptions classes are the class
RuntimeException
and its subclasses, and the class
Error
and its subclasses. All other exception classes are checked exception classes.
Unchecked exception classes are not subjec... | public class StackOverflow {
public static void main(String[] args) {
infiniteRun();
// ...
}
private static void infiniteRun() {
infiniteRun();
}
}
## Noncompliant Code Example
This noncompliant code example generates a
StackOverflowError
as a result of infinite recursion. It exhausts the ava... | public class StackOverflow {
public static void main(String[] args) {
try {
infiniteRun();
} catch (Throwable t) {
// Forward to handler
} finally {
// Free cache, release resources
}
// ...
}
private static void infiniteRun() {
infiniteRun();
}
}
## Compliant... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,656 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487656 | 3 | 7 | ERR54-J | Use a try-with-resources statement to safely handle closeable resources | The Java Development Kit 1.7 (JDK 1.7) introduced the try-with-resources statement (see the JLS, §14.20.3, "
try
-with-resources" [
JLS 2013
]), which simplifies correct use of resources that implement the
java.lang.AutoCloseable
interface, including those that implement the
java.io.Closeable
interface.
Using the try-... | public void processFile(String inPath, String outPath)
throws IOException{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
try... | public void processFile(String inPath, String outPath)
throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
if ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 07. Exceptional Behavior (ERR) |
java | 88,487,879 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487879 | 2 | 2 | EXP00-J | Do not ignore values returned by methods | Methods can return values to communicate failure or success or to update local objects or fields. Security risks can arise when method return values are ignored or when the invoking method fails to take suitable action. Consequently, programs must not ignore method return values.
When getter methods are named after an ... | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
someFile.delete();
}
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original.replace('i', '9');
System.out.println(original);
}
}
## Noncompliant... | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
if (!someFile.delete()) {
// Handle failure to delete the file
}
}
public class Replace {
public static void main(String[] args) {
String original = "insecure";
original = original.replace('i',... | ## Risk Assessment
Ignoring method return values can lead to unexpected program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP00-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,784 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487784 | 2 | 2 | EXP01-J | Do not use a null in a case where an object is required | Do not use the
null
value in any instance where an object is required, including the following cases:
Calling the instance method of a null object
Accessing or modifying the field of a null object
Taking the length of
null
as if it were an array
Accessing or modifying the elements of
null
as if it were an array
Throwin... | public static int cardinality(Object obj, final Collection<?> col) {
int count = 0;
if (col == null) {
return count;
}
Iterator<?> it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) || obj.equals(elt)) { // Null pointer dereference
count++;
... | public static int cardinality(Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) ||
(null != obj && obj.equals(elt))) {
count++;
}
}
... | ## Risk Assessment
Dereferencing a null pointer can lead to a
denial of service
. In multithreaded programs, null pointer dereferences can violate cache coherency policies and can cause resource leaks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP01-J
Low
Likely
No
Yes
P6
L2
Automated Detection
Null... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,911 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487911 | 2 | 2 | EXP02-J | Do not use the Object.equals() method to compare two arrays | In Java, arrays are objects and support object methods such as
Object.equals()
. However, arrays do not support any methods besides those provided by
Object
. Consequently, using
Object.equals()
on any array compares only array
references
, not their
contents
. Programmers who wish to compare the contents of two arrays... | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1.equals(arr2)); // Prints false
## Noncompliant Code Example
## This noncompliant code example uses theObject.equals()method to compare two arrays:
#FFCCCC
int[] arr1 = new int[20]; // Initialized to 0
in... | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(Arrays.equals(arr1, arr2)); // Prints true
int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1 == arr2); // Prints false
## Compliant Solution... | ## Risk Assessment
Using the
equals()
method or relational operators with the intention of comparing array contents produces incorrect results, which can lead to
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP02-J
Low
Likely
Yes
Yes
P9
L2
Automated Detection
Static detection of calls... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,762 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487762 | 2 | 2 | EXP03-J | Do not use the equality operators when comparing values of boxed primitives | The
values
of boxed primitives cannot be directly compared using the
==
and
!=
operators because these operators compare object references rather than object values. Programmers can find this behavior surprising because autoboxing
memoizes
, or caches, the values of some primitive variables. Consequently, reference com... | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
};
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;... | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i > j ? 1 : 0) ;
}
};
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;... | ## Risk Assessment
Using the equivalence operators to compare values of boxed primitives can lead to erroneous comparisons.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP03-J
Low
Likely
Yes
Yes
P9
L2
Automated Detection
Detection of all uses of the reference equality operators on boxed primitive obje... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,864 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487864 | 2 | 2 | EXP04-J | Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type | The interfaces of the Java Collections Framework [
JCF 2014
] use generically typed, parameterized methods, such as
add(E e)
and
put(K key, V value)
, to insert objects into the collection or map, but they have other methods, such as
contains()
,
remove()
, and
get()
, that accept an argument of type
Object
rather than... | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i); // Cast required so that the code compiles
s.remove(i); // Tries to remove an Integer
}
System.out.println(s.size());
}
}
#... | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i);
// Remove a Short
if (s.remove((short)i) == false) {
System.err.println("Error removing " + i);
}
}
System.out.p... | ## Risk Assessment
Passing arguments to certain Java Collection Framework methods that are of a different type from that of the class instance can cause silent failures, resulting in unintended object retention, memory leaks, or incorrect program operation [
Techtalk 2007
].
Rule
Severity
Likelihood
Detectable
Repairab... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,732 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487732 | 2 | 2 | EXP05-J | Do not follow a write by a subsequent write or read of the same object within an expression | Deprecated
This rule may be deprecated and replaced by a similar guideline.
06/28/2014 -- Version 1.0
According to
The Java Language Specification
(JLS),
§15.7, "Evaluation Order"
[
JLS 2015
]:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order,... | class BadPrecedence {
public static void main(String[] args) {
int number = 17;
int threshold = 10;
number = (number > threshold ? 0 : -2)
+ ((31 * ++number) * (number = get()));
// ...
if (number == 0) {
System.out.println("Access granted");
} else {
System.out.prin... | final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold ? 0 : -2);
## Compliant Solution (Order of Evaluation)
This compliant solution uses equivalent code with no side effects and performs not more than one write per expression. The resulting expression can be reordered without conc... | ## Risk Assessment
Failure to understand the evaluation order of expressions containing side effects can result in unexpected output.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP05-J
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Detection of all expressions involving both side effects and multiple ... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,834 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487834 | 2 | 2 | EXP06-J | Expressions used in assertions must not produce side effects | The
assert
statement is a convenient mechanism for incorporating diagnostic tests in code. The behavior of the
assert
statement depends on the status of a runtime property. When enabled, the
assert
statement evaluates its expression argument and throws an
AssertionError
if false. When disabled,
assert
is a no-op; any s... | private ArrayList<String> names;
void process(int index) {
assert names.remove(null); // Side effect
// ...
}
## Noncompliant Code Example
This noncompliant code attempts to delete all the null names from the list in an assertion. However, the Boolean expression is not evaluated when assertions are disabled.
#ff... | private ArrayList<String> names;
void process(int index) {
boolean nullsRemoved = names.remove(null);
assert nullsRemoved; // No side effect
// ...
}
## Compliant Solution
The possibility of side effects in assertions can be avoided by decoupling the Boolean expression from the assertion:
#ccccff
private Arra... | ## Risk Assessment
Side effects in assertions result in program behavior that depends on whether assertions are enabled or disabled.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP06-J
Low
Unlikely
Yes
Yes
P3
L3
Automated Detection
Automated detection of assertion operands that contain locally visible... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,383 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487383 | 2 | 2 | EXP07-J | Prevent loss of useful data due to weak references | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
If weak references are misused then ...
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP07-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 02. Expressions (EXP) |
java | 88,487,880 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487880 | 3 | 2 | EXP50-J | Do not confuse abstract object equality with reference equality | Java defines the equality operators
==
and
!=
for testing reference equality but uses the
equals()
method defined in
Object
and its subclasses for testing abstract object equality. Naïve programmers often confuse the intent of the
==
operation with that of the
Object.equals()
method. This confusion is frequently eviden... | public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1 == str2); // Prints "false"
}
}
## Noncompliant Code Example
## This noncompliant code example declares two distinctStringobjects that conta... | public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(str1.equals( str2)); // Prints "true"
}
}
public class StringComparison {
public static void main(String[] args) {
String str1 = new String... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,457 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487457 | 3 | 2 | EXP51-J | Do not perform assignments in conditional expressions | Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts:
if
(
controlling expression
)
while
(controlling expression)
do ... while
(controlling expression)
for
(second opera... | public void f(boolean a, boolean b) {
if (a = b) {
/* ... */
}
}
public void f(boolean a, boolean b, boolean flag) {
while ( (a = b) && flag ) {
/* ... */
}
}
## In this noncompliant code example, the controlling expression in theifstatement is an assignment expression:
#FFcccc
public void f(boolean a... | public void f(boolean a, boolean b) {
if (a == b) {
/* ... */
}
}
public void f(boolean a, boolean b) {
if ((a = b) == true) {
/* ... */
}
}
public void f(boolean a, boolean b) {
a = b;
if (a) {
/* ... */
}
}
public void f(boolean a, boolean b, boolean flag) {
while ( (a == b) && flag ) {... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,475 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487475 | 3 | 2 | EXP52-J | Use braces for the body of an if, for, or while statement | Use opening and closing braces for
if
,
for
, and
while
statements even when the body contains only a single statement. Braces improve the uniformity and readability of code.
More important, it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, because t... | int login;
if (invalid_login())
login = 0;
else
login = 1;
int login;
if (invalid_login())
login = 0;
else
// Debug line added below
System.out.println("Login is valid\n");
// The next line is always executed
login = 1;
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUE... | int login;
if (invalid_login()) {
login = 0;
} else {
login = 1;
}
int privileges;
if (invalid_login()) {
if (allow_guests()) {
privileges = GUEST;
}
} else {
privileges = ADMINISTRATOR;
}
## Compliant Solution
This compliant solution uses opening and closing braces even though the body of the
if
and... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,527 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487527 | 3 | 2 | EXP53-J | Use parentheses for precedence of operation | Programmers frequently make errors regarding the precedence of operators because of the unintuitively low precedence levels of
&
,
|
,
^
,
<<
, and
>>
. Avoid mistakes regarding precedence through the suitable use of parentheses, which also improves code readability. The precedence of operations by the order of the sub... | public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return x & MASK + OFFSET;
}
x & (MASK + OFFSET)
x & (1337 - 1337)
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "1"
System.out.println("... | public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return (x & MASK) + OFFSET;
}
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "value=0" as expected
System.out.println("value=" + (s == null... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,424 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487424 | 3 | 2 | EXP54-J | Understand the differences between bitwise and logical operators | The conditional AND and OR operators (
&&
and
||
respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result of the conditional operator cannot be deduced solely by evaluating the first operand. Consequently, when the result of the conditional operator
can
be deduced sole... | int array[]; // May be null
int i; // May be an invalid index for array
if (array != null & i >= 0 & i < array.length & array[i] >= 0) {
// Use array
} else {
// Handle error
}
if (end1 >= 0 & i2 >= 0) {
int begin1 = i1;
int begin2 = i2;
while (++i1 < array1.length &&
++i2 < array2.length &&
... | int array[]; // May be null
int i; // May be an invalid index for array
if (array != null && i >= 0 &&
i < array.length && array[i] >= 0) {
// Handle array
} else {
// Handle error
}
int array[]; // May be null
int i; // May be a valid index for array
if (array != null) {
if (i >= 0 && i < array.... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,397 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487397 | 3 | 2 | EXP55-J | Use the same type for the second and third operands in conditional expressions | The conditional operator
?:
uses the
boolean
value of its first operand to decide which of the other two expressions will be evaluated. (See
§15.25, "Conditional Operator
? :
"
of the
Java Language Specification
(JLS) [
JLS 2013
].)
The general form of a Java conditional expression is
operand1 ? operand2 : operand3
.
I... | public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
// Other code. Value of i may change
boolean trueExp = true; // Some expression that evaluates to true
System.out.print(trueExp ? alpha : 0); // prints A
System.out.print(trueExp ? alpha : i); // prints ... | public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
boolean trueExp = true; // Expression that evaluates to true
System.out.print(trueExp ? alpha : ((char) 0)); // Prints A
// Deliberate narrowing cast of i; possible truncation OK
System.out.print(trueExp ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 02. Expressions (EXP) |
java | 88,487,585 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487585 | 2 | 13 | FIO00-J | Do not operate on files in shared directories | Multiuser systems allow multiple users with different privileges to share a file system. Each user in such an environment must be able to determine which files are shared and which are private, and each user must be able to enforce these decisions.
Unfortunately, a wide variety of file system
vulnerabilities
can be
exp... | String file = /* Provided by user */;
InputStream in = null;
try {
in = new FileInputStream(file);
// ...
} finally {
try {
if (in !=null) { in.close();}
} catch (IOException x) {
// Handle error
}
}
String filename = /* Provided by user */;
Path path = new File(filename).toPath();
try (InputStream i... | public static boolean isInSecureDir(Path file) {
return isInSecureDir(file, null);
}
public static boolean isInSecureDir(Path file, UserPrincipal user) {
return isInSecureDir(file, user, 5);
}
/**
* Indicates whether file lives in a secure directory relative
* to the program's user
* @param file Path to test
... | ## Risk Assessment
Performing operations on files in shared directories can result in
DoS attacks
. If the program has elevated privileges, privilege escalation
exploits
are possible.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO00-J
Medium
Unlikely
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,592 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487592 | 2 | 13 | FIO01-J | Create files with appropriate access permissions | Files on multiuser systems are generally owned by a particular user. The owner of the file can specify which other users on the system should be allowed to access the contents of these files.
These file systems use a privileges and permissions model to protect file access. When a file is created, the file access permis... | Writer out = new FileWriter("file");
## Noncompliant Code Example
The constructors for
FileOutputStream
and
FileWriter
do not allow the programmer to explicitly specify file access permissions. In this noncompliant code example, the access permissions of any file created are
implementation-defined
and may not prevent ... | Path file = new File("file").toPath();
// Throw exception rather than overwrite existing file
Set<OpenOption> options = new HashSet<OpenOption>();
options.add(StandardOpenOption.CREATE_NEW);
options.add(StandardOpenOption.APPEND);
// File permissions should be such that only user may read/write file
Set<PosixFilePerm... | ## Risk Assessment
If files are created without appropriate permissions, an attacker may read or write to the files, possibly resulting in compromised system integrity and information disclosure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO01-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,501 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487501 | 2 | 13 | FIO02-J | Detect and handle file-related errors | Java's file-manipulation methods often indicate failure with a return value instead of throwing an exception. Consequently, programs that ignore the return values from file operations often fail to detect that those operations have failed. Java programs must check the return values of methods that perform file I/O. Thi... | File file = new File(args[0]);
file.delete();
## Noncompliant Code Example (delete())
This noncompliant code example attempts to delete a specified file but gives no indication of its success. The Java platform requires
File.delete()
to throw a
SecurityException
only when the program lacks authorization to delete the ... | File file = new File("file");
if (!file.delete()) {
// Deletion failed, handle error
}
Path file = new File(args[0]).toPath();
try {
Files.delete(file);
} catch (IOException x) {
// Deletion failed, handle error
}
## Compliant Solution
## This compliant solution checks the return value ofdelete():
#ccccFF
File ... | ## Risk Assessment
Failure to check the return values of methods that perform file I/O can result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO02-J
Medium
Probable
Yes
Yes
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,821 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487821 | 2 | 13 | FIO03-J | Remove temporary files before termination | Temporary files can be used to
Share data between processes.
Store auxiliary program data (for example, to preserve memory).
Construct and/or load classes, JAR files, and native libraries dynamically.
Temporary files are
files
and consequently must conform to the requirements specified by other rules governing operatio... | class TempFile {
public static void main(String[] args) throws IOException{
File f = new File("tempnam.tmp");
if (f.exists()) {
System.out.println("This file already exists");
return;
}
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
String str = "Data";
... | class TempFile {
public static void main(String[] args) {
Path tempFile = null;
try {
tempFile = Files.createTempFile("tempnam", ".tmp");
try (BufferedWriter writer =
Files.newBufferedWriter(tempFile, Charset.forName("UTF8"),
StandardOpenOption.DELETE_ON... | ## Risk Assessment
Failure to remove temporary files before termination can result in information leakage and resource exhaustion.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO03-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,870 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487870 | 2 | 13 | FIO04-J | Release resources when they are no longer needed | The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the garbage collector cannot free nonmemory resources such as open file descriptors and database connections. Consequently, failing to release such resources can lead to resource exhaustion attacks. In addition, programs ca... | public int processFile(String fileName)
throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
send... | try {
final FileInputStream stream = new FileInputStream(fileName);
try {
final BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} finally {
if (stream != null) {
try {
... | ## Risk Assessment
Failure to explicitly release nonmemory system resources when they are no longer needed can result in resource exhaustion.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO04-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,782 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487782 | 2 | 13 | FIO05-J | Do not expose buffers or their backing arrays methods to untrusted code | Buffer classes defined in the
java.nio
package, such as
IntBuffer
,
CharBuffer
, and
ByteBuffer
, define a variety of methods that wrap an array (or a portion of the array) of the corresponding primitive data type into a buffer and return the buffer as a
Buffer
object. Although these methods create a new
Buffer
object,... | final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray);
}
}
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// Initialize
}
publi... | final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray).asReadOnlyBuffer();
}
}
final class Wrap {
private char[] dataArray;
public Wrap() {
dataArray = new char[10];
... | ## Risk Assessment
Exposing buffers created using the
wrap()
,
duplicate()
,
array()
,
slice()
, or
subsequence()
methods may allow an untrusted caller to alter the contents of the original data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO05-J
Medium
Likely
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,774 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487774 | 2 | 13 | FIO06-J | Do not create multiple buffered wrappers on a single byte or character stream | Java input classes such as
Scanner
and
BufferedInputStream
facilitate fast, nonblocking I/O by buffering an underlying input stream. Programs can create multiple wrappers on an
InputStream
. Programs that use multiple wrappers around a single input stream, however, can behave unpredictably depending on whether the wrap... | public final class InputLibrary {
public static char getChar() throws EOFException, IOException {
BufferedInputStream in = new BufferedInputStream(System.in); // Wrapper
int input = in.read();
if (input == -1) {
throw new EOFException();
}
// Down casting is permitted because InputStream gua... | public final class InputLibrary {
private static BufferedInputStream in =
new BufferedInputStream(System.in);
public static char getChar() throws EOFException, IOException {
int input = in.read();
if (input == -1) {
throw new EOFException();
}
in.skip(1); // This statement is to advance... | ## Risk Assessment
Creating multiple buffered wrappers around an
InputStream
can cause unexpected program behavior when the
InputStream
is redirected.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO06-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,722 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487722 | 2 | 13 | FIO07-J | Do not let external processes block on IO buffers | The
exec()
method of the
java.lang.Runtime
class and the related
ProcessBuilder.start()
method can be used to invoke external programs. While running, these programs are represented by a
java.lang.Process
object. This process contains an input stream, output stream, and error stream. Because the
Process
object allows a... | public class Exec {
public static void main(String args[]) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
int exitVal = proc.exitValue();
}
}
public class Exec {
public static void main(String args[])
throws IOException, Interrup... | public class Exec {
public static void main(String args[])
throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("notemaker");
pb = pb.redirectErrorStream(true);
Process proc = pb.start();
InputStream is = proc.getInputStream();
int c;
whil... | ## Risk Assessment
Failure to properly manage the I/O streams of external processes can result in runtime exceptions and in
DoS
vulnerabilities.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO07-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,889 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487889 | 2 | 13 | FIO08-J | Distinguish between characters or bytes read from a stream and -1 | The abstract
InputStream.read()
and
Reader.read()
methods are used to read a byte or character, respectively, from a stream. The
InputStream.read()
method reads a single byte from an input source and returns its value as an
int
in the range 0 to 255 (
0x00
-
0xff
). The
Reader.read()
method reads a single character and... | FileInputStream in;
// Initialize stream
byte data;
while ((data = (byte) in.read()) != -1) {
// ...
}
FileReader in;
// Initialize stream
char data;
while ((data = (char) in.read()) != -1) {
// ...
}
## Noncompliant Code Example (byte)
FileInputStream
is a subclass of
InputStream
. It will return −1 only w... | FileInputStream in;
// Initialize stream
int inbuff;
byte data;
while ((inbuff = in.read()) != -1) {
data = (byte) inbuff;
// ...
}
FileReader in;
// Initialize stream
int inbuff;
char data;
while ((inbuff = in.read()) != -1) {
data = (char) inbuff;
// ...
}
## Compliant Solution (byte)
Use a variable... | ## Risk Assessment
Historically, using a narrow type to capture the return value of a byte input method has resulted in significant
vulnerabilities
, including command injection attacks; see
CA-1996-22 advisory
. Consequently, the severity of this error is high.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
L... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,720 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487720 | 2 | 13 | FIO09-J | Do not rely on the write() method to output integers outside the range 0 to 255 | The
write()
method, defined in the class
java.io.OutputStream
, takes an argument of type
int
the value of which must be in the range 0 to 255. Because a value of type
int
could be outside this range, failure to range check can result in the truncation of the higher-order bits of the argument.
The general contract for ... | class ConsoleWrite {
public static void main(String[] args) {
// Any input value > 255 will result in unexpected output
System.out.write(Integer.valueOf(args[0]));
System.out.flush();
}
}
## Noncompliant Code Example
This noncompliant code example accepts a value from the user without validating it. A... | class FileWrite {
public static void main(String[] args)
throws NumberFormatException, IOException {
// Perform range checking
int value = Integer.valueOf(args[0]);
if (value < 0 || value > 255) {
throw new ArithmeticException("Value is out of range");
}
Syste... | ## Risk Assessment
Using the
write()
method to output integers outside the range 0 to 255 will result in truncation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO09-J
Low
Unlikely
No
Yes
P2
L3
Automated Detection
Automated detection of all uses of the
write()
method is straightforward. Sound determi... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,767 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487767 | 2 | 13 | FIO10-J | Ensure the array is filled when using read() to fill an array | The contracts of the read methods for
InputStream
and
Reader
classes and their subclasses are complicated with regard to filling byte or character arrays. According to the Java API [
API 2014
] for the class
InputStream
, the
read(byte[] b)
method and the
read(byte[] b, int off, int len)
method provide the following be... | public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
if (in.read(data) == -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
int offset = 0;
... | public static String readBytes(InputStream in) throws IOException {
int offset = 0;
int bytesRead = 0;
byte[] data = new byte[1024];
while ((bytesRead = in.read(data, offset, data.length - offset))
!= -1) {
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
String str = new S... | ## Risk Assessment
Incorrect use of the
read()
method can result in the wrong number of bytes being read or character sequences being interpreted incorrectly.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO10-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,611 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487611 | 2 | 13 | FIO11-J | Do not convert between strings and bytes without specifying a valid character encoding | Deprecated
This rule has been moved to:
STR03-J. Do not convert between strings and bytes without specifying a valid character encoding
12/08/2014 -- Version 1.0 | null | null | null | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,759 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487759 | 2 | 13 | FIO12-J | Provide methods to read and write little-endian data | In Java, data is stored in
big-endian format
(also called network order). That is, all data is represented sequentially starting from the most significant bit to the least significant. JDK versions prior to JDK 1.4 required definition of custom methods that manage reversing byte order to maintain compatibility with lit... | try {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("data"));
// Little-endian data might be read as big-endian
int serialNumber = dis.readInt();
} catch (IOException x) {
// Handle error
} finally {
if (dis != null) {
try {
dis.close();
}... | try {
DataInputStream dis = null;
try {
dis = new DataInputStream( new FileInputStream("data"));
byte[] buffer = new byte[4];
int bytesRead = dis.read(buffer); // Bytes are read into buffer
if (bytesRead != 4) {
throw new IOException("Unexpected End of Stream");
}
int serialNumber =
... | ## Risk Assessment
Reading and writing data without considering endianness can lead to misinterpretations of both the magnitude and sign of the data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO12-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,885 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487885 | 2 | 13 | FIO13-J | Do not log sensitive information outside a trust boundary | Logging is essential for debugging, incident response, and collecting forensic evidence. Nevertheless, logging
sensitive data
raises many concerns, including the privacy of the stakeholders, limitations imposed by the law on the collection of personal information, and the potential for data exposure by insiders. Sensit... | public void logRemoteIPAddress(String name) {
Logger logger = Logger.getLogger("com.organization.Log");
InetAddress machine = null;
try {
machine = InetAddress.getByName(name);
} catch (UnknownHostException e) {
Exception e = MyExceptionReporter.handle(e);
} catch (SecurityException e) {
Exception... | // ...
catch (SecurityException e) {
Exception e = MyExceptionReporter.handle(e);
}
// Make sure that all handlers only print log messages rated INFO or higher
Handler handlers[] = logger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
handlers[i].setLevel(Level.INFO);
}
// ...
logger.finest("Age:... | ## Risk Assessment
Logging sensitive information can violate system
security policies
and can violate user privacy when the logging level is incorrect or when the log files are insecure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO13-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,524 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487524 | 2 | 13 | FIO14-J | Perform proper cleanup at program termination | When certain kinds of errors are detected, such as irrecoverable logic errors, rather than risk data corruption by continuing to execute in an indeterminate state, the appropriate strategy may be for the system to quickly shut down, allowing the operator to start it afresh in a determinate state.
Section 6.46, "Termina... | public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
out.println("hello");
Runtime.getRuntime().exit(1);... | public class CreateFile {
public static void main(String[] args)
throws FileNotFoundException {
final PrintStream out =
new PrintStream(new BufferedOutputStream(
new FileOutputStream("foo.txt")));
try {
out.println("hello");
} finally {
try {
out.close... | ## Risk Assessment
Failure to perform necessary cleanup at program termination may leave the system in an inconsistent state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO14-J
Medium
Likely
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,638 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487638 | 2 | 13 | FIO15-J | Do not reset a servlet's output stream after committing it | When a web servlet receives a request from a client, it must produce some suitable response. Java's
HttpServlet
provides the
HttpServletResponse
object to capture a suitable response. This response can be built using an output stream provided by
getOutputStream()
or a writer provided by
getWriter()
.
A response is said... | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html>");
// ... Write some response text
out.flush(); // Commits the stream
// ... More work
} catch ... | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Do work that doesn't require the output stream
} catch (IOException x) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ServletOutputStream out = response.... | ## Risk Assessment
If a servlet's output stream is reset after it has been committed, an
IllegalStateException
usually results, which can cause the servlet's response to be truncated.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO15-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,708 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487708 | 2 | 13 | FIO16-J | Canonicalize path names before validating them | According to the Java API [
API 2006
] for
class
java.io.File
:
A pathname, whether abstract or in string form, may be either
absolute
or
relative
. An absolute pathname is complete in that no other information is required to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in term... | File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
FileOutputStream fis = new FileOutputStream(file);
// ...
File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonica... | File file = new File("/img/" + args[0]);
if (!isInSecureDir(file)) {
throw new IllegalArgumentException();
}
String canonicalPath = file.getCanonicalPath();
if (!canonicalPath.equals("/img/java/file1.txt") &&
!canonicalPath.equals("/img/java/file2.txt")) {
// Invalid file; handle error
}
FileInputStream fis =... | ## Risk Assessment
Using path names from untrusted sources without first
canonicalizing
them and then validating them can result in directory traversal and path equivalence
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO16-J
Medium
Unlikely
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 13. Input Output (FIO) |
java | 88,487,662 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487662 | 3 | 13 | FIO50-J | Do not make assumptions about file creation | Although creating a file is usually accomplished with a single method call, this single action raises multiple security-related questions. What should be done if the file cannot be created? What should be done if the file already exists? What should be the file's initial attributes, such as permissions?
Java provides s... | public void createFile(String filename)
throws FileNotFoundException{
OutputStream out = new FileOutputStream(filename);
// Work with file
}
public void createFile(String filename)
throws IOException{
OutputStream out = new FileOutputStream(filename, true);
if (!new File(filename).createNewFile()) {
... | public void createFile(String filename)
throws FileNotFoundException{
try (OutputStream out = new BufferedOutputStream(
Files.newOutputStream(Paths.get(filename),
StandardOpenOption.CREATE_NEW))) {
// Work with out
} catch (IOException x) {
// File not writable... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,531 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487531 | 3 | 13 | FIO51-J | Identify files using multiple file attributes | Many file-related security vulnerabilities result from a program accessing an unintended file object. This often happens because file names are only loosely bound to underlying file objects. File names provide no information regarding the nature of the file object itself. Furthermore, the binding of a file name to a fi... | public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle... | public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
FileTime creation1 = attr1.creationTime();
FileTime modified1 = attr1.lastModifiedTime();
//... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,632 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487632 | 3 | 13 | FIO52-J | Do not store unencrypted sensitive information on the client side | When building an application that uses a client-server model, storing sensitive information, such as user credentials, on the client side may result in its unauthorized disclosure if the client is vulnerable to attack.
For web applications, the most common mitigation to this problem is to provide the client with a cook... | protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
... | protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
// Validate input (omitted)
String username = request.getParameter("username");
char[] password = request.getParameter("password").toCharArray();
boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,483 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487483 | 3 | 13 | FIO53-J | Use the serialization methods writeUnshared() and readUnshared() with care | When objects are serialized using the
writeObject()
method, each object is written to the output stream only once. Invoking the
writeObject()
method on the same object a second time places a back-reference to the previously serialized instance in the stream. Correspondingly, the
readObject()
method produces at most one... | String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeUnshared(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new... | String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeObject(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new ... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 13. Input Output (FIO) |
java | 88,487,713 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487713 | 2 | 0 | IDS00-J | Prevent SQL injection | SQL injection vulnerabilities arise in applications where elements of a SQL query originate from an untrusted source. Without precautions, the
untrusted data
may maliciously alter the query, resulting in information leaks or data modification. The primary means of preventing SQL injection are
sanitization
and validatio... | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
St... | public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Validate username length
if (username.length() > 8) {... | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS00-J
High
Likely
Yes
No
P18
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,810 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487810 | 2 | 0 | IDS01-J | Normalize strings before validating them | Many applications that accept untrusted input strings employ input filtering and validation mechanisms based on the strings' character data. For example, an application's strategy for avoiding cross-site scripting (XSS) vulnerabilities may include forbidding <script> tags in inputs. Such blacklisting mechanisms are a u... | // String s may be user controllable
// \uFE64 is normalized to < and \uFE65 is normalized to > using the NFKC normalization form
String s = "\uFE64" + "script" + "\uFE65";
// Validate
Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
/... | String s = "\uFE64" + "script" + "\uFE65";
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
// Validate
Pattern pattern = Pattern.compile("[<>]");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found blacklisted tag
throw new IllegalStateException();
} else {
// ...
}
## Compliant Solution
... | ## Risk Assessment
Validating input before normalization affords attackers the opportunity to bypass filters and other security mechanisms. It can result in the execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS01-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,909 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487909 | 2 | 0 | IDS03-J | Do not log unsanitized user input | A log injection
vulnerability
arises when a log entry contains unsanitized user input. A malicious user can insert fake log data and consequently deceive system administrators as to the system's behavior [
OWASP 2008
]. For example, an attacker might split a legitimate log entry into two log entries by entering a carri... | if (loginSuccessful) {
logger.severe("User login succeeded for: " + username);
} else {
logger.severe("User login failed for: " + username);
}
May 15, 2011 2:19:10 PM java.util.logging.LogManager$RootLogger log
SEVERE: User login failed for: guest
guest
May 15, 2011 2:25:52 PM java.util.logging.LogManager$RootL... | if (loginSuccessful) {
logger.severe("User login succeeded for: " + sanitizeUser(username));
} else {
logger.severe("User login failed for: " + sanitizeUser(username));
}
public String sanitizeUser(String username) {
return Pattern.matches("[A-Za-z0-9_]+", username)
? username : "unauthorized user";
}
Log... | ## Risk Assessment
Allowing unvalidated user input to be logged can result in forging of log entries, leaking secure information, or storing
sensitive data
in a manner that violates a local law or regulation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS03-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,470 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487470 | 2 | 0 | IDS04-J | Safely extract files from ZipInputStream | Java provides the
java.util.zip
package for zip-compatible data compression. It provides classes that enable you to read, create, and modify ZIP and GZIP file formats.
A number of security concerns must be considered when extracting file entries from a ZIP file using
java.util.zip.ZipInputStream
. File names may contai... | static final int BUFFER = 512;
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
S... | static final int BUFFER = 512;
static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
static final int TOOMANY = 1024; // Max number of files
// ...
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String ca... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS04-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,836 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487836 | 2 | 0 | IDS06-J | Exclude unsanitized user input from format strings | The
java.io
package includes a
PrintStream
class that has two equivalent formatting methods:
format()
and
printf()
.
System.out
and
System.err
are
PrintStream
objects, allowing
PrintStream
methods to be invoked on the standard output and error streams. The risks from using these methods are not as high as from using si... | class Format {
static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] should contain the credit card expiration date
// but might contain %1$tm, %1$te or %1$tY format specifiers
System.out.format(
args[0] + " did not match!... | class Format {
static Calendar c =
new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] is the credit card expiration date
// Perform comparison with c,
// if it doesn't match, print the following line
System.out.format(
"%s did no... | ## Risk Assessment
Incorporating
untrusted data
in a format string may result in information leaks or allow a
denial-of-service attack
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS06-J
Medium
Unlikely
Yes
No
P4
L3
Automated Detection
Static analysis tools that perform taint analysis can diagnose s... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,877 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487877 | 2 | 0 | IDS07-J | Sanitize untrusted data passed to the Runtime.exec() method | External programs are commonly invoked to perform a function required by the overall system. This practice is a form of reuse and might even be considered a crude form of component-based software engineering. Command and argument injection
vulnerabilities
occur when an application fails to
sanitize
untrusted input and ... | class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /C dir " + dir);
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result)... | // ...
if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) {
// Handle error
}
// ...
// ...
String dir = null;
int number = Integer.parseInt(System.getProperty("dir")); // Only allow integer choices
switch (number) {
case 1:
dir = "data1";
break; // Option 1
case 2:
dir = "data2";
break; // Option 2... | ## Risk Assessment
Passing
untrusted
, unsanitized data to the
Runtime.exec()
method can result in command and argument injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS07-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,807 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487807 | 2 | 0 | IDS08-J | Sanitize untrusted data included in a regular expression | Regular expressions (regex) are widely used to match strings of text. For example, the POSIX
grep
utility supports regular expressions for finding patterns in the specified text. For introductory information on regular expressions, see the Java Tutorials [
Java Tutorials
]. The
java.util.regex
package provides the
Patt... | import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch... | public static void FindLogEntry(String search) {
// Sanitize search string
StringBuilder sb = new StringBuilder(search.length());
for (int i = 0; i < search.length(); ++i) {
char ch = search.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
sb.append(ch);
}
}
search = sb.... | ## Risk Assessment
Failing to
sanitize
untrusted data
included as part of a regular expression can result in the disclosure of sensitive information.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS08-J
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,808 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487808 | 2 | 0 | IDS11-J | Perform any string modifications before validation | It is important that a string not be modified after validation has occurred because doing so may allow an attacker to bypass validation. For example, a program may filter out
the
<script>
tags from HTML input to avoid cross-site scripting (XSS) and other
vulnerabilities
. If exclamation marks (!) are deleted from the i... | import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Validate input
Pattern pattern = Pattern.compile("<... | Strange things are happening with the regex below. Our bot inserts a link to the same rec within the code regex.
11/16/2014 rCs : is this still a problem or can we delete this comment?
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
publi... | ## Risk Assessment
Validating input before removing or modifying characters in the input string can allow malicious input to bypass validation checks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS11-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,645 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487645 | 2 | 0 | IDS14-J | Do not trust the contents of hidden form fields | HTML allows fields in a web form to be visible or hidden. Hidden fields supply values to a web server but do not provide the user with a mechanism to modify their contents. However, there are techniques that attackers can use to modify these contents anyway. A web servlet that uses a
GET
form to obtain parameters can a... | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getPar... | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getPara... | ## Risk Assessment
Trusting the contents of hidden form fields may lead to all sorts of nasty problems.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS14-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,640 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487640 | 2 | 0 | IDS15-J | Do not allow sensitive information to leak outside a trust boundary | This rule is a stub.
Several guidelines are instances of this one, including
,
, and
.
Noncompliant Code Example
This noncompliant code example shows an example where ...
#FFCCCC
Compliant Solution
In this compliant solution, ...
#CCCCFF
Risk Assessment
Leaking sensitive information outside a trust boundary is not a go... | null | null | null | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,619 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487619 | 2 | 0 | IDS16-J | Prevent XML Injection | The extensible markup language (XML) is designed to help store, structure, and transfer data. Because of its platform independence, flexibility, and relative simplicity, XML has found use in a wide range of applications. However, because of its versatility, XML is vulnerable to a wide spectrum of attacks, including
XML... | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStreamBad(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString = "<item>\n<description>Widget</descrip... | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException, NumberFormatException {
// Write XML string only if quantity... | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS16-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,620 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487620 | 2 | 0 | IDS17-J | Prevent XML External Entity Attacks | Entity declarations
define shortcuts to commonly used text or special characters. An entity declaration may define either an
internal
or
external entity
. For internal entities, the content of the entity is given in the declaration. For external entities, the content is specified by a Uniform Resource Identifier (URI).... | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
priva... | import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class CustomResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// Check for known good ent... | ## Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS17-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,459 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487459 | 3 | 0 | IDS50-J | Use conservative file naming conventions | File and path names containing particular characters or character sequences can cause problems when used in the construction of a file or path name:
Leading dashes: Leading dashes can cause problems when programs are called with the file name as a parameter because the first character or characters of the file name mig... | File f = new File("A\uD8AB");
OutputStream out = new FileOutputStream(f);
A?
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
File f = new File(args[0]);
OutputStream out = new FileOutputStream(f);
// ...
}
## Noncompliant Code Example
## In the followi... | File f = new File("name.ext");
OutputStream out = new FileOutputStream(f);
public static void main(String[] args) throws Exception {
if (args.length < 1) {
// Handle error
}
String filename = args[0];
Pattern pattern = Pattern.compile("[^A-Za-z0-9._]");
Matcher matcher = pattern.matcher(filename);
if ... | ## Risk Assessment
Failing to use only a safe subset of ASCII can result in misinterpreted data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS50-J
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,918 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487918 | 3 | 0 | IDS51-J | Properly encode or escape output | Proper input sanitization can prevent insertion of malicious data into a subsystem such as a database. However, different subsystems require different types of sanitization. Fortunately, it is usually obvious which subsystems will eventually receive which inputs, and consequently what type of sanitization is required.
... | @RequestMapping("/getnotifications.htm")
public ModelAndView getNotifications(
HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
try {
UserInfo userDetails = getUserInfo();
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
List<Notifi... | public class ValidateOutput {
// Allows only alphanumeric characters and spaces
private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9\\s]{0,20}$");
// Validates and encodes the input field based on a whitelist
public String validate(String name, String input) throws ValidationException {
Stri... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,444 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487444 | 3 | 0 | IDS52-J | Prevent code injection | Code injection can occur when untrusted input is injected into dynamically constructed code. One obvious source of potential vulnerabilities is the use of JavaScript from Java code. The
javax.script
package consists of interfaces and classes that define Java scripting engines and a framework for the use of those interf... | private static void evalScript(String firstName) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("print('"+ firstName + "')");
}
dummy\');
var bw = new JavaImporter(java.io.BufferedWriter);
var fw = new J... | private static void evalScript(String firstName) throws ScriptException {
// Allow only alphanumeric and underscore chars in firstName
// (modify if firstName may also include special characters)
if (!firstName.matches("[\\w]*")) {
// String does not match whitelisted characters
throw new IllegalArgument... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,536 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487536 | 3 | 0 | IDS53-J | Prevent XPath Injection | Extensible Markup Language (XML) can be used for data storage in a manner similar to a relational database. Data is frequently retrieved from such an XML document using XPaths.
XPath injection
can occur when data supplied to an XPath retrieval routine to retrieve data from an XML document is used without proper sanitiz... | private boolean doLogin(String userName, char[] password)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuil... | declare variable $userName as xs:string external;
declare variable $password as xs:string external;
//users/user[@userName=$userName and @password=$password]
private boolean doLogin(String userName, String pwd)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuil... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,534 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487534 | 3 | 0 | IDS54-J | Prevent LDAP injection | The Lightweight Directory Access Protocol (LDAP) allows an application to remotely perform operations such as searching and modifying records in directories. LDAP injection results from inadequate input sanitization and validation and allows malicious users to glean restricted information using the directory service.
A... | // String userSN = "S*"; // Invalid
// String userPassword = "*"; // Invalid
public class LDAPInjection {
private void searchRecord(String userSN, String userPassword) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FAC... | // String userSN = "Sherlock Holmes"; // Valid
// String userPassword = "secret2"; // Valid
// ... beginning of LDAPInjection.searchRecord()...
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
if (!userSN.matches("[\\w\\s]*") || !userPassword.matches("[\\w]*")) {
thro... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,392 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487392 | 3 | 0 | IDS55-J | Understand how escape characters are interpreted when strings are loaded | Many classes allow inclusion of escape sequences in character and string literals; examples include
java.util.regex.Pattern
as well as classes that support XML- and SQL-based actions by passing string arguments to methods. According to the
Java Language Specification
(JLS),
§3.10.6, "Escape Sequences for Character and ... | public class Splitter {
// Interpreted as backspace
// Fails to split on word boundaries
private final String WORDS = "\b";
public String[] splitWords(String input) {
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
public class Split... | public class Splitter {
// Interpreted as two chars, '\' and 'b'
// Correctly splits on word boundaries
private final String WORDS = "\\b";
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
WORDS=\... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,635 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487635 | 3 | 0 | IDS56-J | Prevent arbitrary file upload | Java applications, including web applications, that accept file uploads must ensure that an attacker cannot upload or transfer malicious files. If a restricted file containing code is executed by the target system, it can compromise application-layer defenses. For example, an application that permits HTML files to be u... | <action name="doUpload" class="com.example.UploadAction">
<interceptor-ref name="upload">
<param name="maximumSize"> 10240 </param>
<param name="allowedTypes"> text/plain,image/JPEG,text/html </param>
</interceptor-ref>
</action>
public class UploadAction extends ActionSupport {
private File uplo... | public class UploadAction extends ActionSupport {
private File uploadedFile;
// setter and getter for uploadedFile
public String execute() {
try {
// File path and file name are hardcoded for illustration
File fileToCreate = new File("filepath", "filename");
boolean textPlain = checkMeta... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 00. Input Validation and Data Sanitization (IDS) |
java | 88,487,670 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487670 | 2 | 17 | JNI00-J | Define wrappers around native methods | Native methods are defined in Java and written in languages such as C and C++ [
JNI 2006
]. The added extensibility comes at the cost of flexibility and portability because the code no longer conforms to the policies enforced by Java. Native methods have been used for performing platform-specific operations, interfacin... | public final class NativeMethod {
// Public native method
public native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method that lacks security checks and input validation
public void doOperation(byte[] data, int offset, int len) {
nativeOperation(data, offset, len);
}
static ... | public final class NativeMethodWrapper {
// Private native method
private native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method performs SecurityManager and input validation checks
public void doOperation(byte[] data, int offset, int len) {
// Permission needed to invoke native ... | ## Risk Assessment
Failure to define wrappers around native methods can allow unprivileged callers to invoke them and
exploit
inherent
vulnerabilities
such as buffer overflows in native libraries.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI00-J
Medium
Probable
No
No
P4
L3
Automated Detection
Autom... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,334 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487334 | 2 | 17 | JNI01-J | Safely invoke standard APIs that perform tasks using the immediate caller's class loader instance (loadLibrary) | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
Many static methods in standard Java APIs vary their behavior according to the immediate caller's class. Such methods are considered to be caller-sensitive. For example, the
java.lang.System.loadLibrary(library)
method uses the immediate caller's class loader to fin... | // Trusted.java
import java.security.*;
public class Trusted {
public static void loadLibrary(final String library){
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary(library);
return null;
}
});
}
}
----... | // Trusted.java
import java.security.*;
public class Trusted {
// load native libraries
static{
System.loadLibrary("NativeMethodLib1");
System.loadLibrary("NativeMethodLib2");
...
}
// private native methods
private native void nativeOperation1(byte[] data, int offset, int len);
privat... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI01-J
high
likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,633 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487633 | 2 | 17 | JNI02-J | Do not assume object references are constant or unique | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
According to [
JNI Tips
], section "Local and Global References", references in native code to the same object may have different values. Return values from the
NewGlobalRef()
function when applied to the same object may differ from each other. Consequently, object ... | ## Noncompliant Code Example
This noncompliant code example shows an example where it is assumed that an object reference is constant with erroneous results.
#FFCCCC | ## Compliant Solution
In this compliant solution, in native code, object references are tested for object equality using the
IsSameObject()
function, and the object references tested are global references
.
#CCCCFF | ## Risk Assessment
If it is assumed that an object reference is constant or unique then erroneous results may be obtained that could lead to the app crashing. This, in turn, could be used to mount a denial-of-service attack.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI02-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,624 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487624 | 2 | 17 | JNI03-J | Do not use direct pointers to Java objects in JNI code | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
To allow for the proper operation of the garbage collector in Java, the JVM must keep track of all Java objects passed to native code. Consequently, JNI uses
local references
and
global references
, see [
JNISpec 2014
]
Chapter 2: Design Overview
. While at least on... | ## Noncompliant Code Example
## This noncompliant code example shows an example where a direct pointer to a Java object is used with erroneous results.
#FFCCCC | ## Compliant Solution
## In this compliant solution ...
#CCCCFF | ## Risk Assessment
If a direct pointer to a Java object is used then erroneous results may be obtained that could lead to the code crashing. This, in turn, could be used to mount a denial of service attack. In some circumstances, the direct pointer could become a "dangling pointer" which could result in sensitive info... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,626 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487626 | 2 | 17 | JNI04-J | Do not assume that Java strings are null-terminated | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
According to [
JNI Tips
], section "UTF-8 and UTF-16 Strings", Java uses UTF-16 strings that are not null-terminated. UTF-16 strings may contain \u0000 in the middle of the string, so it is necessary to know the length of the string when working on Java strings in ... | ## Noncompliant Code Example
This noncompliant code example shows an example where the wrong type of character encoding is used with erroneous results.
#FFCCCC | ## Compliant Solution
## In this compliant solution ...
#CCCCFF | ## Risk Assessment
If character data is not normalized before being passed to the
NewStringUTF()
function then erroneous results may be obtained.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
JNI04-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 17. Java Native Interface (JNI) |
java | 88,487,798 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487798 | 2 | 9 | LCK00-J | Use private final lock objects to synchronize classes that may interact with untrusted code | There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization. Methods declared as synchronized and blocks that synchronize on the
this
reference both use the object as a
monitor
(that is, its intrinsic lock). An attacker can manipulate the system to trigger cont... | public class SomeObject {
// Locks on the object's monitor
public synchronized void changeValue() {
// ...
}
public static SomeObject lookup(String name) {
// ...
}
}
// Untrusted code
String name = // ...
SomeObject someObject = SomeObject.lookup(name);
if (someObject == null) {
// ... handle ... | public class SomeObject {
private final Object lock = new Object(); // private final lock object
public void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
public class SomeObject {
private static final Object lock = new Object();
public static void changeVa... | ## Risk Assessment
Exposing the lock object to untrusted code can result in DoS.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
LCK00-J
low
probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 09. Locking (LCK) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.