diff --git a/src/main/java/javacodechecker/AccessingAndroidExternalStorage.java b/src/main/java/javacodechecker/AccessingAndroidExternalStorage.java new file mode 100644 index 0000000..212ff3b --- /dev/null +++ b/src/main/java/javacodechecker/AccessingAndroidExternalStorage.java @@ -0,0 +1,14 @@ +package javacodechecker; + +import android.content.Context; +import android.os.Environment; + +public class AccessingAndroidExternalStorage { + + public void accessFiles(Context context) { + // EMB-ISSUE: CodeIssueNames.ACCESSING_ANDROID_EXTERNAL_STORAGE + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // Sensitive + // EMB-ISSUE: CodeIssueNames.ACCESSING_ANDROID_EXTERNAL_STORAGE + context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); // Sensitive + } +} diff --git a/src/main/java/javacodechecker/AuthenticateLDAPConnection.java b/src/main/java/javacodechecker/AuthenticateLDAPConnection.java new file mode 100644 index 0000000..b172265 --- /dev/null +++ b/src/main/java/javacodechecker/AuthenticateLDAPConnection.java @@ -0,0 +1,17 @@ +package javacodechecker; + +import java.util.Hashtable; + +public class AuthenticateLDAPConnection { + public void method() { + Hashtable env = new Hashtable(); + + // Set up the environment for creating the initial context + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); + + // EMB-ISSUE: CodeIssueNames.AUTHENTICATE_LDAP_CONNECTION + env.put(Context.SECURITY_AUTHENTICATION, "none"); + + } +} diff --git a/src/main/java/javacodechecker/Big Integer Instantiation b/src/main/java/javacodechecker/Big Integer Instantiation new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/java/javacodechecker/Big Integer Instantiation @@ -0,0 +1 @@ + diff --git a/src/main/java/javacodechecker/CompileRegularExpressionsOnce.java b/src/main/java/javacodechecker/CompileRegularExpressionsOnce.java new file mode 100644 index 0000000..ad37fc1 --- /dev/null +++ b/src/main/java/javacodechecker/CompileRegularExpressionsOnce.java @@ -0,0 +1,25 @@ +package javacodechecker; + +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class CompileRegularExpressionsOnce { + Pattern pattern2 = Pattern.compile("(.*)"); + + void findText(String inputText) { + // EMB-ISSUE: CodeIssueNames.COMPILE_REGULAR_EXPRESSIONS_ONCE + Pattern pattern = Pattern.compile("(.*)"); + Matcher matcher = pattern.matcher(inputText); + if(matcher.find()) { + MatchResult result = matcher.toMatchResult(); + } + } + + void findText2(String inputText) { + Matcher matcher = pattern2.matcher(inputText); + if(matcher.find()) { + MatchResult result = matcher.toMatchResult(); + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/ComplexRegexPattern.java b/src/main/java/javacodechecker/ComplexRegexPattern.java new file mode 100644 index 0000000..c1a0cdf --- /dev/null +++ b/src/main/java/javacodechecker/ComplexRegexPattern.java @@ -0,0 +1,23 @@ +package javacodechecker; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Test case for ComplexRegexPattern + * @author bhides + * + */ +class ComplexRegexPattern { + public void method() { + String regex = "(a+)+"; + // EMB-ISSUE: CodeIssueNames.COMPLEX_REGEXPATTERN + Pattern r = Pattern.compile(regex); + + // Now create matcher object. + Matcher m = r.matcher(""); + + // EMB-ISSUE: CodeIssueNames.COMPLEX_REGEXPATTERN + Pattern r2 = Pattern.compile("(a+)+"); + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/DatabasesShouldBePasswordProtected.java b/src/main/java/javacodechecker/DatabasesShouldBePasswordProtected.java new file mode 100644 index 0000000..9d79a40 --- /dev/null +++ b/src/main/java/javacodechecker/DatabasesShouldBePasswordProtected.java @@ -0,0 +1,26 @@ +package javacodechecker; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DatabasesShouldBePasswordProtected { + + public void method() throws SQLException { + String password = "password"; + + //EMB-ISSUE:CodeIssueNames.DatabasesShouldBePasswordProtected + Connection conn = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", ""); + + // Next 3 have password + Connection conn1 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", password); + Connection conn2 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=text"); + Connection conn3 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true&password=text", "AppLogin", ""); + + //EMB-ISSUE:CodeIssueNames.DatabasesShouldBePasswordProtected + Connection conn4 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password="); + + //EMB-ISSUE:CodeIssueNames.DatabasesShouldBePasswordProtected + Connection conn5 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user"); + } +} diff --git a/src/main/java/javacodechecker/DisabledSpringSecuritysCSRF.java b/src/main/java/javacodechecker/DisabledSpringSecuritysCSRF.java new file mode 100644 index 0000000..0511fca --- /dev/null +++ b/src/main/java/javacodechecker/DisabledSpringSecuritysCSRF.java @@ -0,0 +1,33 @@ +package javacodechecker; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +@Configuration +@EnableWebSecurity +public class DisabledSpringSecuritysCSRF extends WebSecurityConfigurerAdapter { + + private static final String TEST_ROUTE = "/testroute/"; + + @Bean + protected HttpFirewall strictFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHttpMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + return firewall; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // EMB-ISSUE:CodeIssueNames.DISABLED_SPRING_SECURITYS_CSRF + http.authorizeRequests().mvcMatchers(HttpMethod.GET, TEST_ROUTE).permitAll().anyRequest().denyAll().and().csrf() + .disable(); + http.headers().contentSecurityPolicy("default-src 'self'"); + } + +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/EmptyCatchBlock.java b/src/main/java/javacodechecker/EmptyCatchBlock.java new file mode 100644 index 0000000..c2fc29b --- /dev/null +++ b/src/main/java/javacodechecker/EmptyCatchBlock.java @@ -0,0 +1,16 @@ +package javacodechecker; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +class EmptyCatchBlock { + public static void main(String[] args) { + try { + FileInputStream in = new FileInputStream(new File("")); + } + // EMB-ISSUE: CodeIssueNames.EMPTY_CATCH_BLOCK + catch (FileNotFoundException e) { + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor.java b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor.java new file mode 100644 index 0000000..62d87c0 --- /dev/null +++ b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor.java @@ -0,0 +1,23 @@ +package javacodechecker; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +//EMB-ISSUE: CodeIssueNames.EXTERNALIZABLE_MUST_HAVE_NO_ARGUMENTS_CONSTRUCTOR +public class ExternalizableMustHaveNoArgumentsConstructor implements Externalizable { + private String name; + private int age; + + + public void newMethod() { + + } + public ExternalizableMustHaveNoArgumentsConstructor(String name, int age) { + this.name = name; + this.age = age; + } + + +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor2.java b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor2.java new file mode 100644 index 0000000..b86ba1d --- /dev/null +++ b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor2.java @@ -0,0 +1,15 @@ +package javacodechecker; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +//EMB-ISSUE: CodeIssueNames.EXTERNALIZABLE_MUST_HAVE_NO_ARGUMENTS_CONSTRUCTOR/no-detect +public class ExternalizableMustHaveNoArgumentsConstructor2 implements Externalizable { + private String name; + private int age; + + public ExternalizableMustHaveNoArgumentsConstructor2() { + + } \ No newline at end of file diff --git a/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor3.java b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor3.java new file mode 100644 index 0000000..c8c9df9 --- /dev/null +++ b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor3.java @@ -0,0 +1,10 @@ +package javacodechecker; + +import java.io.Externalizable; + +//EMB-ISSUE: CodeIssueNames.EXTERNALIZABLE_MUST_HAVE_NO_ARGUMENTS_CONSTRUCTOR/no-detect +public class ExternalizableMustHaveNoArgumentsConstructor3 implements Externalizable { + private String name; + private int age; + +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor4.java b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor4.java new file mode 100644 index 0000000..890cc20 --- /dev/null +++ b/src/main/java/javacodechecker/ExternalizableMustHaveNoArgumentsConstructor4.java @@ -0,0 +1,23 @@ +package javacodechecker; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + + +//EMB-ISSUE: CodeIssueNames.EXTERNALIZABLE_MUST_HAVE_NO_ARGUMENTS_CONSTRUCTOR/no-detect +public class ExternalizableMustHaveNoArgumentsConstructor4 implements Externalizable { + private String name; + private int age; + + public ExternalizableMustHaveNoArgumentsConstructor4(String name, int age) { + this.name = name; + this.age = age; + } + + public ExternalizableMustHaveNoArgumentsConstructor4() { + + } + +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/GettersAndSettersShouldAccessTheExpectedFields.java b/src/main/java/javacodechecker/GettersAndSettersShouldAccessTheExpectedFields.java new file mode 100644 index 0000000..c86154b --- /dev/null +++ b/src/main/java/javacodechecker/GettersAndSettersShouldAccessTheExpectedFields.java @@ -0,0 +1,54 @@ +package javacodechecker; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +class GettersAndSettersShouldAccessTheExpectedFields { + + private int x ,y ,z; + + private boolean active; + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS + public void setX(int val) { + //this is for test + this.y = val; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS + public int getY() { + return this.x; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS + public boolean isActive() + { + return x; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS + public void setActive(boolean b) + { + this.y = b; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS/no-detect + public int getName() { + System.out.println(" "); + return this.x; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS/no-detect + public void setName(int val) { + System.out.println(" "); + this.y = val; + } + + // EMB-ISSUE: CodeIssueNames.GETTERS_AND_SETTERS_SHOULD_ACCESS_THE_EXPECTED_FIELDS/no-detect + public void setZ(int val) { + this.z = val; + } + + +} diff --git a/src/main/java/javacodechecker/InitializationOfSecureRandomAtMethodLevel.java b/src/main/java/javacodechecker/InitializationOfSecureRandomAtMethodLevel.java new file mode 100644 index 0000000..3ff3ae7 --- /dev/null +++ b/src/main/java/javacodechecker/InitializationOfSecureRandomAtMethodLevel.java @@ -0,0 +1,21 @@ +package javacodechecker; + +import java.security.SecureRandom; + +class InitializationOfSecureRandomAtMethodLevel { + //Non-compliant code + public int generateSecureKey() { + // EMB-ISSUE: CodeIssueNames.INITIALIZATION_OF_SECURE_RANDOM_AT_METHOD_LEVEL + SecureRandom secureRandom = new SecureRandom(); + return secureRandom.nextInt(); + } +} + +//compliant code +class SecureRandomGenerator { + // EMB-ISSUE: CodeIssueNames.INITIALIZATION_OF_SECURE_RANDOM_AT_METHOD_LEVEL/no-detect + static SecureRandom secureRandom = new SecureRandom(); + public int generateSecureKey() { + return secureRandom.nextInt(); + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/InvalidLoggingClassName.java b/src/main/java/javacodechecker/InvalidLoggingClassName.java new file mode 100644 index 0000000..15e506a --- /dev/null +++ b/src/main/java/javacodechecker/InvalidLoggingClassName.java @@ -0,0 +1,10 @@ +package javacodechecker; + +import org.apache.logging.log4j.Logger; + +public class InvalidLoggingClassName { + + // EMB-ISSUE: CodeIssueNames.INVALID_LOGGING_CLASS_NAME + private static Logger logger = org.apache.logging.log4j.LogManager + .getLogger(SomeOtherClass.class); +} diff --git a/src/main/java/javacodechecker/NonPrivateFieldAccessInSynchronizedBlock.java b/src/main/java/javacodechecker/NonPrivateFieldAccessInSynchronizedBlock.java new file mode 100644 index 0000000..fef27c3 --- /dev/null +++ b/src/main/java/javacodechecker/NonPrivateFieldAccessInSynchronizedBlock.java @@ -0,0 +1,58 @@ +/*- + * ---license-start + * Corona-Warn-App + * --- + * Copyright (C) 2020 SAP SE and all other contributors + * --- + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---license-end + */ + +package javacodechecker; + +import static app.coronawarn.server.services.submission.controller.SubmissionController.SUBMISSION_ROUTE; +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import app.coronawarn.server.services.submission.monitoring.SubmissionMonitor; +import io.micrometer.core.annotation.Timed; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.DeferredResult; + +@RestController +@RequestMapping("/version/v1") + +public class NonPrivateFieldAccessInSynchronizedBlock { + + public int counter = 0; + + public DeferredResult> fakeRequest(@RequestHeader("fake") Integer fake) { + + synchronized (this) { + // EMB-ISSUE: CodeIssueNames.NON_PRIVATE_FIELD_ACCESS_IN_SYNCHRONIZED_BLOCK + counter++; + try { + java.lang.Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + return deferredResult; + } + } diff --git a/src/main/java/javacodechecker/PossibleThreadLeakInExecutorService.java b/src/main/java/javacodechecker/PossibleThreadLeakInExecutorService.java new file mode 100644 index 0000000..5a8abbb --- /dev/null +++ b/src/main/java/javacodechecker/PossibleThreadLeakInExecutorService.java @@ -0,0 +1,40 @@ +package javacodechecker; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class PossibleThreadLeakInExecutorService { + ExecutorService executorService2 = Executors.newSingleThreadExecutor(); + + public void process1() { + + System.out.println("test"); + System.out.println("test"); + + System.out.println("test"); + System.out.println("test"); + + executorService2.shutdown(); + } + + public void process2() { + System.out.println("test"); + System.out.println("test"); + + // EMB-ISSUE: CodeIssueNames.POSSIBLE_THREAD_LEAK_IN_EXECUTOR_SERVICE + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + System.out.println("test"); + // doTask(); + } catch (Exception e) { + //logger.error("indexing failed", e); + } + } + }); + System.out.println("test"); + System.out.println("test"); + } +} diff --git a/src/main/java/javacodechecker/PotentialCommandInjection.java b/src/main/java/javacodechecker/PotentialCommandInjection.java new file mode 100644 index 0000000..6c72635 --- /dev/null +++ b/src/main/java/javacodechecker/PotentialCommandInjection.java @@ -0,0 +1,22 @@ +package javacodechecker; + +import java.io.IOException; + +public class PotentialCommandInjection { + + @GET + @Path("/images/{image}") + @Produces("images/*") + public void method(@javax.ws.rs.PathParam("image") String image) throws IOException { + Runtime r = Runtime.getRuntime(); + + // EMB-ISSUE: CodeIssueNames.POTENTIAL_COMMAND_INJECTION + r.exec("/bin/sh -c some_tool" + image); + + + String rdpFilePath = myObject.getRdpFilePath(); + ProcessBuilder processBuilder = new ProcessBuilder(); + // EMB-ISSUE: CodeIssueNames.POTENTIAL_COMMAND_INJECTION + processBuilder.command("mstsc", image).start(); + } +} diff --git a/src/main/java/javacodechecker/PotentialPathTraversal.java b/src/main/java/javacodechecker/PotentialPathTraversal.java new file mode 100644 index 0000000..5406ecb --- /dev/null +++ b/src/main/java/javacodechecker/PotentialPathTraversal.java @@ -0,0 +1,39 @@ +package javacodechecker; + +import java.io.File; +import java.io.FileInputStream; + +import javax.net.ssl.SSLEngineResult.Status; +import javax.xml.ws.Response; + +import org.apache.commons.io.FilenameUtils; + +public class PotentialPathTraversal { + + @GET + @Path("/images/{image}") + @Produces("images/*") + public Response getImage(@javax.ws.rs.PathParam("image") String image) { + // EMB-ISSUE: CodeIssueNames.POTENTIAL_PATH_TRAVERSAL + 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(); + } + + @GET + @Path("/images/{image}") + @Produces("images/*") + public Response getImage2(@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(); + } +} diff --git a/src/main/java/javacodechecker/ReadOnlyTransaction.java b/src/main/java/javacodechecker/ReadOnlyTransaction.java new file mode 100644 index 0000000..eb43b3e --- /dev/null +++ b/src/main/java/javacodechecker/ReadOnlyTransaction.java @@ -0,0 +1,22 @@ +package javacodechecker; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.transaction.annotation.Transactional; + +class Demo { + @Transactional + public class UserRepository { + // EMB-ISSUE: CodeIssueNames.READ_ONLY_TRANSACTION + @Query("select username from users") + public List getAllUsers() { + } + } + + @Transactional(readOnly=true) + public class UserRepositoryNoDetect { + // EMB-ISSUE: CodeIssueNames.READ_ONLY_TRANSACTION/no-detect + @Query("select username from users") + public List getAllUsers() { + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/RequestedSessionIdShouldNotBeUsed.java b/src/main/java/javacodechecker/RequestedSessionIdShouldNotBeUsed.java new file mode 100644 index 0000000..532631a --- /dev/null +++ b/src/main/java/javacodechecker/RequestedSessionIdShouldNotBeUsed.java @@ -0,0 +1,11 @@ +package javacodechecker; + +public class RequestedSessionIdShouldNotBeUsed { + + public void method(HttpServletRequest request) { + // EMB-ISSUE: CodeIssueNames.REQUESTED_SESSION_ID_SHOULD_NOT_BE_USED + if(isActiveSession(request.getRequestedSessionId()) ){ + + } + } +} diff --git a/src/main/java/javacodechecker/ResourceLeak.java b/src/main/java/javacodechecker/ResourceLeak.java new file mode 100644 index 0000000..1c366c4 --- /dev/null +++ b/src/main/java/javacodechecker/ResourceLeak.java @@ -0,0 +1,102 @@ +package javacodechecker; + + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Reader; + +class ResourceLeak { + public void process1() { + try { + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true))); + out.println("the text"); + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK + out.close(); //close() is in try clause + + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + FileOutputStream in = new FileOutputStream("xanadu.txt"); + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK + in.close(); + } catch (IOException e) { + } + } + + public void processk() { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + PrintWriter out = null; + try { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + out = new PrintWriter(new File("")); + out.println("the text"); + } catch (IOException e) { + } finally { + if(true) { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + out.close(); + } + } + } + + public void testExceptionBlock() throws IOException { + Reader reader = null; + try { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + reader = new FileReader(""); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + //Need to fix this + reader.close(); + } finally { + if (reader != null) { + try { + int k; + int t; + int kk; + int tt; + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + reader.close(); + } catch (IOException e) { + } finally { + + } + } + } + } + + //Non-compliant code + //resource is not closed anywhere + public void process2() { + try { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true))); + out.println("the text"); + } catch (IOException e) { + } + } + + public void process3() { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + try (PrintWriter out2 = new PrintWriter(new File(""))) { +// out2.println("the text"); + } catch (IOException e) { + } + } + + PrintWriter outk = null; + + public void processK() { + try { + // EMB-ISSUE: CodeIssueNames.RESOURCE_LEAK/no-detect + if(null != outk) + outk.close(); + } catch (Exception e) { + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/ReturnEmptyArrayOrCollectionInsteadOfNull.java b/src/main/java/javacodechecker/ReturnEmptyArrayOrCollectionInsteadOfNull.java new file mode 100644 index 0000000..1eed470 --- /dev/null +++ b/src/main/java/javacodechecker/ReturnEmptyArrayOrCollectionInsteadOfNull.java @@ -0,0 +1,21 @@ +package javacodechecker; + + +import java.util.ArrayList; +import java.util.List; + +class ReturnEmptyArrayOrCollectionInsteadOfNull { + + private void method() { + getStringArray(); + } + + private List getStringArray() { + // EMB-ISSUE: CodeIssueNames.RETURN_EMPTY_ARRAY_OR_COLLECTION_INSTEADOF_NULL + return null; + } + + private List getStringArray2() { + return new ArrayList(); + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/RunFinalizersOnExitShouldNotBeCalled.java b/src/main/java/javacodechecker/RunFinalizersOnExitShouldNotBeCalled.java new file mode 100644 index 0000000..cfe4f99 --- /dev/null +++ b/src/main/java/javacodechecker/RunFinalizersOnExitShouldNotBeCalled.java @@ -0,0 +1,10 @@ + +package javacodechecker; +public class RunFinalizersOnExitShouldNotBeCalled +{ + public static void runFinalizersOnExit(boolean value) { + // EMB-ISSUE: CodeIssueNames.RUN_FINALIZERS_ON_EXIT_SHOULD_NOT_BE_CALLED + System.runFinalizersOnExit(value); + +} +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/RunShouldNotBeCalledDirectly.java b/src/main/java/javacodechecker/RunShouldNotBeCalledDirectly.java new file mode 100644 index 0000000..bf3fa17 --- /dev/null +++ b/src/main/java/javacodechecker/RunShouldNotBeCalledDirectly.java @@ -0,0 +1,11 @@ +package javacodechecker; + +public class RunShouldNotBeCalledDirectly { + + public void method() { + Thread myThread = new Thread(); + // EMB-ISSUE: CodeIssueNames.RUN_SHOULD_NOT_BE_CALLED_DIRECTLY + myThread.run(); + } + +} diff --git a/src/main/java/javacodechecker/SecuritySensitiveRegularExpression.java b/src/main/java/javacodechecker/SecuritySensitiveRegularExpression.java new file mode 100644 index 0000000..13312df --- /dev/null +++ b/src/main/java/javacodechecker/SecuritySensitiveRegularExpression.java @@ -0,0 +1,8 @@ +package javacodechecker; + + +class SecuritySensitiveRegularExpression { + public static void main(String[] args) { + //TODO: exmple + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/SettingJavaBeanProperties.java b/src/main/java/javacodechecker/SettingJavaBeanProperties.java new file mode 100644 index 0000000..d191e0b --- /dev/null +++ b/src/main/java/javacodechecker/SettingJavaBeanProperties.java @@ -0,0 +1,16 @@ +package javacodechecker; + +public class SettingJavaBeanProperties { + + public void method() { + 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)); + } + // EMB-ISSUE: CodeIssueNames.SETTING_JAVA_BEAN_PROPERTIES + BeanUtils.populate(bean, map); // Sensitive + } +} diff --git a/src/main/java/javacodechecker/SleepInSynchronisedBlock.java b/src/main/java/javacodechecker/SleepInSynchronisedBlock.java new file mode 100644 index 0000000..ff23fee --- /dev/null +++ b/src/main/java/javacodechecker/SleepInSynchronisedBlock.java @@ -0,0 +1,32 @@ +package javacodechecker; + + +class SleepInSynchronisedBlock { + + private Object lock = new Object(); + + void m1() { + for(int i = 0; i < 10; ++i) { + + synchronized(lock) { + try { + /* + * EMB-ISSUE: Sleep In Synchronized Block + */ + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public synchronized void m2() { + try { +// EMB-ISSUE: Sleep In Synchronized Block + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.java b/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.java new file mode 100644 index 0000000..6d6ba6d --- /dev/null +++ b/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.java @@ -0,0 +1,10 @@ + +import org.springframework.boot.SpringApplication; +//EMB-ISSUE: CodeIssueNames.SPRINGBOOTAPPLICATION_AND_COMPONENTSCAN_NOT_BE_USED_IN_DEFAULT_PACKAGE +@ComponentScan(exclude=Book.class,scanBasePackages={"net.javabeat"}) +public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage { + public static void main(String[] args) + { + SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackageExample.java b/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackageExample.java new file mode 100644 index 0000000..8592092 --- /dev/null +++ b/src/main/java/javacodechecker/SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackageExample.java @@ -0,0 +1,10 @@ +package javacodechecker; +import org.springframework.boot.SpringApplication; +//EMB-ISSUE: CodeIssueNames.SPRINGBOOTAPPLICATION_AND_COMPONENTSCAN_NOT_BE_USED_IN_DEFAULT_PACKAGE/no-detect +@SpringBootApplication +public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackageExample { + public static void main(String[] args) + { + SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackageExample.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/TightlyCoupledClass.java b/src/main/java/javacodechecker/TightlyCoupledClass.java new file mode 100644 index 0000000..cb1c829 --- /dev/null +++ b/src/main/java/javacodechecker/TightlyCoupledClass.java @@ -0,0 +1,19 @@ +package javacodechecker; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; + +class Demo { + + class UserServiceImpl { + + } + + @Controller + @RequestMapping("/users") + public class UserController { + @Autowired + // EMB-ISSUE: CodeIssueNames.TIGHTLY_COUPLED_CLASS + UserServiceImpl userServiceImpl; + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/UnsafeJacksonDeserialization.java b/src/main/java/javacodechecker/UnsafeJacksonDeserialization.java new file mode 100644 index 0000000..3514fd4 --- /dev/null +++ b/src/main/java/javacodechecker/UnsafeJacksonDeserialization.java @@ -0,0 +1,12 @@ +package javacodechecker; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class UnsafeJacksonDeserialization { + + public void method() { + ObjectMapper mapper = new ObjectMapper(); + // EMB-ISSUE: CodeIssueNames.UNSAFE_JACKSON_DESERIALIZATION + mapper.enableDefaultTyping(); + } +} diff --git a/src/main/java/javacodechecker/VariablesShouldNotBeSelfAssigned.java b/src/main/java/javacodechecker/VariablesShouldNotBeSelfAssigned.java new file mode 100644 index 0000000..7954579 --- /dev/null +++ b/src/main/java/javacodechecker/VariablesShouldNotBeSelfAssigned.java @@ -0,0 +1,16 @@ +package javacodechecker; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; + +public class VariablesShouldNotBeSelfAssigned { + + public void setName(String name, String surName) { + // EMB-ISSUE: CodeIssueNames.VARIABLES_SHOULD_NOT_BE_SELF_ASSIGNED + String surName = surName; + name = name; + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/WeakCipherAlgorithm.java b/src/main/java/javacodechecker/WeakCipherAlgorithm.java new file mode 100644 index 0000000..9514246 --- /dev/null +++ b/src/main/java/javacodechecker/WeakCipherAlgorithm.java @@ -0,0 +1,23 @@ +package javacodechecker; + + +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.NullCipher; + +class WeakCipherAlgorithm { + public static void main(String[] args) { + + final String RCVIER = "RC4"; + try { + Cipher c1 = Cipher.getInstance("DES"); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search + Cipher c7 = NullCipher.getInstance("DESede"); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack + Cipher c13 = javax.crypto.Cipher.getInstance("RC2"); // Noncompliant: RC2 is vulnerable to a related-key attack + Cipher c19 = Cipher.getInstance(RCVIER); // Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) Cipher c25 = Cipher.getInstance("Blowfish"); // Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks NullCipher nc = new NullCipher(); // Noncompliant: the NullCipher class provides an "identity cipher" one that does not transform or encrypt the plaintext in any way. + } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/javacodechecker/WebApplicationContainsMainMethod.java b/src/main/java/javacodechecker/WebApplicationContainsMainMethod.java new file mode 100644 index 0000000..3ba1335 --- /dev/null +++ b/src/main/java/javacodechecker/WebApplicationContainsMainMethod.java @@ -0,0 +1,17 @@ +package javacodechecker; + +import java.io.IOException; + +public class WebApplicationContainsMainMethod extends HttpServlet { + + public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + if (userIsAuthorized(req)) { + updatePrices(req); + } + } + + // EMB-ISSUE: CodeIssueNames.WEB_APPLICATION_CONTAINS_MAIN_METHOD + public static void main(String[] args) { // Noncompliant + updatePrices(req); + } +}