RuleDescriptionExampleKPITags
Compile Regex OncePattern object compiles the regular expressions which are passed to them and this compilation happens in the memory. If a regular expression is used many times, then this compilation should be performed only once.Non-compliant code:
Class Foo {
// This method can call multiple times
void findText(String inputText) {
Pattern pattern = Pattern.compile("(.*)(\\d+)(.*)");
Matcher matcher = pattern.matcher(inputText);
if(matcher.find()) {
MatchResult result = matcher.toMatchResult();
}
}
}


Compliant code:
Class Foo {
Pattern pattern = Pattern.compile("(.*)(\\d+)(.*)");

void findText(String inputText) {
Matcher matcher = pattern.matcher(inputText);
if(matcher.find()) {
MatchResult result = matcher.toMatchResult();
}
}
}
Efficiency
Disabled Spring Securitys CSRFCSRF protection is enabled by default in the Java configuration. Disabling CSRF protection can create a major security threat.
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.

More Info - OWASP Top 10 A6:2017 - Security Misconfiguration
CWE-352 - Cross-Site Request Forgery (CSRF)
Non-compliant code:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}


Compliant code:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Do not disable CSRF
// http.csrf().disable();
}
}
Security
Resource LeakResource should be closed in finally block. Another way is to use try-with-resource. In case of either exception or no exception, close() should always be put in finally clause.Non-compliant code:
class Demo {

public void process1() {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
out.close(); //close() is in try clause
} catch (IOException e) {
logger.error("resource is closed in try block",e);
}
}

//Non-compliant code
//resource is not closed anywhere
public void process2() {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
logger.error("Resource is not closed anywhere.",e);
}
}
}


Compliant code:
class Demo {
public void process2() {
printWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
logger.error("Resource is closed in finally block",e);
} finally {
if (out != null) {
out.close(); //close() is in finally clause
}
}
}

//compliant code
//try-with-resource statement
public void process3() {
try (PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)))) {
out2.println("the text");
} catch (IOException e) {
logger.error("try-with-resource",e);
}
}
}
Resource Utilization
Weak Cipher AlgorithmUse strong cryptographic algorithms as they are less vulnerable to brute force attacks among others.
For more information : : OWASP Top 10 2017 Category A3 - Sensitive Data Exposure
MITRE, CWE-327 - Use of a Broken or Risky Cryptographic Algorithm
Non-compliant code:
class CipherExample
{
public void foo()
{
try
{
Cipher c = Cipher.getInstance("DES"); // Or DESede, RC2, RC4 as these are known to be vulnerable
} catch (NoSuchAlgorithmException | NoSuchPaddingException e)
{
logger.error("Invalid algorithm",e);
}
}
}


Compliant code:

class CipherExample
{
public void foo()
{
try
{
Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); // Compliant
} catch(NoSuchAlgorithmException|NoSuchPaddingException e)
{
logger.error("Invalid algorithm",e);
}
}
}
Security
Possible Thread Leak In Executor Service Thread leak can be possible if ExecutorService is not getting shutdown.There is a queue of tasks between client threads and thread pool. When the normal thread finishes the "run" method (Runnable or Callable), it will be passed to garbage collector for collection. But with ExecuterService, threads will be simply put on hold and they will not be selected for garbage collection. Therefore, the shutdown is needed for ExecutorService.
Non-compliant code:
class Demo {

//ExecutorService is not closed anywhere
public void process1() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
doTask();
} catch (Exception e) {
logger.error("indexing failed", e);
}
}
});
}
}


Compliant code:
class Demo {

public void process2() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
doTask();
} catch (Exception e) {
logger.error("indexing failed", e);
}
}
});
executorService.shutdown();
}
}

Resource Utilization
Non Private Field In Synchronized BlockNon-private, non-final field accessed in synchronized block indicates possibly partial synchronization, and does not protect direct access to the field from other parts of the system without synchronization.
Make the field private and/or final, and provide accessors which can enforce synchronization.

More Info - CWE-820 - Missing synchronization
Non-compliant code:
class NonPrivateFieldAccessInSynchronizedBlock {

protected List statuses = new ArrayList<>(); // or public
private Object lock = new Object();

void foo() {
// Some processing
synchronized(lock) {
statuses.add("Running");
}
}
// Some more processing
}


Compliant code
class NonPrivateFieldAccessInSynchronizedBlock {

private List statuses = new ArrayList<>();
private Object lock = new Object();

void foo() {
// Some processing
synchronized(lock) {
statuses.add("Running");
}

// Some more processing
}

void updateStatus(String status) {
synchronized(lock) {
statuses.add(status);
}
}
}
Robustness, Security
Database Should Be Password ProtectedDatabase connection should always be password protected. Attacker can access the sensitive data from the database, in case it is not secured by password.

More Info
- [OWASP Top 10 2017 Category A3] - Sensitive Data Exposure
- [MITRE, CWE-521] - Weak Password Requirements
Non-compliant code:
class CipherExample {
public void foo() {

Connection conn1 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "");
Connection conn2 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=");
Connection conn3 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user");
}
}


Compliant code
class CipherExample {
public void foo() {
Connection conn4 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "password");
Connection conn5 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=text");
Connection conn6 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true&password=text", "AppLogin", "");
}
}
Security
Should Not Use getRequestedSessionId APIThis method returns the session ID specified by the client and may not be the same as the ID of the current valid session for this request. If the client does not mention a session ID, it returns null.
The session ID returned is either transmitted in a cookie or a URL parameter, hence by definition nothing prevents the end-user from manually updating the value of this session ID in the HTTP request.

More Info
- [CWE-807] - Reliance on Untrusted Inputs in a Security Decision

- [OWASP] - Broken Authentication

class Demo{
// Non-compliant code
public void method(HttpServletRequest request) {
if(isActiveSession(request.getRequestedSessionId()) ){

}
}
}

Security
Web Application Contains Main MethodThis method returns the session ID specified by the client and may not be the same as the ID of the current valid session for this request. If the client does not mention a session ID, it returns null.
The session ID returned is either transmitted in a cookie or a URL parameter, hence by definition nothing prevents the end-user from manually updating the value of this session ID in the HTTP request.

More Info

- [CWE-489] - Leftover Debug Code

- [OWASP] - Sensitive Data Exposure

class Demo{
// Non-compliant code
public void method(HttpServletRequest request) {
if(isActiveSession(request.getRequestedSessionId()) ){

}
}
}


```
Security
Authenticate LDAP Connection Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password. Therefore using these binds is strongly discouraged.

More Info

- [OWASP Top 10 2017 Category A2]- Broken Authentication

- [CWE-521] - Weak Password Requirements

- [ldapwiki.com] - Simple Authentication

//Non-compliant code
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none"); // Noncompliant

// Compliant code
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");

Security
Potential Command InjectionAvoid using unfiltered input to process executor APIs because that can lead to arbitrary command execution.

More Info

- [OWASP] - Command Injection

- [OWASP: Top 10 2013 A1] -Injection

- [CWE-78] - Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')


// Non-compliant code
import java.lang.Runtime;
class Demo{
Runtime r = Runtime.getRuntime();
r.exec("/bin/sh -c sometool" + input);
}

Security
Potential Path Traversal Path traversal is a web security vulnerability that allows an attacker to read arbitrary files on the server that is running an application.
This might include application code and data, credentials for back-end systems, and sensitive operating system files.

More Info
- [CWE-22] - Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

- [OWASP] - Path Traversal

// Non-compliant code
class Demo{
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", image); //Weak point

if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}

return Response.ok().entity(new FileInputStream(file)).build();
}

// Compliant code
}
import org.apache.commons.io.FilenameUtils;
class Demo1{
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", FilenameUtils.getName(image)); //Fix

if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}

return Response.ok().entity(new FileInputStream(file)).build();
}
}


Security
Accessing Android external storage is security-sensitiveFiles or data stored in the android application should be security-sensitive. Files can be globally readable or writable as they are stored on external storage.
Avoid storing sensitive information on the external storage as anyone can tamper with the data or remove the files by using any application.

**More Info**
- [OWASP Top 10 2017 Category A1](https://owasp.org/www-project-top-ten/2017/A1_2017-Injection.html) - Injection
- [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/2017/A3_2017-Sensitive_Data_Exposure) - Sensitive Data Exposure
- [CWE-312](https://cwe.mitre.org/data/definitions/312.html) - Cleartext Storage of Sensitive Information
- [CWE-20](https://cwe.mitre.org/data/definitions/20.html) - Improper Input Validation accessing android external storage


```java
//non-compliant
import android.content.Context;
import android.os.Environment;
public class AccessExternalFiles {
public void accessFiles(Context context) {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // non-compliant
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// non-compliant
}
}


Security
Using unsafe Jackson deserialization configuration is security-sensitiveJThe untrusted data could cause abuse to application logic. Jackson's deserialization should be configured securely.
Implement @JsonTypeName and @JsonSubTypes to prevent serialized data from an untrusted source. It can help to safeguard the data from external attackers.

**More Info**
- [OWASP Top 10 2017 Category A8](https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization) - Insecure Deserialization
- [CWE-502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data


//non-compliant
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(); // non-compliant
@JsonTypeInfo(use = Id.CLASS) // non-compliant
abstract class PhoneNumber {
}



Security
Setting JavaBean properties is security-sensitiveThe JavaBean property uses a set or get functions that are exposed to other applications. An attacker can modify its properties, attack malicious code that can be risky. Avoid storing sensitive information under this JavaBean property as it may help the user to retain its software integrity.

**More Info**
- [OWASP Top 10 2017 Category A8](https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization) - Insecure Deserialization
- [CWE-502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data


//non-compliant
class Demo{
Company bean = new Company();
HashMap map = new HashMap();
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
map.put(name, request.getParameterValues(name));
}
BeanUtils.populate(bean, map); // "map" is populated with data coming from user input, here "request.getParameterNames()"
}



Security
Run Should Not Be Called DirectlyThe program accidentally calls the Thread.run() method and causes the code to be executed in the current thread, just like any other method call. Instead, use Thread.start() to actually create a new thread so that the runnable's 'run()' method is executed in parallel.

More Info
[CWE-572] - Call to Thread run() instead of start()
Non-compliant code
class Demo {
Thread myThread = new Thread(runnable);
myThread.run();

}


Compliant code
class Demo {
Thread myThread = new Thread(runnable);
myThread.start();
}
Functionality, Efficiency
Exclude SpringBootApplication And ComponentScan From The Default PackageExclude "SpringBootApplication" and "@ComponentScan" from the default package.Non-compliant code
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage {
public static void main(String[] args)
{
SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.class, args);
}
}


Compliant code
package javacodechecker;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage {
public static void main(String[] args)
{
SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.class, args);
}
}
Efficiencyspring