Merge pull request #5141 from github/yo-h/java-flow-check-fix

Java: prepare to enforce additional compiler checks in test code
This commit is contained in:
Anders Schack-Mulligen
2021-02-15 09:41:03 +01:00
committed by GitHub
53 changed files with 166 additions and 159 deletions

View File

@@ -87,7 +87,7 @@ public class UnsafeCertTrustTest {
/**
* Test the endpoint identification of SSL engine is set to null
*/
public void testSSLEngineEndpointIdSetNull() {
public void testSSLEngineEndpointIdSetNull() throws java.security.NoSuchAlgorithmException {
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
@@ -98,7 +98,7 @@ public class UnsafeCertTrustTest {
/**
* Test the endpoint identification of SSL engine is not set
*/
public void testSSLEngineEndpointIdNotSet() {
public void testSSLEngineEndpointIdNotSet() throws java.security.NoSuchAlgorithmException {
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine();
}
@@ -106,7 +106,7 @@ public class UnsafeCertTrustTest {
/**
* Test the endpoint identification of SSL socket is not set
*/
public void testSSLSocketEndpointIdNotSet() {
public void testSSLSocketEndpointIdNotSet() throws java.security.NoSuchAlgorithmException, java.io.IOException {
SSLContext sslContext = SSLContext.getInstance("TLS");
final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket("www.example.com", 443);
@@ -115,7 +115,7 @@ public class UnsafeCertTrustTest {
/**
* Test the endpoint identification of regular socket is not set
*/
public void testSocketEndpointIdNotSet() {
public void testSocketEndpointIdNotSet() throws java.io.IOException {
SocketFactory socketFactory = SocketFactory.getDefault();
Socket socket = socketFactory.createSocket("www.example.com", 80);
}
@@ -127,4 +127,4 @@ public class UnsafeCertTrustTest {
// ConnectionFactory connectionFactory = new ConnectionFactory();
// connectionFactory.useSslProtocol();
// }
}
}

View File

@@ -29,7 +29,7 @@ class InsecureJavaMail {
final Session session = Session.getInstance(properties, authenticator);
}
public void testSimpleMail() {
public void testSimpleMail() throws Exception {
Email email = new SimpleEmail();
email.setHostName("config.hostName");
email.setSmtpPort(25);
@@ -42,4 +42,4 @@ class InsecureJavaMail {
email.addTo("toAddress");
email.send();
}
}
}

View File

@@ -20,7 +20,7 @@ public class CleartextStorageSharedPrefs extends Activity {
}
// GOOD - save sensitive information in encrypted format
public void testSetSharedPrefs2(Context context, String name, String password) {
public void testSetSharedPrefs2(Context context, String name, String password) throws Exception {
SharedPreferences sharedPrefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
Editor editor = sharedPrefs.edit();
editor.putString("name", encrypt(name));
@@ -28,7 +28,7 @@ public class CleartextStorageSharedPrefs extends Activity {
editor.commit();
}
private static String encrypt(String cleartext) {
private static String encrypt(String cleartext) throws Exception {
// Use an encryption or hashing algorithm in real world. The demo below just returns its hash.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(cleartext.getBytes(StandardCharsets.UTF_8));
@@ -37,7 +37,7 @@ public class CleartextStorageSharedPrefs extends Activity {
}
// GOOD - save sensitive information in encrypted format using separate variables
public void testSetSharedPrefs3(Context context, String name, String password) {
public void testSetSharedPrefs3(Context context, String name, String password) throws Exception {
String encUsername = encrypt(name);
String encPassword = encrypt(password);
SharedPreferences sharedPrefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
@@ -49,7 +49,7 @@ public class CleartextStorageSharedPrefs extends Activity {
// GOOD - save sensitive information using the built-in `EncryptedSharedPreferences` class in androidx
public void testSetSharedPrefs4(Context context, String name, String password) {
public void testSetSharedPrefs4(Context context, String name, String password) throws Exception {
MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
@@ -69,7 +69,7 @@ public class CleartextStorageSharedPrefs extends Activity {
}
// GOOD - save sensitive information using the built-in `EncryptedSharedPreferences` class in androidx
public void testSetSharedPrefs5(Context context, String name, String password) {
public void testSetSharedPrefs5(Context context, String name, String password) throws Exception {
MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
@@ -89,7 +89,7 @@ public class CleartextStorageSharedPrefs extends Activity {
}
// GOOD - save sensitive information using the built-in `EncryptedSharedPreferences` class in androidx
public void testSetSharedPrefs6(Context context, String name, String password) {
public void testSetSharedPrefs6(Context context, String name, String password) throws Exception {
MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();

View File

@@ -3,7 +3,7 @@ import java.security.spec.ECGenParameterSpec;
import javax.crypto.KeyGenerator;
public class InsufficientKeySize {
public void CryptoMethod() {
public void CryptoMethod() throws java.security.NoSuchAlgorithmException, java.security.InvalidAlgorithmParameterException {
KeyGenerator keyGen1 = KeyGenerator.getInstance("AES");
// BAD: Key size is less than 128
keyGen1.init(64);

View File

@@ -57,7 +57,7 @@ public class InsecureBasicAuth {
/**
* Test basic authentication with Apache HTTP POST request using the URI constructor with one argument.
*/
public void testApacheHttpRequest4(String username, String password) {
public void testApacheHttpRequest4(String username, String password) throws Exception {
String uriStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
URI uri = new URI(uriStr);
HttpRequestBase post = new HttpPost(uri);
@@ -74,7 +74,7 @@ public class InsecureBasicAuth {
/**
* Test basic authentication with Apache HTTP POST request using a URI constructor with multiple arguments.
*/
public void testApacheHttpRequest5(String username, String password) {
public void testApacheHttpRequest5(String username, String password) throws Exception {
HttpRequestBase post = new HttpPost(new URI("http", "www.example.com", "/test", "abc=123", null));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
@@ -122,7 +122,7 @@ public class InsecureBasicAuth {
/**
* Test basic authentication with Java HTTP URL connection using the `URL(String spec)` constructor.
*/
public void testHttpUrlConnection(String username, String password) {
public void testHttpUrlConnection(String username, String password) throws Exception {
String urlStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
@@ -136,7 +136,7 @@ public class InsecureBasicAuth {
/**
* Test basic authentication with Java HTTP URL connection using the `URL(String protocol, String host, String file)` constructor.
*/
public void testHttpUrlConnection2(String username, String password) {
public void testHttpUrlConnection2(String username, String password) throws Exception {
String host = "www.example.com";
String path = "/rest/getuser.do?uid=abcdx";
String protocol = "http";
@@ -152,7 +152,7 @@ public class InsecureBasicAuth {
/**
* Test basic authentication with Java HTTP URL connection using a constructor with private URL.
*/
public void testHttpUrlConnection3(String username, String password) {
public void testHttpUrlConnection3(String username, String password) throws Exception {
String host = "LOCALHOST";
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
@@ -161,4 +161,4 @@ public class InsecureBasicAuth {
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
}
}

View File

@@ -7,7 +7,7 @@ import javax.naming.ldap.InitialLdapContext;
public class InsecureLdapAuth {
// BAD - Test LDAP authentication in cleartext using `DirContext`.
public void testCleartextLdapAuth(String ldapUserName, String password) {
public void testCleartextLdapAuth(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://ad.your-server.com:389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -21,7 +21,7 @@ public class InsecureLdapAuth {
}
// BAD - Test LDAP authentication in cleartext using `DirContext`.
public void testCleartextLdapAuth(String ldapUserName, String password, String serverName) {
public void testCleartextLdapAuth(String ldapUserName, String password, String serverName) throws Exception {
String ldapUrl = "ldap://"+serverName+":389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -35,7 +35,7 @@ public class InsecureLdapAuth {
}
// GOOD - Test LDAP authentication over SSL.
public void testSslLdapAuth(String ldapUserName, String password) {
public void testSslLdapAuth(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldaps://ad.your-server.com:636";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -49,7 +49,7 @@ public class InsecureLdapAuth {
}
// GOOD - Test LDAP authentication over SSL.
public void testSslLdapAuth2(String ldapUserName, String password) {
public void testSslLdapAuth2(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://ad.your-server.com:636";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -64,7 +64,7 @@ public class InsecureLdapAuth {
}
// GOOD - Test LDAP authentication with SASL authentication.
public void testSaslLdapAuth(String ldapUserName, String password) {
public void testSaslLdapAuth(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://ad.your-server.com:389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -78,7 +78,7 @@ public class InsecureLdapAuth {
}
// GOOD - Test LDAP authentication in cleartext connecting to local LDAP server.
public void testCleartextLdapAuth2(String ldapUserName, String password) {
public void testCleartextLdapAuth2(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://localhost:389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -92,7 +92,7 @@ public class InsecureLdapAuth {
}
// BAD - Test LDAP authentication in cleartext using `InitialLdapContext`.
public void testCleartextLdapAuth3(String ldapUserName, String password) {
public void testCleartextLdapAuth3(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://ad.your-server.com:389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
@@ -107,7 +107,7 @@ public class InsecureLdapAuth {
// BAD - Test LDAP authentication in cleartext using `DirContext` and string literals.
public void testCleartextLdapAuth4(String ldapUserName, String password) {
public void testCleartextLdapAuth4(String ldapUserName, String password) throws Exception {
String ldapUrl = "ldap://ad.your-server.com:389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put("java.naming.factory.initial",
@@ -131,7 +131,7 @@ public class InsecureLdapAuth {
}
// GOOD - Test LDAP authentication with `ssl` configuration and basic authentication.
public void testCleartextLdapAuth5(String ldapUserName, String password, String serverName) {
public void testCleartextLdapAuth5(String ldapUserName, String password, String serverName) throws Exception {
String ldapUrl = "ldap://"+serverName+":389";
Hashtable<String, String> environment = new Hashtable<String, String>();
setSSL(environment);
@@ -143,7 +143,7 @@ public class InsecureLdapAuth {
}
// BAD - Test LDAP authentication with basic authentication.
public void testCleartextLdapAuth6(String ldapUserName, String password, String serverName) {
public void testCleartextLdapAuth6(String ldapUserName, String password, String serverName) throws Exception {
String ldapUrl = "ldap://"+serverName+":389";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,

View File

@@ -26,7 +26,7 @@ public class SpringSSRF extends HttpServlet {
String fooResourceUrl = request2.getParameter("uri");;
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = new HttpEntity<>(new String("bar"));
try {
{
ResponseEntity<String> response =
restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
@@ -68,5 +68,6 @@ public class SpringSSRF extends HttpServlet {
{
restTemplate.put(fooResourceUrl, new String("object"));
}
} catch (org.springframework.web.client.RestClientException | java.net.URISyntaxException e) {}
}
}

View File

@@ -43,28 +43,28 @@ class Test {
new Bogus().exec("Irrelevant version of exec");
}
void apacheExecute1() {
void apacheExecute1() throws IOException {
String line = "AcroRd32.exe /p /h some.file";
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
}
void apacheExecute2() {
void apacheExecute2() throws IOException {
String line = "AcroRd32.exe /p /h some.file";
CommandLine cmdLine = CommandLine.parse(line, null);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
}
void apacheExecute3() {
void apacheExecute3() throws IOException {
CommandLine cmdLine = new CommandLine("AcroRd32.exe");
cmdLine.addArguments("/p /h some.file");
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
}
void apacheExecute4() {
void apacheExecute4() throws IOException {
CommandLine cmdLine = new CommandLine("AcroRd32.exe");
cmdLine.addArguments("/p /h some.file", false);
DefaultExecutor executor = new DefaultExecutor();

View File

@@ -1,5 +1,5 @@
class Test {
public static void main(String[] args) {
public static void main(String[] args) throws java.io.IOException {
// Relative paths
Runtime.getRuntime().exec("make");
Runtime.getRuntime().exec("m");

View File

@@ -88,8 +88,8 @@ public class CommentedCode {
* &nbsp ;
* &nbsp ;
*/
return -1;
}
// public static int commentedOutMethod(){
//
// return 123;

View File

@@ -32,7 +32,7 @@ public class A {
case 0: return p;
case 1: return s;
case 2: return b1.getElem();
case 3: return b2.getElem();
default:return b2.getElem();
}
}
};

View File

@@ -8,7 +8,7 @@ import java.util.List;
import org.apache.commons.io.IOUtils;
class Test {
public static void ioutils() {
public static void ioutils() throws java.io.FileNotFoundException, java.io.IOException {
InputStream inp = new FileInputStream("test"); // user input
InputStream buf = IOUtils.buffer(inp);

View File

@@ -14,7 +14,7 @@ class Test {
return "tainted";
}
public static void jacksonObjectMapper() {
public static void jacksonObjectMapper() throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException {
String s = taint();
ObjectMapper om = new ObjectMapper();
File file = new File("testFile");
@@ -32,7 +32,7 @@ class Test {
System.out.println(reconstructed);
}
public static void jacksonObjectWriter() {
public static void jacksonObjectWriter() throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException {
String s = taint();
ObjectWriter ow = new ObjectWriter();
File file = new File("testFile");

View File

@@ -15,7 +15,7 @@ public class A {
sink(b2);
}
void test2() {
void test2() throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream();
bOutput.write(taint());
byte[] b = bOutput.toByteArray();
@@ -25,11 +25,11 @@ public class A {
sink(b2);
}
void streamWrite(ByteArrayOutputStream baos, byte[] data) {
void streamWrite(ByteArrayOutputStream baos, byte[] data) throws IOException {
baos.write(data);
}
void test3(ByteArrayOutputStream baos) {
void test3(ByteArrayOutputStream baos) throws IOException {
streamWrite(baos, taint());
sink(baos.toByteArray());
}
@@ -38,11 +38,11 @@ public class A {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
}
void streamWriteHolder(BaosHolder bh, byte[] data) {
void streamWriteHolder(BaosHolder bh, byte[] data) throws IOException {
bh.baos.write(data);
}
void test4(BaosHolder bh) {
void test4(BaosHolder bh) throws IOException {
streamWriteHolder(bh, taint());
sink(bh.baos.toByteArray());
}
@@ -51,7 +51,7 @@ public class A {
byte[] data = new byte[10];
}
void test5_a(DataHolder dh) {
void test5_a(DataHolder dh) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(taint());
bais.read(dh.data);
test5_b(dh);

View File

@@ -11,7 +11,7 @@ public class B {
public static void sink(Object o) { }
public static void maintest() {
public static void maintest() throws java.io.UnsupportedEncodingException, java.net.MalformedURLException {
String[] args = taint();
// tainted - access to main args
String[] aaaargs = args;

View File

@@ -4,21 +4,21 @@ import android.app.Activity;
public class IntentSources extends Activity {
public void test() {
public void test() throws java.io.IOException {
String trouble = this.getIntent().getStringExtra("key");
Runtime.getRuntime().exec(trouble);
}
public void test2() {
public void test2() throws java.io.IOException {
String trouble = getIntent().getStringExtra("key");
Runtime.getRuntime().exec(trouble);
}
public void test3() {
public void test3() throws java.io.IOException {
String trouble = getIntent().getExtras().getString("key");
Runtime.getRuntime().exec(trouble);
@@ -29,9 +29,9 @@ public class IntentSources extends Activity {
class OtherClass {
public void test(IntentSources is) {
public void test(IntentSources is) throws java.io.IOException {
String trouble = is.getIntent().getStringExtra("key");
Runtime.getRuntime().exec(trouble);
}
}
}

View File

@@ -4,5 +4,5 @@ import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RmiFlow extends Remote {
String listDirectory(String path);
String listDirectory(String path) throws java.io.IOException;
}

View File

@@ -1,13 +1,13 @@
package security.library.dataflow;
public class RmiFlowImpl implements RmiFlow {
public String listDirectory(String path) {
public String listDirectory(String path) throws java.io.IOException {
String command = "ls " + path;
Runtime.getRuntime().exec(command);
return "pretend there are some results here";
}
public String notRemotable(String path) {
public String notRemotable(String path) throws java.io.IOException {
String command = "ls " + path;
Runtime.getRuntime().exec(command);
return "pretend there are some results here";

View File

@@ -5,21 +5,21 @@
| A.java:41:5:41:53 | getInputStream(...) | A.java:41:5:41:53 | getInputStream(...) |
| A.java:42:5:42:45 | getInputStream(...) | A.java:42:5:42:45 | getInputStream(...) |
| A.java:43:5:43:47 | getHostName(...) | A.java:43:5:43:47 | getHostName(...) |
| IntentSources.java:9:20:9:35 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1057:19:1057:32 | parameter this |
| IntentSources.java:9:20:9:35 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1059:19:1059:32 | parameter this |
| IntentSources.java:9:20:9:35 | getIntent(...) | IntentSources.java:9:20:9:35 | getIntent(...) |
| IntentSources.java:9:20:9:35 | getIntent(...) | IntentSources.java:9:20:9:57 | getStringExtra(...) |
| IntentSources.java:9:20:9:35 | getIntent(...) | IntentSources.java:10:29:10:35 | trouble |
| IntentSources.java:16:20:16:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1057:19:1057:32 | parameter this |
| IntentSources.java:16:20:16:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1059:19:1059:32 | parameter this |
| IntentSources.java:16:20:16:30 | getIntent(...) | IntentSources.java:16:20:16:30 | getIntent(...) |
| IntentSources.java:16:20:16:30 | getIntent(...) | IntentSources.java:16:20:16:52 | getStringExtra(...) |
| IntentSources.java:16:20:16:30 | getIntent(...) | IntentSources.java:17:29:17:35 | trouble |
| IntentSources.java:23:20:23:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1356:19:1356:27 | parameter this |
| IntentSources.java:23:20:23:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/os/BaseBundle.java:599:19:599:27 | parameter this |
| IntentSources.java:23:20:23:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1358:19:1358:27 | parameter this |
| IntentSources.java:23:20:23:30 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/os/BaseBundle.java:600:19:600:27 | parameter this |
| IntentSources.java:23:20:23:30 | getIntent(...) | IntentSources.java:23:20:23:30 | getIntent(...) |
| IntentSources.java:23:20:23:30 | getIntent(...) | IntentSources.java:23:20:23:42 | getExtras(...) |
| IntentSources.java:23:20:23:30 | getIntent(...) | IntentSources.java:23:20:23:59 | getString(...) |
| IntentSources.java:23:20:23:30 | getIntent(...) | IntentSources.java:24:29:24:35 | trouble |
| IntentSources.java:33:20:33:33 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1057:19:1057:32 | parameter this |
| IntentSources.java:33:20:33:33 | getIntent(...) | ../../../stubs/google-android-9.0.0/android/content/Intent.java:1059:19:1059:32 | parameter this |
| IntentSources.java:33:20:33:33 | getIntent(...) | IntentSources.java:33:20:33:33 | getIntent(...) |
| IntentSources.java:33:20:33:33 | getIntent(...) | IntentSources.java:33:20:33:55 | getStringExtra(...) |
| IntentSources.java:33:20:33:33 | getIntent(...) | IntentSources.java:34:29:34:35 | trouble |

View File

@@ -36,7 +36,7 @@ class ViableCallable {
i2.f("", 0l);
}
<TMock> TMock Mock() { throw new Exception(); }
<TMock> TMock Mock() { throw new Error(); }
void CreateTypeInstance() {
Run(new C2<Boolean>(), null, null, null);
@@ -63,7 +63,7 @@ abstract class C1<T1_C1, T2_C1> {
M(x, 8);
}
public void f(T1_C1 x, T2_C1 y) { throw new Exception(); }
public void f(T1_C1 x, T2_C1 y) { throw new Error(); }
}
interface I1<T_I1> {
@@ -80,27 +80,27 @@ interface I2<T_I2> {
class C2<T_C2> extends C1<String, T_C2> implements I1<T_C2> {
@Override
public <T3_C2> T_C2 M(String x, T3_C2 y) { throw new Exception(); }
public <T3_C2> T_C2 M(String x, T3_C2 y) { throw new Error(); }
}
class C3 extends C1<String, Long> implements I2<Long> {
@Override
public <T3_C3> Long M(String x, T3_C3 y) { throw new Exception(); }
public <T3_C3> Long M(String x, T3_C3 y) { throw new Error(); }
}
class C4<T_C4> extends C1<T_C4[], Boolean> {
@Override
public <T3_C4> Boolean M(T_C4[] x, T3_C4 y) { throw new Exception(); }
public <T3_C4> Boolean M(T_C4[] x, T3_C4 y) { throw new Error(); }
}
class C5 extends C1<String, Boolean> {
@Override
public <T3_C5> Boolean M(String x, T3_C5 y) { throw new Exception(); }
public <T3_C5> Boolean M(String x, T3_C5 y) { throw new Error(); }
}
class C6<T1_C6, T2_C6> extends C1<T1_C6, T2_C6> {
@Override
public <T3_C6> T2_C6 M(T1_C6 x, T3_C6 y) { throw new Exception(); }
public <T3_C6> T2_C6 M(T1_C6 x, T3_C6 y) { throw new Error(); }
public void Run(T1_C6 x) {
// Viable callables: C6.M(), C7.M()
@@ -113,7 +113,7 @@ class C6<T1_C6, T2_C6> extends C1<T1_C6, T2_C6> {
class C7<T1_C7> extends C6<T1_C7, Byte> {
@Override
public <T3_C7> Byte M(T1_C7 x, T3_C7 y) { throw new Exception(); }
public <T3_C7> Byte M(T1_C7 x, T3_C7 y) { throw new Error(); }
public void Run(T1_C7 x) {
// Viable callables: C7.M()
@@ -129,11 +129,11 @@ class C7<T1_C7> extends C6<T1_C7, Byte> {
class C8<T_C8, T2_C8> extends C1<String, T2_C8> {
@Override
public <T3_C8> T2_C8 M(String x, T3_C8 y) { throw new Exception(); }
public <T3_C8> T2_C8 M(String x, T3_C8 y) { throw new Error(); }
}
class C9<T_C9> extends C8<Boolean, Boolean> {
@Override
public <T3_C9> Boolean M(String x, T3_C9 y) { throw new Exception(); }
public <T3_C9> Boolean M(String x, T3_C9 y) { throw new Error(); }
}

View File

@@ -20,10 +20,10 @@ class ViableCallable2 {
}
class A {
public void m() { throw new Exception(); }
public void m() { throw new Error(); }
}
class B extends A {
@Override
public void m() { throw new Exception(); }
public void m() { throw new Error(); }
}

View File

@@ -41,7 +41,7 @@ public class Logic {
}
private static void checkTrue(boolean b, String msg) {
if (!b) throw new Exception(msg);
if (!b) throw new Error (msg);
}
private static void checkFalse(boolean b, String msg) {

View File

@@ -3,7 +3,7 @@ class Test {
void test(int x) {
z = 0;
if (x < 0) {
throw new Exception();
throw new Error();
}
int y = 0;
while(x >= 0) {

View File

@@ -18,7 +18,7 @@ class PathCreation {
File f = new File(new File("dir"), "sub");
}
public void testNewFileWithURI() {
public void testNewFileWithURI() throws java.net.URISyntaxException {
File f = new File(new URI("dir"));
}
@@ -27,7 +27,7 @@ class PathCreation {
Path p2 = Path.of("dir", "sub");
}
public void testPathOfWithURI() {
public void testPathOfWithURI() throws java.net.URISyntaxException {
Path p = Path.of(new URI("dir"));
}
@@ -36,7 +36,7 @@ class PathCreation {
Path p2 = Paths.get("dir", "sub");
}
public void testPathsGetWithURI() {
public void testPathsGetWithURI() throws java.net.URISyntaxException {
Path p = Paths.get(new URI("dir"));
}
@@ -53,19 +53,19 @@ class PathCreation {
Path p = Path.of("dir").resolve("sub");
}
public void testNewFileWriterWithString() {
public void testNewFileWriterWithString() throws java.io.IOException {
FileWriter fw = new FileWriter("dir");
}
public void testNewFileReaderWithString() {
public void testNewFileReaderWithString() throws java.io.FileNotFoundException {
FileReader fr = new FileReader("dir");
}
public void testNewFileOutputStreamWithString() {
public void testNewFileOutputStreamWithString() throws java.io.FileNotFoundException {
FileOutputStream fos = new FileOutputStream("dir");
}
public void testNewFileInputStreamWithString() {
public void testNewFileInputStreamWithString() throws java.io.FileNotFoundException {
FileInputStream fis = new FileInputStream("dir");
}
}

View File

@@ -14,7 +14,7 @@ public class ReflectiveAccess {
return classContainingAnnotation.getAnnotation(annotationClass);
}
public static void main(String[] args) {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> testClass = Class.forName("reflection.ReflectiveAccess$TestClass");
testClass.newInstance();

View File

@@ -5,8 +5,8 @@ class TestThrow2 {
{
try {
thrower();
} catch (Exception e) {
} catch (Throwable e) {
;
}
}
}
}

View File

@@ -100,7 +100,7 @@ class CloseReader {
private void init(InputStreamReader reader) {
fileRd = new BufferedReader(reader);
}
public void readStuff() {
public void readStuff() throws java.io.IOException {
System.out.println(fileRd.readLine());
fileRd.close();
}

View File

@@ -30,21 +30,21 @@ public class A {
break;
} while (c.cond());
// --- while, for loops ---
while (false) {
if (c.cond())
continue; // GOOD [never reached, if the condition changed so it was then the result would no longer apply]
if (c.cond())
break;
}
for (i = 0; false; i++) {
if (c.cond())
continue; // GOOD [never reached, if the condition changed so it was then the result would no longer apply]
if (c.cond())
break;
}
// --- nested loops ---

View File

@@ -1,10 +1,10 @@
class IAmAGoodCloneable implements Cloneable {
public Object clone() {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Sub1 extends IAmAGoodCloneable { public Object clone() { return super.clone(); } }
class Sub1 extends IAmAGoodCloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } }
class IAmABadCloneable implements Cloneable {
public Object clone() {

View File

@@ -3,7 +3,7 @@ class GoodReturn {
@Override
public int hashCode() {
getClass().hashCode();
return getClass().hashCode();
}
@Override

View File

@@ -171,7 +171,7 @@ public class C {
private void verifyBool(boolean b) {
if (!b) {
throw new Exception();
throw new Error();
}
}
@@ -192,7 +192,7 @@ public class C {
private void verifyNotNull(Object obj) {
if (obj == null) {
throw new Exception();
throw new Error();
}
}

View File

@@ -5,7 +5,7 @@ public class A {
public A(int[] arr2, int n) {
if (arr2.length % 2 != 0)
throw new Exception();
throw new Error();
this.arr2 = arr2;
this.arr3 = new int[n << 1];
}
@@ -168,7 +168,7 @@ public class A {
if (n > 0) {
a = n > 0 ? new int[3 * n] : null;
}
int sum;
int sum = 0;
if (a != null) {
for (int i = 0; i < a.length; i += 3) {
sum += a[i + 2]; // OK

View File

@@ -7,9 +7,9 @@ class UseBraces
void f() { }
void g() { }
void h() { }
void test()
void test(boolean bb)
{
int x, y;
int x = 0, y;
int[] branches = new int[10];
// If-then statement
@@ -67,27 +67,27 @@ class UseBraces
// While statement
while(false)
while(bb)
{
f();
}
g(); // No alert
while(false)
while(bb)
f();
g();
while(false)
while(bb )
f();
g(); // Alert
g(); // No alert
while(false)
while(bb )
f(); g(); // Alert
while(false)
while(bb)
if (x != 0) x = 1;
// Do-while statement

View File

@@ -3,7 +3,7 @@ class Test {
void test(int x) {
z = getInt();
if (x < 0 || z < 0) {
throw new Exception();
throw new Error();
}
int y = 0;
if (x >= 0) y++; // useless test due to test in line 5 being false

View File

@@ -7,7 +7,7 @@ public class A {
new Object();
} catch(Exception e) {
if (e == null) { // Useless check
throw new Exception();
throw new Error();
}
}
}
@@ -16,7 +16,7 @@ public class A {
if (o instanceof A) {
A a = (A)o;
if (a != null) { // Useless check
throw new Exception();
throw new Error();
}
}
}

View File

@@ -16,7 +16,7 @@ public class ReflectionTest {
public int shadowedField;
}
public static void main(String[] args) {
public static void main(String[] args) throws NoSuchFieldException {
// Ensure the two classes are live, otherwise we might hide some results
new ParentClass();
new ChildClass();

View File

@@ -19,7 +19,7 @@ public class ReflectionMethodTest {
public void test4() { }
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException {
// Get class by name
Class.forName("ReflectionTest$TestObject1").getMethod("test1");
// Use classloader

View File

@@ -3,7 +3,7 @@ import java.nio.file.*;
import java.util.zip.*;
public class ZipTest {
public void m1(ZipEntry entry, File dir) {
public void m1(ZipEntry entry, File dir) throws Exception {
String name = entry.getName();
File file = new File(dir, name);
FileOutputStream os = new FileOutputStream(file); // ZipSlip
@@ -11,7 +11,7 @@ public class ZipTest {
FileWriter fw = new FileWriter(file); // ZipSlip
}
public void m2(ZipEntry entry, File dir) {
public void m2(ZipEntry entry, File dir) throws Exception {
String name = entry.getName();
File file = new File(dir, name);
File canFile = file.getCanonicalFile();
@@ -21,7 +21,7 @@ public class ZipTest {
FileOutputStream os = new FileOutputStream(file); // OK
}
public void m3(ZipEntry entry, File dir) {
public void m3(ZipEntry entry, File dir) throws Exception {
String name = entry.getName();
File file = new File(dir, name);
if (!file.toPath().normalize().startsWith(dir.toPath()))
@@ -29,20 +29,20 @@ public class ZipTest {
FileOutputStream os = new FileOutputStream(file); // OK
}
private void validate(File tgtdir, File file) {
private void validate(File tgtdir, File file) throws Exception {
File canFile = file.getCanonicalFile();
if (!canFile.toPath().startsWith(tgtdir.toPath()))
throw new Exception();
}
public void m4(ZipEntry entry, File dir) {
public void m4(ZipEntry entry, File dir) throws Exception {
String name = entry.getName();
File file = new File(dir, name);
validate(dir, file);
FileOutputStream os = new FileOutputStream(file); // OK
}
public void m5(ZipEntry entry, File dir) {
public void m5(ZipEntry entry, File dir) throws Exception {
String name = entry.getName();
File file = new File(dir, name);
Path absfile = file.toPath().toAbsolutePath().normalize();
@@ -52,7 +52,7 @@ public class ZipTest {
FileOutputStream os = new FileOutputStream(file); // OK
}
public void m6(ZipEntry entry, Path dir) {
public void m6(ZipEntry entry, Path dir) throws Exception {
String canonicalDest = dir.toFile().getCanonicalPath();
Path target = dir.resolve(entry.getName());
String canonicalTarget = target.toFile().getCanonicalPath();

View File

@@ -3,7 +3,7 @@ import java.util.List;
import java.util.ArrayList;
class Test {
public static void shellCommand(String arg) {
public static void shellCommand(String arg) throws java.io.IOException {
ProcessBuilder pb = new ProcessBuilder("/bin/bash -c echo " + arg);
pb.start();
@@ -25,7 +25,7 @@ class Test {
pb.start();
}
public static void nonShellCommand(String arg) {
public static void nonShellCommand(String arg) throws java.io.IOException {
ProcessBuilder pb = new ProcessBuilder("./customTool " + arg);
pb.start();
@@ -46,7 +46,7 @@ class Test {
pb.start();
}
public static void relativeCommand() {
public static void relativeCommand() throws java.io.IOException {
ProcessBuilder pb = new ProcessBuilder("ls");
pb.start();
@@ -54,11 +54,11 @@ class Test {
pb.start();
}
public static void main(String[] args) {
public static void main(String[] args) throws java.io.IOException {
String arg = args.length > 1 ? args[1] : "default";
shellCommand(arg);
nonShellCommand(arg);
relativeCommand();
}
}
}

View File

@@ -66,7 +66,7 @@ public class UnsafeHostnameVerification {
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
verify(hostname, session.getPeerCertificates());
try { verify(hostname, session.getPeerCertificates()); } catch (Exception e) { throw new RuntimeException(); }
return true; // GOOD [but detected as BAD]. The verification of the certificate is done in
// another method and
// in the case of a mismatch, an `Exception` is thrown so the `return true`

View File

@@ -3,7 +3,7 @@ import javax.net.ssl.HttpsURLConnection;
import java.io.*;
class Test {
public void m1(HttpURLConnection connection) {
public void m1(HttpURLConnection connection) throws java.io.IOException {
InputStream input;
if (connection instanceof HttpsURLConnection) {
input = connection.getInputStream(); // OK

View File

@@ -31,7 +31,7 @@ class Test {
return true;
}
public void doConnect(int desiredPort, String username) {
public void doConnect(int desiredPort, String username) throws Exception {
ServerSocket listenSocket = new ServerSocket(desiredPort);
if (isAuthenticated(username)) {
@@ -56,7 +56,7 @@ class Test {
}
public void doConnectChannel(int desiredPort, String username) {
public void doConnectChannel(int desiredPort, String username) throws Exception {
ServerSocketChannel listenChannel = ServerSocketChannel.open();
SocketAddress port = new InetSocketAddress(desiredPort);
listenChannel.bind(port);

View File

@@ -9,32 +9,32 @@ import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.Yaml;
public class A {
public Object deserialize1(Socket sock) {
public Object deserialize1(Socket sock) throws java.io.IOException, ClassNotFoundException {
InputStream inputStream = sock.getInputStream();
ObjectInputStream in = new ObjectInputStream(inputStream);
return in.readObject(); // unsafe
}
public Object deserialize2(Socket sock) {
public Object deserialize2(Socket sock) throws java.io.IOException, ClassNotFoundException {
InputStream inputStream = sock.getInputStream();
ObjectInputStream in = new ObjectInputStream(inputStream);
return in.readUnshared(); // unsafe
}
public Object deserialize3(Socket sock) {
public Object deserialize3(Socket sock) throws java.io.IOException {
InputStream inputStream = sock.getInputStream();
XMLDecoder d = new XMLDecoder(inputStream);
return d.readObject(); // unsafe
}
public Object deserialize4(Socket sock) {
public Object deserialize4(Socket sock) throws java.io.IOException {
XStream xs = new XStream();
InputStream inputStream = sock.getInputStream();
Reader reader = new InputStreamReader(inputStream);
return xs.fromXML(reader); // unsafe
}
public void deserialize5(Socket sock) {
public void deserialize5(Socket sock) throws java.io.IOException {
Kryo kryo = new Kryo();
Input input = new Input(sock.getInputStream());
A a1 = kryo.readObject(input, A.class); // unsafe
@@ -42,20 +42,20 @@ public class A {
Object o = kryo.readClassAndObject(input); // unsafe
}
private Kryo getSafeKryo() {
private Kryo getSafeKryo() throws java.io.IOException {
Kryo kryo = new Kryo();
kryo.setRegistrationRequired(true);
// ... kryo.register(A.class) ...
return kryo;
}
public void deserialize6(Socket sock) {
public void deserialize6(Socket sock) throws java.io.IOException {
Kryo kryo = getSafeKryo();
Input input = new Input(sock.getInputStream());
Object o = kryo.readClassAndObject(input); // OK
}
public void deserializeSnakeYaml(Socket sock) {
public void deserializeSnakeYaml(Socket sock) throws java.io.IOException {
Yaml yaml = new Yaml();
InputStream input = sock.getInputStream();
Object o = yaml.load(input); //unsafe
@@ -65,7 +65,7 @@ public class A {
A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //unsafe
}
public void deserializeSnakeYaml2(Socket sock) {
public void deserializeSnakeYaml2(Socket sock) throws java.io.IOException {
Yaml yaml = new Yaml(new Constructor());
InputStream input = sock.getInputStream();
Object o = yaml.load(input); //unsafe
@@ -75,7 +75,7 @@ public class A {
A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //unsafe
}
public void deserializeSnakeYaml3(Socket sock) {
public void deserializeSnakeYaml3(Socket sock) throws java.io.IOException {
Yaml yaml = new Yaml(new SafeConstructor());
InputStream input = sock.getInputStream();
Object o = yaml.load(input); //OK
@@ -85,7 +85,7 @@ public class A {
A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //OK
}
public void deserializeSnakeYaml4(Socket sock) {
public void deserializeSnakeYaml4(Socket sock) throws java.io.IOException {
Yaml yaml = new Yaml(new Constructor(A.class));
InputStream input = sock.getInputStream();
Object o = yaml.load(input); //OK

View File

@@ -3,19 +3,19 @@ import java.net.Socket;
import com.alibaba.fastjson.JSON;
public class B {
public Object deserializeJson1(Socket sock) {
public Object deserializeJson1(Socket sock) throws java.io.IOException {
InputStream inputStream = sock.getInputStream();
return JSON.parseObject(inputStream, null); // unsafe
}
public Object deserializeJson2(Socket sock) {
public Object deserializeJson2(Socket sock) throws java.io.IOException {
InputStream inputStream = sock.getInputStream();
byte[] bytes = new byte[100];
inputStream.read(bytes);
return JSON.parse(bytes); // unsafe
}
public Object deserializeJson3(Socket sock) {
public Object deserializeJson3(Socket sock) throws java.io.IOException {
InputStream inputStream = sock.getInputStream();
byte[] bytes = new byte[100];
inputStream.read(bytes);
@@ -23,7 +23,7 @@ public class B {
return JSON.parseObject(s); // unsafe
}
public Object deserializeJson4(Socket sock) {
public Object deserializeJson4(Socket sock) throws java.io.IOException {
InputStream inputStream = sock.getInputStream();
byte[] bytes = new byte[100];
inputStream.read(bytes);

View File

@@ -102,7 +102,7 @@ class DocumentBuilderTests {
builder.parse(source.getInputStream()); //unsafe
}
private static DocumentBuilderFactory getDocumentBuilderFactory() {
private static DocumentBuilderFactory getDocumentBuilderFactory() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String feature = "";
feature = "http://xml.org/sax/features/external-parameter-entities";
@@ -115,8 +115,8 @@ class DocumentBuilderTests {
private static final ThreadLocal<DocumentBuilder> XML_DOCUMENT_BUILDER = new ThreadLocal<DocumentBuilder>() {
@Override
protected DocumentBuilder initialValue() {
DocumentBuilderFactory factory = getDocumentBuilderFactory();
try {
DocumentBuilderFactory factory = getDocumentBuilderFactory();
return factory.newDocumentBuilder();
} catch (Exception ex) {
throw new RuntimeException(ex);

View File

@@ -31,11 +31,11 @@ class Test {
new FileInputStream(f2);
}
public static void readFile(File f) {
public static void readFile(File f) throws java.io.FileNotFoundException {
new FileReader(f);
}
public static void setWorldWritable(File f) {
f.setWritable(true, false);
}
}
}

View File

@@ -1,4 +1,4 @@
| MethodAccessLockOrder.java:29:4:29:40 | transferFrom(...) | Synchronization here and $@ may be performed in reverse order starting $@ and result in deadlock. | MethodAccessLockOrder.java:8:21:8:41 | subtract(...) | here | MethodAccessLockOrder.java:31:4:31:40 | transferFrom(...) | here |
| MethodAccessLockOrder.java:29:11:29:47 | transferFrom(...) | Synchronization here and $@ may be performed in reverse order starting $@ and result in deadlock. | MethodAccessLockOrder.java:8:21:8:41 | subtract(...) | here | MethodAccessLockOrder.java:31:11:31:47 | transferFrom(...) | here |
| ReentrantLockOrder.java:11:4:11:21 | lock(...) | Synchronization here and $@ may be performed in reverse order starting $@ and result in deadlock. | ReentrantLockOrder.java:12:4:12:21 | lock(...) | here | ReentrantLockOrder.java:28:4:28:21 | lock(...) | here |
| ReentrantLockOrder.java:28:4:28:21 | lock(...) | Synchronization here and $@ may be performed in reverse order starting $@ and result in deadlock. | ReentrantLockOrder.java:29:4:29:21 | lock(...) | here | ReentrantLockOrder.java:11:4:11:21 | lock(...) | here |
| SynchronizedStmtLockOrder.java:8:16:8:26 | primaryLock | Synchronization here and $@ may be performed in reverse order starting $@ and result in deadlock. | SynchronizedStmtLockOrder.java:9:17:9:27 | savingsLock | here | SynchronizedStmtLockOrder.java:22:16:22:26 | savingsLock | here |

View File

@@ -26,9 +26,9 @@ class MethodAccessLockOrder {
public boolean initiateTransfer(boolean fromSavings, int amount) {
// AVOID: inconsistent lock order
if (fromSavings) {
primary.transferFrom(savings, amount);
return primary.transferFrom(savings, amount);
} else {
savings.transferFrom(primary, amount);
return savings.transferFrom(primary, amount);
}
}

View File

@@ -1019,6 +1019,7 @@ public class Activity {
* @see Activity#requireViewById(int)
*/
public <T> T findViewById(int id) {
return null;
}
/**
@@ -1141,4 +1142,4 @@ public class Activity {
*/
public void startActivities(Intent[] intents, Bundle options) {
}
}
}

View File

@@ -821,6 +821,7 @@ public class Intent implements Parcelable, Cloneable {
*/
@Deprecated
public static Intent getIntent(String uri) {
return null;
}
/**
@@ -845,6 +846,7 @@ public class Intent implements Parcelable, Cloneable {
* @see #toUri
*/
public static Intent parseUri(String uri, int flags) {
return null;
}
/**
@@ -2069,4 +2071,4 @@ public class Intent implements Parcelable, Cloneable {
return null;
}
}
}

View File

@@ -97,6 +97,7 @@ public class BaseBundle {
* @hide
*/
public String getPairValue() {
return null;
}
/**

View File

@@ -229,6 +229,7 @@ public final class Parcel {
}
public final float[] createFloatArray() {
return null;
}
public final void readFloatArray(float[] val) {

View File

@@ -85,6 +85,7 @@ public final class EncryptedSharedPreferences implements SharedPreferences {
PrefKeyEncryptionScheme prefKeyEncryptionScheme,
PrefValueEncryptionScheme prefValueEncryptionScheme)
throws GeneralSecurityException, IOException {
return null;
}
/**
@@ -168,4 +169,4 @@ public final class EncryptedSharedPreferences implements SharedPreferences {
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
}
}
}