repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
codeql
codeql-master/java/ql/test/query-tests/security/CWE-327/semmle/tests/Test.java
// Semmle test case for CWE-327: Use of a Broken or Risky Cryptographic Algorithm // http://cwe.mitre.org/data/definitions/327.html package test.cwe327.semmle.tests; import javax.crypto.*; import javax.crypto.spec.*; import java.security.*; class Test { public void test() { try { String input = "ABCDEFG123456"; KeyGenerator keyGenerator; SecretKeySpec secretKeySpec; Cipher cipher; { // BAD: DES is a weak algorithm keyGenerator = KeyGenerator.getInstance("DES"); } // GOOD: RSA is a strong algorithm // NB: in general the algorithms used in the various stages must be // the same, but for testing purposes we will vary them keyGenerator = KeyGenerator.getInstance("RSA"); /* Perform initialization of KeyGenerator */ keyGenerator.init(112); SecretKey secretKey = keyGenerator.generateKey(); byte[] byteKey = secretKey.getEncoded(); { // BAD: foo is an unknown algorithm that may not be secure secretKeySpec = new SecretKeySpec(byteKey, "foo"); } // GOOD: GCM is a strong algorithm secretKeySpec = new SecretKeySpec(byteKey, "GCM"); { // BAD: RC2 is a weak algorithm cipher = Cipher.getInstance("RC2"); } // GOOD: ECIES is a strong algorithm cipher = Cipher.getInstance("ECIES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8")); } catch (Exception e) { // fail } } }
1,445
25.777778
81
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-079/semmle/tests/XSS.java
// Test case for // CWE-079: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // http://cwe.mitre.org/data/definitions/79.html package test.cwe079.cwe.examples; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class XSS extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // BAD: a request parameter is written directly to the Servlet response stream response.getWriter().print( "The page \"" + request.getParameter("page") + "\" was not found."); // BAD: a request parameter is written directly to an error response page response.sendError(HttpServletResponse.SC_NOT_FOUND, "The page \"" + request.getParameter("page") + "\" was not found."); // GOOD: escape HTML characters first response.sendError(HttpServletResponse.SC_NOT_FOUND, "The page \"" + encodeForHtml(request.getParameter("page")) + "\" was not found."); // FALSE NEGATIVE: passed through function that is not a secure check response.sendError(HttpServletResponse.SC_NOT_FOUND, "The page \"" + capitalizeName(request.getParameter("page")) + "\" was not found."); // BAD: outputting the path of the resource response.getWriter().print("The path section of the URL was " + request.getPathInfo()); // BAD: typical XSS, this time written to an OutputStream instead of a Writer response.getOutputStream().write(request.getPathInfo().getBytes()); } /** * Replace special characters in the given text such that it can * be inserted into an HTML file and not be interpreted as including * any HTML tags. */ static String encodeForHtml(String text) { // This is just a stub. For an example of a real implementation, see // the OWASP Java Encoder Project. return text.replace("<", "&lt;"); } static String capitalizeName(String text) { return text.replace("foo inc", "Foo, Inc."); } }
2,145
32.015385
96
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-732/semmle/tests/Test.java
import java.io.File; import java.io.FileReader; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.Set; class Test { public static void main(String[] args) throws IOException { // Using the File API File f = new File("file"); setWorldWritable(f); readFile(f); // Using the Path API Path p = Paths.get("file"); Set<PosixFilePermission> filePermissions = EnumSet.of(PosixFilePermission.OTHERS_WRITE); Files.setPosixFilePermissions(p, filePermissions); Files.readAllLines(p); // Convert file to path File f2 = new File("file2"); Set<PosixFilePermission> file2Permissions = new LinkedHashSet<>(); file2Permissions.add(PosixFilePermission.OTHERS_WRITE); Files.setPosixFilePermissions(Paths.get(f2.getCanonicalPath()), file2Permissions); new FileInputStream(f2); } public static void readFile(File f) { new FileReader(f); } public static void setWorldWritable(File f) { f.setWritable(true, false); } }
1,159
27.292683
90
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-022/semmle/tests/Test.java
// Semmle test case for CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') // http://cwe.mitre.org/data/definitions/22.html package test.cwe22.semmle.tests; import java.io.IOException; import java.io.File; import java.net.InetAddress; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.FileSystems; class Test { void doGet1(InetAddress address) throws IOException { String temp = address.getHostName(); File file; Path path; // BAD: construct a file path with user input file = new File(temp); // BAD: construct a path with user input path = Paths.get(temp); // BAD: construct a path with user input path = FileSystems.getDefault().getPath(temp); } void doGet2(InetAddress address) throws IOException { String temp = address.getHostName(); File file; // GOOD: check string is safe if(isSafe(temp)) file = new File(temp); } void doGet3(InetAddress address) throws IOException { String temp = address.getHostName(); File file; // FALSE NEGATIVE: inadequate check - fails to account // for '.'s if(isSortOfSafe(temp)) file = new File(temp); } boolean isSafe(String pathSpec) { // no file separators if (pathSpec.contains(File.separator)) return false; // at most one dot int indexOfDot = pathSpec.indexOf('.'); if (indexOfDot != -1 && pathSpec.indexOf('.', indexOfDot + 1) != -1) return false; return true; } boolean isSortOfSafe(String pathSpec) { // no file separators if (pathSpec.contains(File.separator)) return false; return true; } }
1,633
21.694444
110
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-022/semmle/tests/ZipTest.java
import java.io.*; import java.nio.file.*; import java.util.zip.*; public class ZipTest { public void m1(ZipEntry entry, File dir) { String name = entry.getName(); File file = new File(dir, name); FileOutputStream os = new FileOutputStream(file); // ZipSlip RandomAccessFile raf = new RandomAccessFile(file, "rw"); // ZipSlip FileWriter fw = new FileWriter(file); // ZipSlip } public void m2(ZipEntry entry, File dir) { String name = entry.getName(); File file = new File(dir, name); File canFile = file.getCanonicalFile(); String canDir = dir.getCanonicalPath(); if (!canFile.toPath().startsWith(canDir)) throw new Exception(); FileOutputStream os = new FileOutputStream(file); // OK } public void m3(ZipEntry entry, File dir) { String name = entry.getName(); File file = new File(dir, name); if (!file.toPath().normalize().startsWith(dir.toPath())) throw new Exception(); FileOutputStream os = new FileOutputStream(file); // OK } private void validate(File tgtdir, File file) { File canFile = file.getCanonicalFile(); if (!canFile.toPath().startsWith(tgtdir.toPath())) throw new Exception(); } public void m4(ZipEntry entry, File dir) { 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) { String name = entry.getName(); File file = new File(dir, name); Path absfile = file.toPath().toAbsolutePath().normalize(); Path absdir = dir.toPath().toAbsolutePath().normalize(); if (!absfile.startsWith(absdir)) throw new Exception(); FileOutputStream os = new FileOutputStream(file); // OK } public void m6(ZipEntry entry, Path dir) { String canonicalDest = dir.toFile().getCanonicalPath(); Path target = dir.resolve(entry.getName()); String canonicalTarget = target.toFile().getCanonicalPath(); if (!canonicalTarget.startsWith(canonicalDest + File.separator)) throw new Exception(); OutputStream os = Files.newOutputStream(target); // OK } }
2,162
32.796875
71
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-835/semmle/tests/InfiniteLoop.java
class Test { public void bad() { for (int i=0; i<10; i++) { for (int j=0; i<10; j++) { // potentially infinite loop due to test on wrong variable if (shouldBreak()) break; } } } private boolean shouldBreak() { return Math.random() < 0.5; } }
338
23.214286
74
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-335/semmle/tests/Test.java
// Semmle test case for CWE-335: Use of a predictable seed in a secure random number generator // http://cwe.mitre.org/data/definitions/335.html package test.cwe335.semmle.tests; import java.util.Random; import java.security.SecureRandom; import java.math.BigInteger; class Test { public void test() { long time1 = System.currentTimeMillis(); long time2 = System.nanoTime(); // GOOD: We only care about SecureRandom generators. Random r = new Random(time1); r.nextInt(); // GOOD: SecureRandom initialized with random seed. SecureRandom r1 = new SecureRandom(); byte[] random_seed = new BigInteger(Long.toString(r1.nextLong())).toByteArray(); SecureRandom r2 = new SecureRandom(random_seed); r2.nextInt(); // BAD: SecureRandom initialized with times. SecureRandom r_time1 = new SecureRandom(new BigInteger(Long.toString(time1)).toByteArray()); // BAD: SecureRandom initialized with times. SecureRandom r_time2 = new SecureRandom(new BigInteger(Long.toString(time2)).toByteArray()); r_time1.nextInt(); r_time2.nextInt(); // BAD: SecureRandom initialized with constant value. SecureRandom r_const = new SecureRandom(new BigInteger(Long.toString(12345L)).toByteArray()); r_const.nextInt(); // BAD: SecureRandom's seed set to constant with setSeed. SecureRandom r_const_set = new SecureRandom(); r_const_set.setSeed(12345L); r_const_set.nextInt(); // GOOD: SecureRandom self seeded and then seed is supplemented. SecureRandom r_selfseed = new SecureRandom(); r_selfseed.nextInt(); r_selfseed.setSeed(12345L); r_selfseed.nextInt(); // GOOD: SecureRandom seed set to something random. SecureRandom r_random_set = new SecureRandom(); r_random_set.setSeed(random_seed); r_random_set.nextInt(); // GOOD: SecureRandom seeded with a bad seed but then seed is supplemented. SecureRandom r_suplseed = new SecureRandom(); r_suplseed.setSeed(12345L); r_suplseed.setSeed(random_seed); r_suplseed.nextInt(); // GOOD: SecureRandom seeded with composite seed that is partially random. SecureRandom r_composite = new SecureRandom(); r_composite.setSeed(0L + r1.nextLong()); r_composite.nextInt(); } }
2,191
34.354839
95
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-833/semmle/tests/MethodAccessLockOrder.java
class MethodAccessLockOrder { private Account primary = new Account(); private Account savings = new Account(); class Account { private int balance; public synchronized boolean transferFrom(Account malo, int amount) { int subtracted = malo.subtract(amount); if (subtracted == amount) { balance += subtracted; return true; } return false; } public synchronized int subtract(int amount) { if (amount>0 && balance>amount) { balance -= amount; return amount; } return 0; } } public boolean initiateTransfer(boolean fromSavings, int amount) { // AVOID: inconsistent lock order if (fromSavings) { primary.transferFrom(savings, amount); } else { savings.transferFrom(primary, amount); } } }
756
20.027778
70
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-833/semmle/tests/SynchronizedStmtLockOrder.java
class SynchronizedStmtLockOrder { private int primaryAccountBalance; private Object primaryLock = new Object(); private int savingsAccountBalance; private Object savingsLock = new Object(); public boolean transferToSavings(int amount) { synchronized(primaryLock) { synchronized(savingsLock) { if (amount>0 && primaryAccountBalance>=amount) { primaryAccountBalance -= amount; savingsAccountBalance += amount; return true; } } } return false; } public boolean transferToPrimary(int amount) { // AVOID: lock order is different from "transferToSavings" // and may result in deadlock synchronized(savingsLock) { synchronized(primaryLock) { if (amount>0 && savingsAccountBalance>=amount) { savingsAccountBalance -= amount; primaryAccountBalance += amount; return true; } } } return false; } }
870
24.617647
60
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-833/semmle/tests/ReentrantLockOrder.java
import java.util.concurrent.locks.ReentrantLock; class ReentrantLockOrder { private int primaryAccountBalance; private final ReentrantLock primaryLock = new ReentrantLock(); private int savingsAccountBalance; private final ReentrantLock savingsLock = new ReentrantLock(); public boolean transferToSavings(int amount) { try { primaryLock.lock(); savingsLock.lock(); if (amount>0 && primaryAccountBalance>=amount) { primaryAccountBalance -= amount; savingsAccountBalance += amount; return true; } } finally { savingsLock.unlock(); primaryLock.unlock(); } return false; } public boolean transferToPrimary(int amount) { // AVOID: lock order is different from "transferToSavings" // and may result in deadlock try { savingsLock.lock(); primaryLock.lock(); if (amount>0 && primaryAccountBalance>=amount) { primaryAccountBalance -= amount; savingsAccountBalance += amount; return true; } } finally { primaryLock.unlock(); savingsLock.unlock(); } return false; } }
1,047
23.952381
63
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/SAXBuilderTests.java
import java.net.Socket; import org.jdom.input.SAXBuilder; public class SAXBuilderTests { public void unconfiguredSAXBuilder(Socket sock) throws Exception { SAXBuilder builder = new SAXBuilder(); builder.build(sock.getInputStream()); //unsafe } public void safeBuilder(Socket sock) throws Exception { SAXBuilder builder = new SAXBuilder(); builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true); builder.build(sock.getInputStream()); //safe } public void misConfiguredBuilder(Socket sock) throws Exception { SAXBuilder builder = new SAXBuilder(); builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",false); builder.build(sock.getInputStream()); //unsafe } }
754
31.826087
85
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/XPathExpressionTests.java
import java.net.Socket; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.xml.sax.InputSource; public class XPathExpressionTests { public void safeXPathExpression(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = factory.newDocumentBuilder(); XPathFactory xFactory = XPathFactory.newInstance(); XPath path = xFactory.newXPath(); XPathExpression expr = path.compile(""); expr.evaluate(builder.parse(sock.getInputStream())); //safe } public void unsafeExpressionTests(Socket sock) throws Exception { XPathFactory xFactory = XPathFactory.newInstance(); XPath path = xFactory.newXPath(); XPathExpression expr = path.compile(""); expr.evaluate(new InputSource(sock.getInputStream())); //unsafe } }
1,090
35.366667
87
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/SchemaTests.java
import java.net.Socket; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; public class SchemaTests { public void unconfiguredSchemaFactory(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //unsafe } public void safeSchemaFactory(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //safe } public void partialConfiguredSchemaFactory1(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //unsafe } public void partialConfiguredSchemaFactory2(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredSchemaFactory1(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "ab"); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredSchemaFactory2(Socket sock) throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "cd"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); Schema schema = factory.newSchema(new StreamSource(sock.getInputStream())); //unsafe } }
2,281
46.541667
90
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/SAXReaderTests.java
import java.net.Socket; import org.dom4j.io.SAXReader; public class SAXReaderTests { public void unconfiguredReader(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.read(sock.getInputStream()); //unsafe } public void safeReader(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.read(sock.getInputStream()); //safe } public void partialConfiguredReader1(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.read(sock.getInputStream()); //unsafe } public void partialConfiguredReader2(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.read(sock.getInputStream()); //unsafe } public void partialConfiguredReader3(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.read(sock.getInputStream()); //unsafe } public void misConfiguredReader1(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", true); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.read(sock.getInputStream()); //unsafe } public void misConfiguredReader2(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.read(sock.getInputStream()); //unsafe } public void misConfiguredReader3(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", true); reader.read(sock.getInputStream()); //unsafe } }
2,977
45.53125
92
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/DocumentBuilderTests.java
import java.net.Socket; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.XMLConstants; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import org.xml.sax.InputSource; class DocumentBuilderTests { public void unconfiguredParse(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableDTD(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableSecurityFeature(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableSecurityFeature2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableDTD(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableSecurityFeature(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableExternalEntities(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void partialDisableExternalEntities(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void partialDisableExternalEntities2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void misConfigureExternalEntities1(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void misConfigureExternalEntities2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void taintedSAXInputSource1(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); SAXSource source = new SAXSource(new InputSource(sock.getInputStream())); builder.parse(source.getInputSource()); //unsafe } public void taintedSAXInputSource2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StreamSource source = new StreamSource(sock.getInputStream()); builder.parse(SAXSource.sourceToInputSource(source)); //unsafe builder.parse(source.getInputStream()); //unsafe } private static DocumentBuilderFactory getDocumentBuilderFactory() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String feature = ""; feature = "http://xml.org/sax/features/external-parameter-entities"; factory.setFeature(feature, false); feature = "http://xml.org/sax/features/external-general-entities"; factory.setFeature(feature, false); return factory; } private static final ThreadLocal<DocumentBuilder> XML_DOCUMENT_BUILDER = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { DocumentBuilderFactory factory = getDocumentBuilderFactory(); try { return factory.newDocumentBuilder(); } catch (Exception ex) { throw new RuntimeException(ex); } } }; public void disableExternalEntities2(Socket sock) throws Exception { DocumentBuilder builder = XML_DOCUMENT_BUILDER.get(); builder.parse(sock.getInputStream()); //safe } }
5,986
44.015038
111
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/TransformerTests.java
import java.net.Socket; import javax.xml.XMLConstants; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class TransformerTests { public void unconfiguredTransformerFactory(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(new StreamSource(sock.getInputStream()), null); //unsafe tf.newTransformer(new StreamSource(sock.getInputStream())); //unsafe } public void safeTransformerFactory1(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("http://javax.xml.XMLConstants/property/accessExternalDTD", ""); tf.setAttribute("http://javax.xml.XMLConstants/property/accessExternalStylesheet", ""); Transformer transformer = tf.newTransformer(); transformer.transform(new StreamSource(sock.getInputStream()), null); //safe tf.newTransformer(new StreamSource(sock.getInputStream())); //safe } public void safeTransformerFactory2(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = tf.newTransformer(); transformer.transform(new StreamSource(sock.getInputStream()), null); //safe tf.newTransformer(new StreamSource(sock.getInputStream())); //safe } public void safeTransformerFactory3(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); SAXSource source = new SAXSource(reader, new InputSource(sock.getInputStream())); //safe transformer.transform(source, null); //safe tf.newTransformer(source); //safe } public void safeTransformerFactory4(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); SAXSource source = new SAXSource(new InputSource(sock.getInputStream())); source.setXMLReader(reader); transformer.transform(source, null); //safe tf.newTransformer(source); //safe } public void partialConfiguredTransformerFactory1(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); Transformer transformer = tf.newTransformer(); transformer.transform(new StreamSource(sock.getInputStream()), null); //unsafe tf.newTransformer(new StreamSource(sock.getInputStream())); //unsafe } public void partialConfiguredTransformerFactory2(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = tf.newTransformer(); transformer.transform(new StreamSource(sock.getInputStream()), null); //unsafe tf.newTransformer(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredTransformerFactory1(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "ab"); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); transformer.transform(new StreamSource(sock.getInputStream()), null); //unsafe tf.newTransformer(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredTransformerFactory2(Socket sock) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "cd"); transformer.transform(new StreamSource(sock.getInputStream()), null); //unsafe tf.newTransformer(new StreamSource(sock.getInputStream())); //unsafe } public void unconfiguredSAXTransformerFactory(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //unsafe } public void safeSAXTransformerFactory(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //safe } public void partialConfiguredSAXTransformerFactory1(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //unsafe } public void partialConfiguredSAXTransformerFactory2(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredSAXTransformerFactory1(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "ab"); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //unsafe } public void misConfiguredSAXTransformerFactory2(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "cd"); sf.newXMLFilter(new StreamSource(sock.getInputStream())); //unsafe } public void taintedSAXSource(Socket sock) throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); sf.newXMLFilter(new SAXSource(new InputSource(sock.getInputStream()))); //unsafe } }
7,181
48.875
94
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/XMLReaderTests.java
import java.net.Socket; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.dom4j.io.SAXReader; public class XMLReaderTests { public void unconfiguredReader(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void safeReaderFromConfig1(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); reader.parse(new InputSource(sock.getInputStream())); //safe } public void safeReaderFromConfig2(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.parse(new InputSource(sock.getInputStream())); //safe } public void safeReaderFromSAXParser(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.parse(new InputSource(sock.getInputStream())); //safe } public void safeReaderFromSAXReader(Socket sock) throws Exception { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); XMLReader xmlReader = reader.getXMLReader(); xmlReader.parse(new InputSource(sock.getInputStream())); //safe } public void partialConfiguredXMLReader1(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void partialConfiguredXMLReader2(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void partilaConfiguredXMLReader3(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void misConfiguredXMLReader1(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", true); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void misConfiguredXMLReader2(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", true); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void misConfiguredXMLReader3(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); reader.parse(new InputSource(sock.getInputStream())); //unsafe } public void misConfiguredXMLReader4(Socket sock) throws Exception { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); reader.parse(new InputSource(sock.getInputStream())); //unsafe } }
5,177
49.271845
98
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/SimpleXMLTests.java
import java.io.InputStreamReader; import java.net.Socket; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.stream.DocumentProvider; import org.simpleframework.xml.stream.NodeBuilder; import org.simpleframework.xml.stream.StreamProvider; import org.simpleframework.xml.stream.Formatter; public class SimpleXMLTests { public void persisterValidate1(Socket sock) throws Exception { Persister persister = new Persister(); persister.validate(this.getClass(), sock.getInputStream()); } public void persisterValidate2(Socket sock) throws Exception { Persister persister = new Persister(); persister.validate(this.getClass(), sock.getInputStream(), true); } public void persisterValidate3(Socket sock) throws Exception { Persister persister = new Persister(); persister.validate(this.getClass(), new InputStreamReader(sock.getInputStream())); } public void persisterValidate4(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.validate(this.getClass(), new String(b)); } public void persisterValidate5(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.validate(this.getClass(), new String(b), true); } public void persisterValidate6(Socket sock) throws Exception { Persister persister = new Persister(); persister.validate(this.getClass(), new InputStreamReader(sock.getInputStream()), true); } public void persisterRead1(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this.getClass(), sock.getInputStream()); } public void persisterRead2(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this.getClass(), sock.getInputStream(), true); } public void persisterRead3(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this, sock.getInputStream()); } public void persisterRead4(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this, sock.getInputStream(), true); } public void persisterRead5(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this.getClass(), new InputStreamReader(sock.getInputStream())); } public void persisterRead6(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this.getClass(), new InputStreamReader(sock.getInputStream()), true); } public void persisterRead7(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this, new InputStreamReader(sock.getInputStream())); } public void persisterRead8(Socket sock) throws Exception { Persister persister = new Persister(); persister.read(this, new InputStreamReader(sock.getInputStream()), true); } public void persisterRead9(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.read(this.getClass(), new String(b)); } public void persisterRead10(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.read(this.getClass(), new String(b), true); } public void persisterRead11(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.read(this, new String(b)); } public void persisterRead12(Socket sock) throws Exception { Persister persister = new Persister(); byte[] b = new byte[]{}; sock.getInputStream().read(b); persister.read(this, new String(b), true); } public void nodeBuilderRead1(Socket sock) throws Exception { NodeBuilder.read(sock.getInputStream()); } public void nodeBuilderRead2(Socket sock) throws Exception { NodeBuilder.read(new InputStreamReader(sock.getInputStream())); } public void documentProviderProvide1(Socket sock) throws Exception { DocumentProvider provider = new DocumentProvider(); provider.provide(sock.getInputStream()); } public void documentProviderProvide2(Socket sock) throws Exception { DocumentProvider provider = new DocumentProvider(); provider.provide(new InputStreamReader(sock.getInputStream())); } public void streamProviderProvide1(Socket sock) throws Exception { StreamProvider provider = new StreamProvider(); provider.provide(sock.getInputStream()); } public void streamProviderProvide2(Socket sock) throws Exception { StreamProvider provider = new StreamProvider(); provider.provide(new InputStreamReader(sock.getInputStream())); } public void formatterFormat1(Socket sock) throws Exception { Formatter formatter = new Formatter(); byte[] b = new byte[]{}; sock.getInputStream().read(b); formatter.format(new String(b), null); } public void formatterFormat2(Socket sock) throws Exception { Formatter formatter = new Formatter(); byte[] b = new byte[]{}; sock.getInputStream().read(b); formatter.format(new String(b)); } }
5,353
33.320513
92
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/SAXParserTests.java
import java.net.Socket; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.helpers.DefaultHandler; public class SAXParserTests { public void unconfiguredParser(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void safeParser(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //safe } public void partialConfiguredParser1(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void partialConfiguredParser2(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void partialConfiguredParser3(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void misConfiguredParser1(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", true); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void misConfiguredParser2(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", true); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } public void misConfiguredParser3(Socket sock) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); SAXParser parser = factory.newSAXParser(); parser.parse(sock.getInputStream(), new DefaultHandler()); //unsafe } }
3,874
49.986842
96
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-611/XmlInputFactoryTests.java
import java.net.Socket; import javax.xml.stream.XMLInputFactory; public class XmlInputFactoryTests { public void unconfigureFactory(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } public void safeFactory(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); factory.createXMLStreamReader(sock.getInputStream()); //safe factory.createXMLEventReader(sock.getInputStream()); //safe } public void misConfiguredFactory(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } public void misConfiguredFactory2(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } public void misConfiguredFactory3(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", true); factory.setProperty(XMLInputFactory.SUPPORT_DTD, true); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } public void misConfiguredFactory4(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); factory.setProperty(XMLInputFactory.SUPPORT_DTD, true); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } public void misConfiguredFactory5(Socket sock) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", true); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.createXMLStreamReader(sock.getInputStream()); //unsafe factory.createXMLEventReader(sock.getInputStream()); //unsafe } }
2,669
44.254237
80
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-134/semmle/tests/Test.java
// Test case for // CWE-134: Use of Externally-Controlled Format String // http://cwe.mitre.org/data/definitions/134.html package test.cwe134.cwe.examples; import java.io.IOException; import java.util.Formatter; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; class Test { public static void basic() { String userProperty = System.getProperty("userProperty"); // BAD User provided value as format string for String.format String.format(userProperty); // BAD User provided value as format string for PrintStream.format System.out.format(userProperty); // BAD User provided value as format string for PrintStream.printf System.out.printf(userProperty); // BAD User provided value as format string for Formatter.format new Formatter().format(userProperty); // BAD User provided value as format string for Formatter.format new Formatter().format(Locale.ENGLISH, userProperty); } public class FileUploadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userParameter = request.getParameter("userProvidedParameter"); formatString(userParameter); } private void formatString(String format) { // BAD This is used with user provided parameter System.out.format(format); } } }
1,524
34.465116
121
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-807/semmle/tests/Test.java
// Test case for CWE-807 (Reliance on Untrusted Inputs in a Security Decision) // http://cwe.mitre.org/data/definitions/807.html package test.cwe807.semmle.tests; import java.net.InetAddress; import java.net.Inet4Address; import java.net.UnknownHostException; import javax.servlet.http.Cookie; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; class Test { public static void main(String[] args) throws UnknownHostException { String user = args[0]; String password = args[1]; String isAdmin = args[3]; // BAD: login is only executed if isAdmin is false, but isAdmin // is controlled by the user if(isAdmin=="false") login(user, password); Cookie adminCookie = getCookies()[0]; // BAD: login is only executed if the cookie value is false, but the cookie // is controlled by the user if(adminCookie.getValue().equals("false")) login(user, password); // FALSE POSITIVES: both methods are conditionally executed, but they probably // both perform the security-critical action if(adminCookie.getValue()=="false") { login(user, password); } else { reCheckAuth(user, password); } // FALSE NEGATIVE: we have no way of telling that the skipped method is sensitive if(adminCookie.getValue()=="false") doReallyImportantSecurityWork(); // Apache Shiro permissions system String whatDoTheyWantToDo = args[4]; Subject subject = SecurityUtils.getSubject(); // BAD: permissions decision made using tainted data if(subject.isPermitted("domain:sublevel:" + whatDoTheyWantToDo)) doIt(); // GOOD: use fixed checks if(subject.isPermitted("domain:sublevel:whatTheMethodDoes")) doIt(); InetAddress local = InetAddress.getLocalHost(); // GOOD: reverse DNS on localhost is fine if (local.getCanonicalHostName().equals("localhost")) { login(user, password); } if (Inet4Address.getLocalHost().getCanonicalHostName().equals("localhost")) { login(user, password); } } public static void test(String user, String password) { Cookie adminCookie = getCookies()[0]; // GOOD: login always happens if(adminCookie.getValue()=="false") login(user, password); else { // do something else login(user, password); } } public static void test2(String user, String password) { Cookie adminCookie = getCookies()[0]; // BAD: login may happen once or twice if(adminCookie.getValue()=="false") login(user, password); else { // do something else } login(user, password); } public static void test3(String user, String password) { Cookie adminCookie = getCookies()[0]; if(adminCookie.getValue()=="false") login(user, password); else { // do something else // BAD: login may not happen return; } } public static void test4(String user, String password) { Cookie adminCookie = getCookies()[0]; // GOOD: login always happens if(adminCookie.getValue()=="false") { login(user, password); return; } // do other things login(user, password); return; } public static void login(String user, String password) { // login } public static void reCheckAuth(String user, String password) { // login } public static Cookie[] getCookies() { // get cookies from a servlet return new Cookie[0]; } public static void doIt() {} public static void doReallyImportantSecurityWork() { // login, authenticate, everything } }
3,425
24.954545
83
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-601/semmle/tests/UrlRedirect.java
// Test case for // CWE-601: URL Redirection to Untrusted Site ('Open Redirect') // http://cwe.mitre.org/data/definitions/601.html package test.cwe601.cwe.examples; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UrlRedirect extends HttpServlet { private static final String VALID_REDIRECT = "http://cwe.mitre.org/data/definitions/601.html"; private static final String LOCATION_HEADER_KEY = "Location"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // BAD: a request parameter is incorporated without validation into a URL redirect response.sendRedirect(request.getParameter("target")); // GOOD: the request parameter is validated against a known fixed string if (VALID_REDIRECT.equals(request.getParameter("target"))) { response.sendRedirect(VALID_REDIRECT); } // FALSE NEGATIVE: the user attempts to clean the string, but this will fail // if the argument is "hthttp://tp://malicious.com" response.sendRedirect(weakCleanup(request.getParameter("target"))); // FALSE POSITIVE: the user input is not used in a position that allows it to dictate // the target of the redirect response.sendRedirect("http://example.com?username=" + request.getParameter("username")); // BAD: set the "Location" header response.setHeader("Location", request.getParameter("target")); // BAD: set the "Location" header response.addHeader(LOCATION_HEADER_KEY, request.getParameter("target")); } public String weakCleanup(String input) { return input.replaceAll("http://", ""); } }
1,757
34.877551
95
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-421/semmle/Test.java
// Test case for CWE-421 (Race Condition During Access to Alternate Channel) // http://cwe.mitre.org/data/definitions/421.html package test.cwe807.semmle.tests; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; class Test { byte[] secretData = "The password is: passw0rd".getBytes(); // fake stub for testing public boolean isAuthenticated(String username) { return true; } // fake stub for testing public boolean doAuthenticate(Socket connection, String username) { return true; } // fake stub for testing public boolean doAuthenticate(SocketChannel connection, String username) { return true; } public void doConnect(int desiredPort, String username) { ServerSocket listenSocket = new ServerSocket(desiredPort); if (isAuthenticated(username)) { Socket connection1 = listenSocket.accept(); // BAD: no authentication over the socket connection1.getOutputStream().write(secretData); } Socket connection2 = listenSocket.accept(); // GOOD: authentication happens over the socket if (doAuthenticate(connection2, username)) { connection2.getOutputStream().write(secretData); } if (isAuthenticated(username)) { // FP: we authenticate both beforehand and over the socket Socket connection3 = listenSocket.accept(); if (doAuthenticate(connection3, username)) { connection3.getOutputStream().write(secretData); } } } public void doConnectChannel(int desiredPort, String username) { ServerSocketChannel listenChannel = ServerSocketChannel.open(); SocketAddress port = new InetSocketAddress(desiredPort); listenChannel.bind(port); if (isAuthenticated(username)) { SocketChannel connection1 = listenChannel.accept(); // BAD: no authentication over the socket connection1.write(ByteBuffer.wrap(secretData)); } SocketChannel connection2 = listenChannel.accept(); // GOOD: authentication happens over the socket if (doAuthenticate(connection2, username)) { connection2.write(ByteBuffer.wrap(secretData)); } } }
2,198
27.192308
76
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-129/semmle/tests/Test.java
// Test case for // CWE-129: Improper Validation of Array Index // http://cwe.mitre.org/data/definitions/129.html package test.cwe129.cwe.examples; import java.security.SecureRandom; class Test { public static void basic() { int array[] = { 0, 1, 2, 3, 4 }; String userProperty = System.getProperty("userProperty"); try { int index = Integer.parseInt(userProperty.trim()); // BAD Accessing array without conditional check System.out.println(array[index]); if (index >= 0 && index < array.length) { // GOOD Accessing array under conditions System.out.println(array[index]); } try { /* * GOOD Accessing array, but catch ArrayIndexOutOfBounds, so someone has at least * considered the consequences. */ System.out.println(array[index]); } catch (ArrayIndexOutOfBoundsException ex) { } } catch(NumberFormatException exceptNumberFormat) { } } public static void random() { int array[] = { 0, 1, 2, 3, 4 }; int index = (new SecureRandom()).nextInt(10); // BAD Accessing array without conditional check System.out.println(array[index]); if (index < array.length) { // GOOD Accessing array under conditions System.out.println(array[index]); } // GOOD, the array access is protected by short-circuiting if (index < array.length && array[index] > 0) { } } public static void construction() { String userProperty = System.getProperty("userProperty"); try { int size = Integer.parseInt(userProperty.trim()); int[] array = new int[size]; // BAD The array was created without checking the size, so this access may be dubious System.out.println(array[0]); if (size >= 0) { int[] array2 = new int[size]; // BAD The array was created without checking that the size is greater than zero System.out.println(array2[0]); } if (size > 0) { int[] array3 = new int[size]; // GOOD We verified that this was greater than zero System.out.println(array3[0]); } } catch(NumberFormatException exceptNumberFormat) { } } public static void constructionBounded() { int size = 0; int[] array = new int[size]; // BAD Array may be empty. System.out.println(array[0]); int index = 0; if (index < array.length) { // GOOD protected by length check System.out.println(array[index]); } size = 2; array = new int[2]; // GOOD array size is guaranteed to be larger than zero System.out.println(array[0]); } }
2,715
25.115385
93
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-367/semmle/tests/Test.java
// Semmle test case for CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition // http://cwe.mitre.org/data/definitions/367.html package test.cwe367.semmle.tests; class Test { public final Object lock = new Object(); public volatile boolean aField = true; public synchronized void bad1(Resource r) { // probably used concurrently due to synchronization if (r.getState()) { r.act(); } } public synchronized void bad2(Resource2 r) { // probably used concurrently due to synchronization if (r.getState()) { r.act(); } } public void bad3(Resource r) { // probably used concurrently due to use of volatile field if (r.getState() && aField) { r.act(); } } public void bad4(Resource r) { // probably used concurrently due to synchronization synchronized(this) { if (r.getState() && aField) { r.act(); } } } public void good1(Resource r) { // synchronizes on the same monitor as the called methods synchronized(r) { if (r.getState()) { r.act(); } } } public Resource rField = new Resource(); public void someOtherMethod() { synchronized(lock) { rField.act(); } } public void good2() { // r is always guarded with the same lock, so okay synchronized(lock) { if (rField.getState()) { rField.act(); } } } public void good3() { // r never escapes, so cannot be used concurrently Resource r = new Resource(); if (r.getState()) { r.act(); } } // probably not used in a concurrent context, so not worth flagging public void good3(Resource r) { if (r.getState()) { r.act(); } } class Resource { boolean state; public synchronized void setState(boolean newState) { this.state = newState; } public synchronized boolean getState() { return state; } public synchronized void act() { if (state) sideEffect(); else sideEffect(); } public void sideEffect() { } } class Resource2 { boolean state; public void setState(boolean newState) { synchronized(this) { this.state = newState; } } public boolean getState() { synchronized(this) { return state; } } public void act() { synchronized(this) { if (state) sideEffect(); else sideEffect(); } } public void sideEffect() { } } }
2,322
17.007752
82
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-090/LdapInjection.java
import java.util.List; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import com.unboundid.ldap.sdk.Filter; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPSearchException; import com.unboundid.ldap.sdk.ReadOnlySearchRequest; import com.unboundid.ldap.sdk.SearchRequest; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.filter.EqualityNode; import org.apache.directory.api.ldap.model.message.SearchRequestImpl; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.owasp.esapi.Encoder; import org.owasp.esapi.reference.DefaultEncoder; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.filter.EqualsFilter; import org.springframework.ldap.filter.HardcodedFilter; import org.springframework.ldap.query.LdapQuery; import org.springframework.ldap.query.LdapQueryBuilder; import org.springframework.ldap.support.LdapEncoder; import org.springframework.ldap.support.LdapNameBuilder; import org.springframework.ldap.support.LdapUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LdapInjection { // JNDI @RequestMapping public void testJndiBad1(@RequestParam String jBad, @RequestParam String jBadDN, DirContext ctx) throws NamingException { ctx.search("ou=system" + jBadDN, "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad2(@RequestParam String jBad, @RequestParam String jBadDNName, InitialDirContext ctx) throws NamingException { ctx.search(new LdapName("ou=system" + jBadDNName), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad3(@RequestParam String jBad, @RequestParam String jOkDN, LdapContext ctx) throws NamingException { ctx.search(new LdapName(List.of(new Rdn("ou=" + jOkDN))), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad4(@RequestParam String jBadInitial, InitialLdapContext ctx) throws NamingException { ctx.search("ou=system", "(uid=" + jBadInitial + ")", new SearchControls()); } @RequestMapping public void testJndiBad5(@RequestParam String jBad, @RequestParam String jBadDNNameAdd, InitialDirContext ctx) throws NamingException { ctx.search(new LdapName("").addAll(new LdapName("ou=system" + jBadDNNameAdd)), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad6(@RequestParam String jBad, @RequestParam String jBadDNNameAdd2, InitialDirContext ctx) throws NamingException { LdapName name = new LdapName(""); name.addAll(new LdapName("ou=system" + jBadDNNameAdd2).getRdns()); ctx.search(new LdapName("").addAll(name), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad7(@RequestParam String jBad, @RequestParam String jBadDNNameToString, InitialDirContext ctx) throws NamingException { ctx.search(new LdapName("ou=system" + jBadDNNameToString).toString(), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiBad8(@RequestParam String jBad, @RequestParam String jBadDNNameClone, InitialDirContext ctx) throws NamingException { ctx.search((Name) new LdapName("ou=system" + jBadDNNameClone).clone(), "(uid=" + jBad + ")", new SearchControls()); } @RequestMapping public void testJndiOk1(@RequestParam String jOkFilterExpr, DirContext ctx) throws NamingException { ctx.search("ou=system", "(uid={0})", new String[] { jOkFilterExpr }, new SearchControls()); } @RequestMapping public void testJndiOk2(@RequestParam String jOkAttribute, DirContext ctx) throws NamingException { ctx.search("ou=system", new BasicAttributes(jOkAttribute, jOkAttribute)); } // UnboundID @RequestMapping public void testUnboundBad1(@RequestParam String uBad, @RequestParam String uBadDN, LDAPConnection c) throws LDAPSearchException { c.search(null, "ou=system" + uBadDN, null, null, 1, 1, false, "(uid=" + uBad + ")"); } @RequestMapping public void testUnboundBad2(@RequestParam String uBadFilterCreate, LDAPConnection c) throws LDAPException { c.search(null, "ou=system", null, null, 1, 1, false, Filter.create(uBadFilterCreate)); } @RequestMapping public void testUnboundBad3(@RequestParam String uBadROSearchRequest, @RequestParam String uBadROSRDN, LDAPConnection c) throws LDAPException { ReadOnlySearchRequest s = new SearchRequest(null, "ou=system" + uBadROSRDN, null, null, 1, 1, false, "(uid=" + uBadROSearchRequest + ")"); c.search(s); } @RequestMapping public void testUnboundBad4(@RequestParam String uBadSearchRequest, @RequestParam String uBadSRDN, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "ou=system" + uBadSRDN, null, null, 1, 1, false, "(uid=" + uBadSearchRequest + ")"); c.search(s); } @RequestMapping public void testUnboundBad5(@RequestParam String uBad, @RequestParam String uBadDNSFR, LDAPConnection c) throws LDAPSearchException { c.searchForEntry("ou=system" + uBadDNSFR, null, null, 1, false, "(uid=" + uBad + ")"); } @RequestMapping public void testUnboundBad6(@RequestParam String uBadROSearchRequestAsync, @RequestParam String uBadROSRDNAsync, LDAPConnection c) throws LDAPException { ReadOnlySearchRequest s = new SearchRequest(null, "ou=system" + uBadROSRDNAsync, null, null, 1, 1, false, "(uid=" + uBadROSearchRequestAsync + ")"); c.asyncSearch(s); } @RequestMapping public void testUnboundBad7(@RequestParam String uBadSearchRequestAsync, @RequestParam String uBadSRDNAsync, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "ou=system" + uBadSRDNAsync, null, null, 1, 1, false, "(uid=" + uBadSearchRequestAsync + ")"); c.asyncSearch(s); } @RequestMapping public void testUnboundBad8(@RequestParam String uBadFilterCreateNOT, LDAPConnection c) throws LDAPException { c.search(null, "ou=system", null, null, 1, 1, false, Filter.createNOTFilter(Filter.create(uBadFilterCreateNOT))); } @RequestMapping public void testUnboundBad9(@RequestParam String uBadFilterCreateToString, LDAPConnection c) throws LDAPException { c.search(null, "ou=system", null, null, 1, 1, false, Filter.create(uBadFilterCreateToString).toString()); } @RequestMapping public void testUnboundBad10(@RequestParam String uBadFilterCreateToStringBuffer, LDAPConnection c) throws LDAPException { StringBuilder b = new StringBuilder(); Filter.create(uBadFilterCreateToStringBuffer).toNormalizedString(b); c.search(null, "ou=system", null, null, 1, 1, false, b.toString()); } @RequestMapping public void testUnboundBad11(@RequestParam String uBadSearchRequestDuplicate, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "ou=system", null, null, 1, 1, false, "(uid=" + uBadSearchRequestDuplicate + ")"); c.search(s.duplicate()); } @RequestMapping public void testUnboundBad12(@RequestParam String uBadROSearchRequestDuplicate, LDAPConnection c) throws LDAPException { ReadOnlySearchRequest s = new SearchRequest(null, "ou=system", null, null, 1, 1, false, "(uid=" + uBadROSearchRequestDuplicate + ")"); c.search(s.duplicate()); } @RequestMapping public void testUnboundBad13(@RequestParam String uBadSearchRequestSetDN, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "", null, null, 1, 1, false, ""); s.setBaseDN(uBadSearchRequestSetDN); c.search(s); } @RequestMapping public void testUnboundBad14(@RequestParam String uBadSearchRequestSetFilter, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "ou=system", null, null, 1, 1, false, ""); s.setFilter(uBadSearchRequestSetFilter); c.search(s); } @RequestMapping public void testUnboundOk1(@RequestParam String uOkEqualityFilter, LDAPConnection c) throws LDAPSearchException { c.search(null, "ou=system", null, null, 1, 1, false, Filter.createEqualityFilter("uid", uOkEqualityFilter)); } @RequestMapping public void testUnboundOk2(@RequestParam String uOkVaragsAttr, LDAPConnection c) throws LDAPSearchException { c.search("ou=system", null, null, 1, 1, false, "(uid=fixed)", "a" + uOkVaragsAttr); } @RequestMapping public void testUnboundOk3(@RequestParam String uOkFilterSearchRequest, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest(null, "ou=system", null, null, 1, 1, false, Filter.createEqualityFilter("uid", uOkFilterSearchRequest)); c.search(s); } @RequestMapping public void testUnboundOk4(@RequestParam String uOkSearchRequestVarargs, LDAPConnection c) throws LDAPException { SearchRequest s = new SearchRequest("ou=system", null, "(uid=fixed)", "va1", "va2", "va3", "a" + uOkSearchRequestVarargs); c.search(s); } // Spring LDAP @RequestMapping public void testSpringBad1(@RequestParam String sBad, @RequestParam String sBadDN, LdapTemplate c) { c.search("ou=system" + sBadDN, "(uid=" + sBad + ")", 1, false, null); } @RequestMapping public void testSpringBad2(@RequestParam String sBad, @RequestParam String sBadDNLNBuilder, LdapTemplate c) { c.authenticate(LdapNameBuilder.newInstance("ou=system" + sBadDNLNBuilder).build(), "(uid=" + sBad + ")", "pass"); } @RequestMapping public void testSpringBad3(@RequestParam String sBad, @RequestParam String sBadDNLNBuilderAdd, LdapTemplate c) { c.searchForObject(LdapNameBuilder.newInstance().add("ou=system" + sBadDNLNBuilderAdd).build(), "(uid=" + sBad + ")", null); } @RequestMapping public void testSpringBad4(@RequestParam String sBadLdapQuery, LdapTemplate c) { c.findOne(LdapQueryBuilder.query().filter("(uid=" + sBadLdapQuery + ")"), null); } @RequestMapping public void testSpringBad5(@RequestParam String sBadFilter, @RequestParam String sBadDNLdapUtils, LdapTemplate c) { c.find(LdapUtils.newLdapName("ou=system" + sBadDNLdapUtils), new HardcodedFilter("(uid=" + sBadFilter + ")"), null, null); } @RequestMapping public void testSpringBad6(@RequestParam String sBadLdapQuery, LdapTemplate c) { c.searchForContext(LdapQueryBuilder.query().filter("(uid=" + sBadLdapQuery + ")")); } @RequestMapping public void testSpringBad7(@RequestParam String sBadLdapQuery2, LdapTemplate c) { LdapQuery q = LdapQueryBuilder.query().filter("(uid=" + sBadLdapQuery2 + ")"); c.searchForContext(q); } @RequestMapping public void testSpringBad8(@RequestParam String sBadLdapQueryWithFilter, LdapTemplate c) { c.searchForContext(LdapQueryBuilder.query().filter(new HardcodedFilter("(uid=" + sBadLdapQueryWithFilter + ")"))); } @RequestMapping public void testSpringBad9(@RequestParam String sBadLdapQueryWithFilter2, LdapTemplate c) { org.springframework.ldap.filter.Filter f = new HardcodedFilter("(uid=" + sBadLdapQueryWithFilter2 + ")"); c.searchForContext(LdapQueryBuilder.query().filter(f)); } @RequestMapping public void testSpringBad10(@RequestParam String sBadLdapQueryBase, LdapTemplate c) { c.find(LdapQueryBuilder.query().base(sBadLdapQueryBase).base(), null, null, null); } @RequestMapping public void testSpringBad11(@RequestParam String sBadLdapQueryComplex, LdapTemplate c) { c.searchForContext(LdapQueryBuilder.query().base(sBadLdapQueryComplex).where("uid").is("test")); } @RequestMapping public void testSpringBad12(@RequestParam String sBadFilterToString, LdapTemplate c) { c.search("", new HardcodedFilter("(uid=" + sBadFilterToString + ")").toString(), 1, false, null); } @RequestMapping public void testSpringBad13(@RequestParam String sBadFilterEncode, LdapTemplate c) { StringBuffer s = new StringBuffer(); new HardcodedFilter("(uid=" + sBadFilterEncode + ")").encode(s); c.search("", s.toString(), 1, false, null); } @RequestMapping public void testSpringOk1(@RequestParam String sOkLdapQuery, LdapTemplate c) { c.find(LdapQueryBuilder.query().filter("(uid={0})", sOkLdapQuery), null); } @RequestMapping public void testSpringOk2(@RequestParam String sOkFilter, @RequestParam String sOkDN, LdapTemplate c) { c.find(LdapNameBuilder.newInstance().add("ou", sOkDN).build(), new EqualsFilter("uid", sOkFilter), null, null); } @RequestMapping public void testSpringOk3(@RequestParam String sOkLdapQuery, @RequestParam String sOkPassword, LdapTemplate c) { c.authenticate(LdapQueryBuilder.query().filter("(uid={0})", sOkLdapQuery), sOkPassword); } // Apache LDAP API @RequestMapping public void testApacheBad1(@RequestParam String aBad, @RequestParam String aBadDN, LdapConnection c) throws LdapException { c.search("ou=system" + aBadDN, "(uid=" + aBad + ")", null); } @RequestMapping public void testApacheBad2(@RequestParam String aBad, @RequestParam String aBadDNObjToString, LdapNetworkConnection c) throws LdapException { c.search(new Dn("ou=system" + aBadDNObjToString).getName(), "(uid=" + aBad + ")", null); } @RequestMapping public void testApacheBad3(@RequestParam String aBadSearchRequest, LdapConnection c) throws LdapException { org.apache.directory.api.ldap.model.message.SearchRequest s = new SearchRequestImpl(); s.setFilter("(uid=" + aBadSearchRequest + ")"); c.search(s); } @RequestMapping public void testApacheBad4(@RequestParam String aBadSearchRequestImpl, @RequestParam String aBadDNObj, LdapConnection c) throws LdapException { SearchRequestImpl s = new SearchRequestImpl(); s.setBase(new Dn("ou=system" + aBadDNObj)); c.search(s); } @RequestMapping public void testApacheBad5(@RequestParam String aBadDNSearchRequestGet, LdapConnection c) throws LdapException { org.apache.directory.api.ldap.model.message.SearchRequest s = new SearchRequestImpl(); s.setBase(new Dn("ou=system" + aBadDNSearchRequestGet)); c.search(s.getBase(), "(uid=test", null); } @RequestMapping public void testApacheOk1(@RequestParam String aOk, LdapConnection c) throws LdapException { org.apache.directory.api.ldap.model.message.SearchRequest s = new SearchRequestImpl(); s.setFilter(new EqualityNode<String>("uid", aOk)); c.search(s); } @RequestMapping public void testApacheOk2(@RequestParam String aOk, LdapConnection c) throws LdapException { SearchRequestImpl s = new SearchRequestImpl(); s.setFilter(new EqualityNode<String>("uid", aOk)); c.search(s); } // ESAPI encoder sanitizer @RequestMapping public void testOk3(@RequestParam String okEncodeForLDAP, DirContext ctx) throws NamingException { Encoder encoder = DefaultEncoder.getInstance(); ctx.search("ou=system", "(uid=" + encoder.encodeForLDAP(okEncodeForLDAP) + ")", new SearchControls()); } // Spring LdapEncoder sanitizer @RequestMapping public void testOk4(@RequestParam String okFilterEncode, DirContext ctx) throws NamingException { ctx.search("ou=system", "(uid=" + LdapEncoder.filterEncode(okFilterEncode) + ")", new SearchControls()); } // UnboundID Filter.encodeValue sanitizer @RequestMapping public void testOk5(@RequestParam String okUnboundEncodeValue, DirContext ctx) throws NamingException { ctx.search("ou=system", "(uid=" + Filter.encodeValue(okUnboundEncodeValue) + ")", new SearchControls()); } }
16,253
41.328125
128
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-113/semmle/tests/ResponseSplitting.java
// Test case for // CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') // http://cwe.mitre.org/data/definitions/113.html package test.cwe113.cwe.examples; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseSplitting extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // BAD: setting a cookie with an unvalidated parameter // can lead to HTTP splitting { Cookie cookie = new Cookie("name", request.getParameter("name")); response.addCookie(cookie); } // BAD: setting a header with an unvalidated parameter // can lead to HTTP splitting response.addHeader("Content-type", request.getParameter("contentType")); response.setHeader("Content-type", request.getParameter("contentType")); // GOOD: remove special characters before putting them in the header { String name = removeSpecial(request.getParameter("name")); Cookie cookie = new Cookie("name", name); response.addCookie(cookie); } // GOOD: Splicing headers into other headers cannot cause splitting response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); } private static String removeSpecial(String str) { return str.replaceAll("[^a-zA-Z ]", ""); } public void addCookieName(HttpServletResponse response, Cookie cookie) { // GOOD: cookie.getName() cannot lead to HTTP splitting Cookie cookie2 = new Cookie("name", cookie.getName()); response.addCookie(cookie2); } }
1,745
32.576923
97
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-829/semmle/tests/A.java
public class A { }
19
5.666667
16
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-502/A.java
import java.io.*; import java.net.Socket; import java.beans.XMLDecoder; import com.thoughtworks.xstream.XStream; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.Yaml; public class A { public Object deserialize1(Socket sock) { InputStream inputStream = sock.getInputStream(); ObjectInputStream in = new ObjectInputStream(inputStream); return in.readObject(); // unsafe } public Object deserialize2(Socket sock) { InputStream inputStream = sock.getInputStream(); ObjectInputStream in = new ObjectInputStream(inputStream); return in.readUnshared(); // unsafe } public Object deserialize3(Socket sock) { InputStream inputStream = sock.getInputStream(); XMLDecoder d = new XMLDecoder(inputStream); return d.readObject(); // unsafe } public Object deserialize4(Socket sock) { XStream xs = new XStream(); InputStream inputStream = sock.getInputStream(); Reader reader = new InputStreamReader(inputStream); return xs.fromXML(reader); // unsafe } public void deserialize5(Socket sock) { Kryo kryo = new Kryo(); Input input = new Input(sock.getInputStream()); A a1 = kryo.readObject(input, A.class); // unsafe A a2 = kryo.readObjectOrNull(input, A.class); // unsafe Object o = kryo.readClassAndObject(input); // unsafe } private Kryo getSafeKryo() { Kryo kryo = new Kryo(); kryo.setRegistrationRequired(true); // ... kryo.register(A.class) ... return kryo; } public void deserialize6(Socket sock) { Kryo kryo = getSafeKryo(); Input input = new Input(sock.getInputStream()); Object o = kryo.readClassAndObject(input); // OK } public void deserializeSnakeYaml(Socket sock) { Yaml yaml = new Yaml(); InputStream input = sock.getInputStream(); Object o = yaml.load(input); //unsafe Object o2 = yaml.loadAll(input); //unsafe Object o3 = yaml.parse(new InputStreamReader(input)); //unsafe A o4 = yaml.loadAs(input, A.class); //unsafe A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //unsafe } public void deserializeSnakeYaml2(Socket sock) { Yaml yaml = new Yaml(new Constructor()); InputStream input = sock.getInputStream(); Object o = yaml.load(input); //unsafe Object o2 = yaml.loadAll(input); //unsafe Object o3 = yaml.parse(new InputStreamReader(input)); //unsafe A o4 = yaml.loadAs(input, A.class); //unsafe A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //unsafe } public void deserializeSnakeYaml3(Socket sock) { Yaml yaml = new Yaml(new SafeConstructor()); InputStream input = sock.getInputStream(); Object o = yaml.load(input); //OK Object o2 = yaml.loadAll(input); //OK Object o3 = yaml.parse(new InputStreamReader(input)); //OK A o4 = yaml.loadAs(input, A.class); //OK A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //OK } public void deserializeSnakeYaml4(Socket sock) { Yaml yaml = new Yaml(new Constructor(A.class)); InputStream input = sock.getInputStream(); Object o = yaml.load(input); //OK Object o2 = yaml.loadAll(input); //OK Object o3 = yaml.parse(new InputStreamReader(input)); //OK A o4 = yaml.loadAs(input, A.class); //OK A o5 = yaml.loadAs(new InputStreamReader(input), A.class); //OK } }
3,467
34.387755
71
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-502/TestMessageBodyReader.java
import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; public class TestMessageBodyReader implements MessageBodyReader<Object> { @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return false; } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { try { return new ObjectInputStream(entityStream).readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } }
910
31.535714
109
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-089/semmle/examples/Test.java
// Test cases for CWE-089 (SQL injection and Java Persistence query injection) // http://cwe.mitre.org/data/definitions/89.html package test.cwe089.semmle.tests; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; enum Category { FloorWax, Topping, Biscuits } abstract class Test { public static Connection connection; public static int categoryId; public static String categoryName; public static String tableName; private static void tainted(String[] args) throws IOException, SQLException { // BAD: the category might have SQL special characters in it { String category = args[1]; Statement statement = connection.createStatement(); String query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + category + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(query1); } // BAD: don't use user input when building a prepared call { String id = args[1]; String query2 = "{ call get_product_by_id('" + id + "',?,?,?) }"; PreparedStatement statement = connection.prepareCall(query2); ResultSet results = statement.executeQuery(); } // BAD: don't use user input when building a prepared query { String category = args[1]; String query3 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + category + "' ORDER BY PRICE"; PreparedStatement statement = connection.prepareStatement(query3); ResultSet results = statement.executeQuery(); } // BAD: an injection using a StringBuilder instead of string append { String category = args[1]; StringBuilder querySb = new StringBuilder(); querySb.append("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='"); querySb.append(category); querySb.append("' ORDER BY PRICE"); String querySbToString = querySb.toString(); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(querySbToString); } // BAD: executeUpdate { String item = args[1]; String price = args[2]; Statement statement = connection.createStatement(); String query = "UPDATE PRODUCT SET PRICE='" + price + "' WHERE ITEM='" + item + "'"; int count = statement.executeUpdate(query); } // BAD: executeUpdate { String item = args[1]; String price = args[2]; Statement statement = connection.createStatement(); String query = "UPDATE PRODUCT SET PRICE='" + price + "' WHERE ITEM='" + item + "'"; long count = statement.executeLargeUpdate(query); } // OK: validate the input first { String category = args[1]; Validation.checkIdentifier(category); Statement statement = connection.createStatement(); String query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + category + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(query1); } } private static void unescaped() throws IOException, SQLException { // BAD: the category might have SQL special characters in it { Statement statement = connection.createStatement(); String queryFromField = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + categoryName + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryFromField); } // BAD: unescaped code using a StringBuilder { StringBuilder querySb = new StringBuilder(); querySb.append("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='"); querySb.append(categoryName); querySb.append("' ORDER BY PRICE"); String querySbToString = querySb.toString(); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(querySbToString); } // BAD: a StringBuilder with appends of + operations { StringBuilder querySb2 = new StringBuilder(); querySb2.append("SELECT ITEM,PRICE FROM PRODUCT "); querySb2.append("WHERE ITEM_CATEGORY='" + categoryName + "' "); querySb2.append("ORDER BY PRICE"); String querySb2ToString = querySb2.toString(); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(querySb2ToString); } } private static void good(String[] args) throws IOException, SQLException { // GOOD: use a prepared query { String category = args[1]; String query2 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=? ORDER BY PRICE"; PreparedStatement statement = connection.prepareStatement(query2); statement.setString(1, category); ResultSet results = statement.executeQuery(); } } private static void controlledStrings() throws IOException, SQLException { // GOOD: integers cannot have special characters in them { Statement statement = connection.createStatement(); String queryWithInt = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + categoryId + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithInt); } // GOOD: enum names are safe { Statement statement = connection.createStatement(); String queryWithEnum = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + Category.Topping + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithEnum); } // GOOD: enum with toString called on it is safe { Statement statement = connection.createStatement(); String queryWithEnumToString = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + Category.Topping.toString() + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithEnumToString); } // GOOD: class names are okay { Statement statement = connection.createStatement(); String queryWithClassName = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + Test.class.getName() + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithClassName); } // GOOD: class names are okay { Statement statement = connection.createStatement(); String queryWithClassSimpleName = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + Test.class.getSimpleName() + "' ORDER BY PRICE"; ResultSet results = statement .executeQuery(queryWithClassSimpleName); } // GOOD: certain toString() methods are okay { Statement statement = connection.createStatement(); String queryWithDoubleToString = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + Double.toString(categoryId) + "' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithDoubleToString); } } private static void tableNames(String[] args) throws IOException, SQLException { // GOOD: table names cannot be replaced by a wildcard { Statement statement = connection.createStatement(); String queryWithTableName = "SELECT ITEM,PRICE FROM " + tableName + " WHERE ITEM_CATEGORY='Biscuits' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithTableName); } { Statement statement = connection.createStatement(); String queryWithTableName2 = "SELECT ITEM,PRICE FROM " + tableName; ResultSet results = statement.executeQuery(queryWithTableName2); } { Statement statement = connection.createStatement(); String queryWithTableName3 = "SELECT ITEM,PRICE" + " FROM " + tableName; ResultSet results = statement.executeQuery(queryWithTableName3); } // BAD: a table name that is user input { String userTabName = args[1]; Statement statement = connection.createStatement(); String queryWithUserTableName = "SELECT ITEM,PRICE FROM " + userTabName + " WHERE ITEM_CATEGORY='Biscuits' ORDER BY PRICE"; ResultSet results = statement.executeQuery(queryWithUserTableName); } } public static void main(String[] args) throws IOException, SQLException { tainted(args); unescaped(); good(args); controlledStrings(); tableNames(args); } }
7,850
34.364865
91
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-089/semmle/examples/Validation.java
// Test case for CWE-089 (SQL injection) // http://cwe.mitre.org/data/definitions/89.html package test.cwe089.semmle.tests; public class Validation { public static void checkIdentifier(String id) { for (int i = 0; i < id.length(); i++) { char c = id.charAt(i); if (!Character.isLetter(c)) { throw new RuntimeException("Invalid identifier: " + id); } } } }
376
24.133333
60
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-311/CWE-319/Test.java
import java.net.HttpURLConnection; import javax.net.ssl.HttpsURLConnection; import java.io.*; class Test { public void m1(HttpURLConnection connection) { InputStream input; if (connection instanceof HttpsURLConnection) { input = connection.getInputStream(); // OK } else { input = connection.getInputStream(); // BAD } } }
356
22.8
51
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-311/CWE-614/semmle/tests/Test.java
// Semmle test case for CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute // http://cwe.mitre.org/data/definitions/614.html package test.cwe614.semmle.tests; import javax.servlet.http.*; class Test { public static void test(HttpServletRequest request, HttpServletResponse response) { { Cookie cookie = new Cookie("secret" ,"fakesecret"); // BAD: secure flag not set response.addCookie(cookie); } { Cookie cookie = new Cookie("secret" ,"fakesecret"); // GOOD: set secure flag cookie.setSecure(true); response.addCookie(cookie); } } }
604
19.862069
93
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-798/semmle/tests/Test.java
package test.cwe798.cwe.examples; import java.sql.DriverManager; import java.sql.SQLException; public class Test { public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://localhost/test"; String usr = "admin"; // hard-coded user name (flow source) String pass = "123456"; // hard-coded password (flow source) test(url, usr, pass); // flow through method DriverManager.getConnection(url, "admin", "123456"); // hard-coded user/pass used directly in call DriverManager.getConnection(url, usr, pass); // hard-coded user/pass flows into API call new java.net.PasswordAuthentication(usr, "123456".toCharArray()); // flow into char[] array new java.net.PasswordAuthentication(usr, pass.toCharArray()); // flow through variable, then char[] array byte[] key = {1, 2, 3, 4, 5, 6, 7, 8}; // hard-coded cryptographic key, flowing into API call below javax.crypto.spec.SecretKeySpec spec = new javax.crypto.spec.SecretKeySpec(key, "AES"); byte[] key2 = "abcdefgh".getBytes(); // hard-coded cryptographic key, flowing into API call below javax.crypto.spec.SecretKeySpec spec2 = new javax.crypto.spec.SecretKeySpec(key2, "AES"); passwordCheck(pass); // flow through } public static void test(String url, String user, String password) throws SQLException { DriverManager.getConnection(url, user, password); // sensitive API call (flow target) } public static final String password = "myOtherPassword"; // hard-coded password public static boolean passwordCheck(String password) { return password.equals("admin"); // hard-coded password comparison } }
1,617
40.487179
107
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-798/semmle/tests/CredentialsTest.java
package test.cwe798.cwe.examples; import java.sql.DriverManager; import java.sql.SQLException; public class CredentialsTest { private static final String p = "123456"; // hard-coded credential (flow source) public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://localhost/test"; String u = "admin"; // hard-coded credential (flow source) DriverManager.getConnection(url, u, p); // sensitive call (flow target) test(url, u, p); } public static void test(String url, String v, String q) throws SQLException { DriverManager.getConnection(url, v, q); // sensitive call (flow target) } }
636
29.333333
81
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-798/semmle/tests/FileCredentialTest.java
package test.cwe798.cwe.examples; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.sql.DriverManager; import java.sql.SQLException; public class FileCredentialTest { public static void main(String[] args) throws SQLException, IOException { String url = "jdbc:mysql://localhost/test"; String u = "admin"; String file = "/test/p.config"; String p = readText(new File(file)); DriverManager.getConnection("", "admin", p); // sensitive call (flow target) test(url, u, p); } public static void test(String url, String v, String q) throws SQLException { DriverManager.getConnection(url, v, q); // sensitive call (flow target) } public static String readText(File f) throws IOException { StringBuilder buf = new StringBuilder(); try (FileInputStream fis = new FileInputStream(f); // opening file input stream (flow source) InputStreamReader reader = new InputStreamReader(fis, "UTF8");) { int n; while ((n = reader.read()) != -1) { buf.append((char)n); } } return buf.toString(); } }
1,107
26.7
95
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-798/semmle/tests/HardcodedAWSCredentials.java
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; public class HardcodedAWSCredentials { public static void main(String[] args) { //BAD: Hardcoded credentials for connecting to AWS services //To fix the problem, use other approaches including AWS credentials file, environment variables, or instance/container credentials instead AWSCredentials creds = new BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY"); } }
458
44.9
142
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-798/semmle/tests/User.java
class User { private static final String DEFAULT_PW = "123456"; // hard-coded password private String pw; public User() { setPassword(DEFAULT_PW); // sensitive call } public void setPassword(String password) { pw = password; } }
238
22.9
74
java
codeql
codeql-master/java/ql/test/query-tests/security/CWE-209/semmle/tests/Test.java
// Semmle test cases for rule CWE-209: Information Exposure Through an Error Message // https://cwe.mitre.org/data/definitions/209.html package test.cwe209.semmle.tests; import java.io.PrintWriter; import java.io.StringWriter; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; class Test extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doSomeWork(); } catch (NullPointerException ex) { // BAD: printing a stack trace back to the response ex.printStackTrace(response.getWriter()); return; } try { doSomeWork(); } catch (NullPointerException ex) { // BAD: printing a stack trace back to the response response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, printTrace(ex)); return; } try { doSomeWork(); } catch (NullPointerException ex) { // BAD: printing a stack trace back to the response response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, printTrace2(ex)); return; } try { doSomeWork(); } catch (Throwable ex) { // BAD: printing an exception message back to the response response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } } private void doSomeWork() { } private static String printTrace(Throwable ex) { StringWriter content = new StringWriter(); ex.printStackTrace(new PrintWriter(content)); return content.toString(); } private static String printTrace2(Throwable ex) { StringWriter content = new StringWriter(); PrintWriter pw = new PrintWriter(content); ex.printStackTrace(pw); return content.toString(); } }
1,884
24.133333
84
java
codeql
codeql-master/java/ql/test/query-tests/SynchSetUnsynchGet/Test.java
class SynchSetUnsynchGet { private static int var; public synchronized void setA(int a) { this.var = a; } public synchronized int getA() { return var; // ok get is synchronized } public synchronized void setB(int a) { this.var = a; } public int getB() { return var; // bad } public synchronized void setC(int a) { this.var = a; } public int getC() { synchronized (this) { return var; // ok get uses synchronized block } } public void setD(int a) { this.var = a; } public int getD() { return var; // ok set is not synchronized } public synchronized void setE(int a) { this.var = a; } public int getE() { synchronized (String.class) { return var; // bad synchronize on wrong thing } } public static synchronized void setF(int a) { var = a; } public static int getF() { synchronized (SynchSetUnsynchGet.class) { return var; // ok get uses synchronized block } } }
950
15.396552
48
java
codeql
codeql-master/java/ql/test/query-tests/InnerClassCouldBeStatic/Test.java
class Test { static class Super<T> { public void test() {} } class Sub<T> extends Super<T> { public void test2() { test(); } } }
144
12.181818
33
java
codeql
codeql-master/java/ql/test/query-tests/InnerClassCouldBeStatic/Classes.java
public class Classes { private static int staticFoo; protected int foo; public int bar() { return foo; } private static int staticBar() { return staticFoo; } /** Already static. */ private static class Static { } /** Could be static. */ private class MaybeStatic { } /** Only accesses enclosing instance in constructor. */ private class MaybeStatic1 { public MaybeStatic1() { System.out.println(foo); } } /** Only accesses enclosing instance in constructor. */ private class MaybeStatic2 { public MaybeStatic2() { System.out.println(Classes.this); } private int bar(Classes c) { return c.bar(); } } /** * Supertype could be static, and no enclosing instance accesses. */ private class MaybeStatic3 extends MaybeStatic2 { public void foo(int i) { staticFoo = i; } } private static class Static1 { public void foo(int i) {} /** Nested and extending classes that can be static; using enclosing * state only in constructor. */ public class MaybeStatic4 extends Static { MaybeStatic4() { System.out.println(staticFoo); } } } /** * Access to bar() is through inheritance, not enclosing state. */ private class MaybeStatic5 extends Classes { public void doit() { System.out.println(bar()); } } private class MaybeStatic6 { private final int myFoo = staticFoo; MaybeStatic6() { staticBar(); } } /** A qualified `this` access needn't refer to the enclosing instance. */ private class MaybeStatic7 { private void foo() { MaybeStatic7.this.foo(); } } public interface Interface { public int interfaceFoo = 0; /** Class is implicitly static as a member of an interface. */ public class Static2 { private void bar() { System.out.println(interfaceFoo); } class MaybeStatic8 { private void bar() { System.out.println(interfaceFoo); } } } } /** Accesses implicitly static interface field. */ public class MaybeStatic9 extends MaybeStatic7 { private void bar() { System.out.println(Interface.interfaceFoo); } } /** A qualified `super` access that doesn't refer to the enclosing scope. */ class MaybeStatic10 extends Classes { private void baz() { System.out.println(MaybeStatic10.super.getClass()); } } static class A { interface B { class ThisIsStatic { final int outer = 0; class MaybeStaticToo { final int a = 0; } class MayNotBeStatic { public void foo() { class ThisIsNotStatic { int b = outer; // see? class NeitherIsThis { int c = outer; // yeah. It also can't be. } } new ThisIsNotStatic() { int d = outer; // either. Also can't be. }; } } } } } enum E { A; class NotStaticButCouldBe {} } /** * Uses enclosing field outside constructor. */ private class NotStatic { public int foo() { return foo; } } /** Uses enclosing method outside constructor. */ private class NotStatic1 { public void foo() { bar(); } } /** Uses enclosing instance outside constructor. */ private class NotStatic2 { public void bar() { Classes.this.bar(); } } private void enclosing() { /** A local class can't be static. */ class NotStatic3 { } } /** Extends a class that can't be static. */ private class NotStatic4 extends NotStatic2 { /** Nested in a class that can't be static. */ private class NotStatic5 { } } /** Explicitly calls enclosing instance method, not inherited method. */ private class NotStatic6 extends Classes { public void doit() { System.out.println(Classes.this.bar()); } } /** Uses enclosing field in instance initialiser */ private class NotStatic7 { private final int myFoo = foo; } /** A qualified `super` access referring to an enclosing instance's `super`. */ static class Outer extends Classes { class NotStatic8 extends Classes { private void baz() { System.out.println(Outer.super.getClass()); } } } /** Could be static. */ private class SadlyNotStatic { /** Could be static, provided the enclosing class is made static. */ private class SadlyNotStaticToo { } } /** Anonymous classes can't be static. */ private final Object anon = new Object() {}; /** Constructs a class that needs an enclosing instance. */ private class NotStatic8 { { new NotStatic(); } } private class MaybeStatic11 { { new MaybeStatic11(); } } private class MaybeStatic12 { { new Classes().new NotStatic(); } } private class MaybeStatic13 { { new Static(); } } class CouldBeStatic { { new Object() { class CannotBeStatic { } }; } class CouldBeStatic2 { int i; class NotStatic { { i = 0; } } } } /** An inner class extends a non-static class. */ class CannotBeStatic2 { int i; class NotStatic extends Classes.NotStatic { { i = 0; } } } /** Has an inner anonymous class with a field initializer accessing an enclosing instance of this class. */ class CannotBeStatic3 { { new Object() { int i = foo; }; } } /** Has an inner anonymous class with a field initializer accessing a member of this class. */ class CouldBeStatic3 { int j; { new Object() { int i = j; }; } } /** Has a method that calls a constructor that accessing an enclosing instance of this class. */ class CannotBeStatic4 { CannotBeStatic4() { System.out.println(foo); } void foo() { new CannotBeStatic4(); } } }
5,754
20.00365
108
java
codeql
codeql-master/java/ql/test/query-tests/EqualsUsesInstanceOf/Test.java
import java.util.Comparator; class Test { static class CustomComparator<T> implements Comparator<T> { @Override public int compare(Object o1, Object o2) { return 0; } } static class TestComparator extends CustomComparator { int val; @Override public boolean equals(Object o) { if (o instanceof TestComparator) { return ((TestComparator)o).val == val; } return false; } } }
409
17.636364
60
java
codeql
codeql-master/java/ql/test/query-tests/InefficientOutputStream/InefficientOutputStreamGood.java
import java.io.*; import java.security.*; import java.util.*; public class InefficientOutputStreamGood extends OutputStream { private DigestOutputStream digest; private byte[] expectedMD5; public InefficientOutputStreamGood(File file, byte[] expectedMD5) throws IOException, NoSuchAlgorithmException { this.expectedMD5 = expectedMD5; digest = new DigestOutputStream(new FileOutputStream(file), MessageDigest.getInstance("MD5")); } @Override public void write(int b) throws IOException { digest.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { digest.write(b, off, len); } @Override public void close() throws IOException { super.close(); digest.close(); byte[] md5 = digest.getMessageDigest().digest(); if (expectedMD5 != null && !Arrays.equals(expectedMD5, md5)) { throw new InternalError(); } } }
883
24.257143
113
java
codeql
codeql-master/java/ql/test/query-tests/InefficientOutputStream/InefficientOutputStreamBad.java
import java.io.*; import java.security.*; import java.util.*; public class InefficientOutputStreamBad extends OutputStream { private DigestOutputStream digest; private byte[] expectedMD5; public InefficientOutputStreamBad(File file, byte[] expectedMD5) throws IOException, NoSuchAlgorithmException { this.expectedMD5 = expectedMD5; digest = new DigestOutputStream(new FileOutputStream(file), MessageDigest.getInstance("MD5")); } @Override public void write(int b) throws IOException { digest.write(b); } @Override public void close() throws IOException { super.close(); digest.close(); byte[] md5 = digest.getMessageDigest().digest(); if (expectedMD5 != null && !Arrays.equals(expectedMD5, md5)) { throw new InternalError(); } } }
769
24.666667
112
java
codeql
codeql-master/java/ql/test/query-tests/PartiallyMaskedCatch/PartiallyMaskedCatchTest.java
import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class PartiallyMaskedCatchTest { public static void method() { try(ClosableThing thing = new ClosableThing()){ thing.doThing(); } catch (ExceptionB e) { // reachable: ExceptionB is thrown by invocation of CloseableThing.doThing() } catch (ExceptionA e) { // reachable: ExceptionA is thrown by implicit invocation of CloseableThing.close() } catch (IOException e) { // unreachable: only more specific exceptions are thrown and caught by previous catch blocks } try(ClosableThing thing = new ClosableThing()){ thing.doThing(); } catch (ExceptionB | NullPointerException e) { // reachable: ExceptionB is thrown by invocation of CloseableThing.doThing() } catch (ExceptionA | RuntimeException e) { // reachable: ExceptionA is thrown by implicit invocation of CloseableThing.close() } catch (IOException e) { // unreachable: only more specific exceptions are thrown and caught by previous catch blocks } try(ClosableThing thing = new ClosableThing()){ thing.doThing(); } catch (ExceptionB | NullPointerException e) { // reachable: ExceptionB is thrown by invocation of CloseableThing.doThing() } catch (ExceptionA | IllegalArgumentException e) { // reachable: ExceptionA is thrown by implicit invocation of CloseableThing.close() } catch (IOException | RuntimeException e) { // unreachable for type IOException: only more specific exceptions are thrown and caught by previous catch blocks } try { throwingMethod(); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(""); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException(""); } catch (InvocationTargetException ite) { throw new IllegalStateException(""); } try { Class<?> clazz = Class.forName("", true, null).asSubclass(null); Constructor<?> constructor = clazz.getConstructor(); constructor.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(""); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException(""); } catch (InvocationTargetException ite) { throw new IllegalStateException(""); } try(ClosableThing thing = getClosableThing()){ thing.doThing(); } catch (ExceptionB e) { // reachable: ExceptionB is thrown by invocation of CloseableThing.doThing() } catch (ExceptionA e) { // reachable: ExceptionA is thrown by implicit invocation of CloseableThing.close() } catch (IOException e) { // reachable: IOException is thrown by getClosableThing() } try (ClosableThing thing = new ClosableThing()) { genericThrowingMethod(IOException.class); } catch (ExceptionA e) { // reachable: ExceptionA is thrown by implicit invocation of CloseableThing.close() } catch (IOException e) { // reachable: IOException is thrown by invocation of genericThrowingMethod(IOException.class) } } public static ClosableThing getClosableThing() throws IOException { return new ClosableThing(); } public static class ClosableThing implements Closeable { @Override public void close() throws ExceptionA {} public void doThing() throws ExceptionB {} } public static class ExceptionA extends IOException { private static final long serialVersionUID = 1L; } public static class ExceptionB extends ExceptionA { private static final long serialVersionUID = 1L; } public static void throwingMethod() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {} public static <E extends Exception> void genericThrowingMethod(Class<E> c) throws E {} }
3,885
34.981481
116
java
codeql
codeql-master/java/ql/test/query-tests/MissingOverrideAnnotation/Test.java
import java.util.Arrays; import java.util.stream.Collectors; class Super { int m() { return 23; } private void n() {} public String f() { return "Hello"; } } public class Test extends Super { // NOT OK int m() { return 42; } // OK public void n() {} // OK @Override public String f() { return "world"; } public void test() { // OK Arrays.asList(1,2).stream().map(x -> x+1).collect(Collectors.toList()); } }
446
11.771429
73
java
codeql
codeql-master/java/ql/test/query-tests/WhitespaceContradictsPrecedence/WhitespaceContradictsPrecedence.java
public class WhitespaceContradictsPrecedence { int bad(int x) { return x + x>>1; } int ok1(int x) { return x + x >> 1; } int ok2(int x) { return x+x >> 1; } int ok3(int x) { return x + (x>>1); } int ok4(int x, int y, int z) { return x + y + z; } int ok5(int x, int y, int z) { return x + y+z; } int ok6(int x) { return x + x>> 1; } }
373
11.896552
46
java
codeql
codeql-master/java/ql/test/query-tests/UselessNullCheck/A.java
public class A { void f() { Object o = new Object(); if (o == null) { } // Useless check if (o != null) { } // Useless check try { new Object(); } catch(Exception e) { if (e == null) { // Useless check throw new Exception(); } } } void g(Object o) { if (o instanceof A) { A a = (A)o; if (a != null) { // Useless check throw new Exception(); } } } interface I { A get(); } I h() { final A x = this; return () -> { if (x != null) { // Useless check return x; } return new A(); }; } Object f2(Object x) { if (x == null) { return this != null ? this : null; // Useless check } if (x != null) { // Useless check return x; } return null; } private final Object finalObj = new Object(); public void ex12() { finalObj.hashCode(); if (finalObj != null) { // Useless check finalObj.hashCode(); } } }
998
16.526316
57
java
codeql
codeql-master/java/ql/test/query-tests/SelfAssignment/Test.java
class Outer { int x; Outer(int x) { // NOT OK x = x; // OK this.x = x; } Outer() {} class Inner { int x; // OK { x = Outer.this.x; } } class Inner2 extends Outer { // OK { x = Outer.this.x; } } }
225
8.826087
29
java
codeql
codeql-master/java/ql/test/query-tests/LazyInitStaticField/LazyInits.java
public class LazyInits { private static Object lock = new Object(); private static Object badLock; public void resetLock() { badLock = new Object(); } // Eager init public static final LazyInits eager = new LazyInits(); // Correct lazy inits public static LazyInits correct1; public synchronized static LazyInits getCorrect1() { if (correct1 == null) correct1 = new LazyInits(); return correct1; } public static LazyInits correct2; public static LazyInits getCorrect2() { synchronized(LazyInits.class) { if (correct1 == null) correct1 = new LazyInits(); return correct1; } } public static LazyInits correct3; public static LazyInits getCorrect3() { synchronized(lock) { if (correct1 == null) correct1 = new LazyInits(); return correct1; } } private static class Holder { private static LazyInits correct4 = new LazyInits(); } public static LazyInits getCorrect4() { return Holder.correct4; } private static LazyInits correct5; public static LazyInits getCorrect5() { if (correct5 == null) { synchronized(lock) { // NB: Initialising wrong field, so should not trigger this check. if (correct5 == null) correct3 = new LazyInits(); } } return correct5; } private static volatile LazyInits correct6; public static LazyInits getCorrect6() { if (correct6 == null) { synchronized(lock) { if (correct6 == null) correct6 = new LazyInits(); } } return correct6; } private static LazyInits correct7; public static LazyInits getCorrect7() { synchronized(LazyInits.class) { if (correct7 == null) correct7 = new LazyInits(); } return correct7; } private static LazyInits correct8; public static LazyInits getCorrect8() { synchronized(lock) { if (correct8 == null) correct8 = new LazyInits(); } return correct8; } private static LazyInits correct9; static { if (correct9 == null) correct9 = new LazyInits(); } // Bad cases // No synch attempt. private static LazyInits bad1; public static LazyInits getBad1() { if (bad1 == null) bad1 = new LazyInits(); return bad1; } // Synch on field. private static LazyInits bad2; public static LazyInits getBad2() { if (bad2 == null) { synchronized(bad2) { if (bad2 == null) bad2 = new LazyInits(); } } return bad2; } // Synch on unrelated class. private static LazyInits bad3; public static LazyInits getBad3() { if (bad3 == null) { synchronized(Object.class) { if (bad3 == null) bad3 = new LazyInits(); } } return bad3; } // Standard (broken) double-checked locking. private static LazyInits bad4; public static LazyInits getBad4() { if (bad4 == null) { synchronized(LazyInits.class) { if (bad4 == null) bad4 = new LazyInits(); } } return bad4; } // Standard (broken) double-checked locking with lock object. private static LazyInits bad5; public static LazyInits getBad5() { if (bad5 == null) { synchronized(lock) { if (bad5 == null) bad5 = new LazyInits(); } } return bad5; } // Volatile object with bad lock. private static volatile LazyInits bad6; public static LazyInits getBad6() { if (bad6 == null) { synchronized(badLock) { if (bad6 == null) bad6 = new LazyInits(); } } return bad6; } // Other cases // OK private static LazyInits ok; private static java.util.concurrent.locks.ReentrantLock okLock = new java.util.concurrent.locks.ReentrantLock(); public static void init() { okLock.lock(); try { if (ok==null) { ok = new LazyInits(); } } finally { okLock.unlock(); } } }
3,659
19.677966
113
java
codeql
codeql-master/java/ql/test/query-tests/UseBraces/UseBraces.java
class UseBraces { void f() { } void g() { } void h() { } void test() { int x, y; int[] branches = new int[10]; // If-then statement if(1==1) { f(); } g(); // No alert if(1==1) f(); g(); // No alert if(1==1) f(); g(); // Alert if(1==1) f(); g(); // Alert // If-then-else statement if (1 + 2 == 3) { f(); } else { g(); } g(); // No alert if(1==2) f(); else g(); f(); // No alert if(true) { f(); } else f(); g(); // Alert if(true) { f(); } else f(); g(); // Alert // While statement while(false) { f(); } g(); // No alert while(false) f(); g(); while(false) f(); g(); // Alert g(); // No alert while(false) f(); g(); // Alert while(false) if (x != 0) x = 1; // Do-while statement do f(); while(false); g(); // No alert // For statement for(int i=0; i<10; ++i) { f(); } g(); for(int i=0; i<10; ++i) f(); g(); for(int i=0; i<10; ++i) f(); g(); // Alert for(int i=0; i<10; ++i) f(); g(); // Alert // Foreach statement for( int b : branches) x += b; f(); for( int b : branches) { x += b; } f(); for( int b : branches) f(); g(); // Alert for( int b : branches) f(); g(); // Alert // Nested ifs if( true ) if(false) f(); g(); // No alert if( true ) if(false) f(); g(); // Alert if( true ) ; else if (false) f(); g(); // No alert if( true ) ; else if (false) f(); g(); // false negative if( true ) ; else if (false) f(); g(); // Alert // Nested combinations if (true) while (x<10) f(); g(); // No alert if (true) while (x<10) f(); g(); // Alert while (x<10) if (true) f(); g(); // No alert while (x<10) if (true) f(); g(); // Alert if (true) f(); class C {} // No alert if (true) f(); g(); // No alert } }
2,062
9.366834
31
java
codeql
codeql-master/java/ql/test/query-tests/MissedTernaryOpportunity/MissedTernaryOpportunityTest.java
import java.util.*; public class MissedTernaryOpportunityTest { public static boolean missedOpportunity1(int a){ if(a == 42) return true; else return false; } public static boolean doNotComplain1(int a){ if(a == 42){ return true; }else{ System.out.println("output"); return false; } } public static boolean doNotComplain2(int a){ if(a == 42){ System.out.println("output"); return true; }else{ return false; } } public static boolean missedOpportunity2(int a){ boolean ret; if(a == 42) ret = true; else ret = false; return ret; } public static boolean doNotComplain3(int a){ boolean ret; String someOutput; if(a == 42){ ret = true; someOutput = "yes"; }else{ someOutput = "nope"; ret = false; } System.out.println(someOutput); return ret; } // complex condition public static boolean doNotComplain4(int a){ boolean ret; if(a == 42 || a % 2 == 0) ret = true; else ret = false; return ret; } // complex condition public static boolean doNotComplain5(int a){ boolean ret; if(a > 42 && a % 2 == 0) ret = true; else ret = false; return ret; } public static boolean missedOpportunity3(int a){ if(a == 42) return true; else return someOtherFn(a); } // nested function call public static boolean doNotComplain6(int a){ if(a == 42) return true; else return someOtherFn(someFn(a)); } // nested function call public static boolean doNotComplain7(int a){ if(a == 42) return someOtherFn(someFn(a)); else return true; } // nested ConditionalExpr public static boolean doNotComplain8(int a){ if(a > 42) return a == 55 ? true : false; else return true; } private String memberVar1 = "hello"; private String memberVar2 = "hello"; // no assignment public void doNotComplain9(int a){ if(a > 42) System.out.println(memberVar1); else System.out.println(memberVar1 + "5"); } // assignment to two different member variables public void doNotComplain10(int a){ if(a > 42) this.memberVar1 = "hey"; else this.memberVar2 = "hey"; } // same variable names, but different variables (different qualifiers) public void doNotComplain11(int a){ if(a > 42) this.memberVar1 = "hey"; else SomeBogusClass.memberVar1 = "ho"; } // same variables, different qualification public void missedOpportunity4(int a){ if(a > 42) memberVar1 = "hey"; else MissedTernaryOpportunityTest.this.memberVar1 = "ho"; } // nested if public boolean missedOpportunity5(int a){ if(a > 42){ System.out.println("something"); return false; }else{ if(a == 42) return true; else return false; } } // nested if public boolean missedOpportunity6(int a){ if(a > 42){ if(a == 42) return true; else return false; }else{ System.out.println("something"); return false; } } private static int someFn(int a){ return a + 5; } private static boolean someOtherFn(int a){ return a > 0; } private static class SomeBogusClass{ public static String memberVar1 = "something"; } }
3,602
19.82659
74
java
codeql
codeql-master/java/ql/test/query-tests/AvoidDeprecatedCallableAccess/Test.java
public class Test { @Deprecated void m() {} @Deprecated void n() { // OK m(); } { // NOT OK m(); } public static void main(String[] args) { // NOT OK new Test().n(); } }
196
8.85
41
java
codeql
codeql-master/java/ql/test/query-tests/ReturnValueIgnored/return_value_ignored/Test.java
package return_value_ignored; interface I { I setI(int i); } public class Test implements I { private int i; public Test(int i) { this.i = i; } public int getI() { return i; } public Test setI(int i) { this.i = i; return this; } public static void main(String[] args) { Test test1 = new Test(23); Test test2 = new Test(42); Test test3 = new Test(56); // test getter; should flag last call int foo; foo = test1.getI(); foo = test2.getI(); foo = test3.getI(); foo = test1.getI(); foo = test2.getI(); foo = test3.getI(); foo = test1.getI(); foo = test2.getI(); foo = test3.getI(); foo = test1.getI(); foo = test2.getI(); test3.getI(); // test setter; shouldn't flag last call Test test; test = test1.setI(24); test = test2.setI(43); test = test3.setI(57); test = test1.setI(24); test = test2.setI(43); test = test3.setI(57); test = test1.setI(24); test = test2.setI(43); test = test3.setI(57); test = test1.setI(24); test = test2.setI(43); test3.setI(57); // same for call through interface I i1 = test1; I i2 = test2; I i3 = test3; I i; i = i1.setI(24); i = i2.setI(43); i = i3.setI(57); i = i1.setI(24); i = i2.setI(43); i = i3.setI(57); i = i1.setI(24); i = i2.setI(43); i = i3.setI(57); i = i1.setI(24); i = i2.setI(43); i3.setI(57); // should flag last call to String.trim String s = "Hi! ", t; t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); t = s.trim(); s.trim(); } }
1,629
16.717391
42
java
codeql
codeql-master/java/ql/test/query-tests/MissingInstanceofInEquals/AlsoGood.java
class AlsoGood { private int data; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + data; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; return checkEquality(this, obj); } private static boolean checkEquality(AlsoGood thiz, Object obj) { if (thiz.getClass() != obj.getClass()) return false; AlsoGood that = (AlsoGood)obj; if (thiz.data != that.data) return false; return true; } } class Good2 extends Good2Super<Object> { private int data; @Override public int getData() { return data; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getData(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; return checkEquality(obj); } } abstract class Good2Super<T> { protected abstract int getData(); protected boolean checkEquality(Object obj) { if (this.getClass() != obj.getClass()) return false; Good2Super that = (Good2Super)obj; if (this.getData() != that.getData()) return false; return true; } }
1,244
17.863636
66
java
codeql
codeql-master/java/ql/test/query-tests/MissingInstanceofInEquals/Bad.java
class Bad { private int data; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + data; return result; } @Override public boolean equals(Object obj) { Bad other = (Bad) obj; if (data != other.data) return false; return true; } }
300
14.842105
36
java
codeql
codeql-master/java/ql/test/query-tests/MissingInstanceofInEquals/GoodReturn.java
class GoodReturn { public static final GoodReturn GR = new GoodReturn(); @Override public int hashCode() { getClass().hashCode(); } @Override public boolean equals(Object obj) { return obj == GR; } }
224
15.071429
55
java
codeql
codeql-master/java/ql/test/query-tests/MissingInstanceofInEquals/Good.java
class Good { private int data; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + data; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Good other = (Good) obj; if (data != other.data) return false; return true; } }
427
16.12
36
java
codeql
codeql-master/java/ql/test/query-tests/IteratorRemoveMayFail/Test.java
import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; public class Test { public static void main(String[] args) { A a = A.mkA(23, 42); Iterator<Integer> iter = a.getL().iterator(); removeOdd(iter); } private static void removeOdd(Iterator<Integer> iter) { while (iter.hasNext()) { if (iter.next()%2 != 0) iter.remove(); } } } class A { private List<Integer> l; private A(List<Integer> l) { this.l = l; } public static A mkA(Integer... is) { return new A(Arrays.asList(is)); } public static A mkA2(int i) { return new A(Collections.singletonList(i)); } public List<Integer> getL() { return l; } }
696
16.871795
56
java
codeql
codeql-master/java/ql/test/query-tests/ContradictoryTypeChecks/Test.java
public class Test<T> { static class Super {} static class Sub1 extends Super {} static class Sub2 extends Super {} // modeled after results on Alfresco void foo(Super lhs, Super rhs) { if (lhs instanceof Sub1) ; else if (rhs instanceof Sub1) if ((lhs instanceof Sub1) || (lhs instanceof Sub2)); } void bar(Super x) { if (x instanceof Super); else if (x instanceof Sub1); } // modeled after results on Apache Lucene void baz(Super x, Super y) { if (x instanceof Sub1); else if (x instanceof Sub1); } // NOT OK void w(Super x) { if (x instanceof Sub2 || x instanceof Super); else if (x instanceof Sub1); } // modeled after result on WildFly @Override public boolean equals(Object object) { if ((object != null) && !(object instanceof Test)) { Test<?> value = (Test<?>) object; return (this.hashCode() == value.hashCode()) && super.equals(object); } return super.equals(object); } // NOT OK Sub1 m(Super o) { if (!(o instanceof Sub1)) return (Sub1)o; return null; } // OK: not a guaranteed failure Sub1 m2(Super o) { if (!(o instanceof Sub1)); return (Sub1)o; } // OK: reassigned Sub1 m3(Super o) { if (!(o instanceof Sub1)) { o = new Sub1(); return (Sub1)o; } return null; } }
1,265
19.095238
72
java
codeql
codeql-master/java/ql/test/query-tests/NotifyWithoutSynch/Test.java
class NotifyWithoutSynch { private Object obj1; private Object obj2; public synchronized void pass_unqualified_wait() throws InterruptedException { wait(); } public void fail_unqualified_wait() throws InterruptedException { wait(); } public synchronized void pass_unqualified_notify() throws InterruptedException { notify(); } public void fail_unqualified_notify() throws InterruptedException { notify(); } public synchronized void pass_unqualified_notifyAll() throws InterruptedException { notifyAll(); } public void fail_unqualified_notifyAll() throws InterruptedException { notifyAll(); } public void pass_unqualified_wait2() throws InterruptedException { synchronized(this) { wait(); } } public synchronized void pass_qualified_wait01() throws InterruptedException { this.wait(); } public void pass_qualified_wait02() throws InterruptedException { synchronized(this) { this.wait(); } } public void pass_qualified_wait03() throws InterruptedException { synchronized(obj1) { obj1.wait(); } } public void fail_qualified_wait01() throws InterruptedException { this.wait(); } public void fail_qualified_wait02() throws InterruptedException { this.wait(); } public void fail_qualified_wait03() throws InterruptedException { synchronized(obj1) { this.wait(); } } public void fail_qualified_wait04() throws InterruptedException { synchronized(this) { obj1.wait(); } } public synchronized void fail_qualified_wait05() throws InterruptedException { obj1.wait(); } public synchronized void fail_qualified_wait06() throws InterruptedException { synchronized(obj1) { obj2.wait(); } } private void pass_indirect_callee07() throws InterruptedException { this.wait(); } private void pass_indirect_callee08() throws InterruptedException { pass_indirect_callee07(); } private void pass_indirect_callee09() throws InterruptedException { pass_indirect_callee07(); } private void pass_indirect_callee10() throws InterruptedException { pass_indirect_callee07(); } public synchronized void pass_indirect_caller11() throws InterruptedException { pass_indirect_callee08(); } public void pass_indirect_caller12() throws InterruptedException { synchronized(this) { pass_indirect_callee09(); } } public void pass_indirect_caller13() throws InterruptedException { synchronized(NotifyWithoutSynch.this) { pass_indirect_callee10(); } } private void fail_indirect_callee14() throws InterruptedException { wait(); } public void fail_indirect_caller15() throws InterruptedException { fail_indirect_callee14(); } }
2,651
20.917355
84
java
codeql
codeql-master/java/ql/test/query-tests/Javadoc/ImpossibleJavadocThrows.java
import java.lang.InterruptedException; import java.lang.Exception; import java.lang.RuntimeException; class ImpossibleJavadocThrows { /** * * @throws InterruptedException */ public void bad1() { } /** * * @exception Exception */ public void bad2() { } /** * * @throws InterruptedException */ public void goodDeclared() throws Exception{ } /** * * @exception RuntimeException */ public void goodUnchecked(){ } }
459
12.529412
45
java
codeql
codeql-master/java/ql/test/query-tests/MutualDependency/otherpackage/OtherClass.java
package otherpackage; public class OtherClass { public static int c = onepackage.MutualDependency.B.b; }
107
17
55
java
codeql
codeql-master/java/ql/test/query-tests/MutualDependency/onepackage/MutualDependency.java
package onepackage; public class MutualDependency { static int m = A.a; // allow intra-package dependencies static class A { static int a = m; } // disallow inter-package dependencies public static class B { public static int b = otherpackage.OtherClass.c; } }
273
18.571429
50
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/SuppressedConstructorTest.java
public class SuppressedConstructorTest { private static class SuppressedConstructor { // This should not be reported as dead private SuppressedConstructor() { } public static void liveMethod() { } } public void deadMethod() { new NestedPrivateConstructor(); } private static class NestedPrivateConstructor { // This should be dead, because it is called from a dead method. private NestedPrivateConstructor() { } public static void liveMethod() { } } private static class OtherConstructor { /* * This should be marked as dead. There is another constructor declared, so no default * constructor will be added by the compiler. Therefore, we do not need to declare this private * in order to suppress it. */ private OtherConstructor() { } // Live constructor private OtherConstructor(Object foo) { } } public static void main(String[] args) { new OtherConstructor(new Object()); SuppressedConstructor.liveMethod(); NestedPrivateConstructor.liveMethod(); } }
1,057
26.842105
99
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/InternalDeadCodeCycle.java
public class InternalDeadCodeCycle { public void foo() { bar(); } public void bar() { foo(); } public static void main(String[] args) { // Ensure the class is live, otherwise the dead methods will not be reported. } }
233
14.6
79
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/ReflectionMethodTest.java
public class ReflectionMethodTest { public static class TestObject1 { public void test1() { } } public static class TestObject2 { public void test2() { } } public static class TestObject3 { public void test3() { } } public static class TestObject4 { public void test4() { } } public static class TestObject4a extends TestObject4 { public void test4() { } } public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Get class by name Class.forName("ReflectionTest$TestObject1").getMethod("test1"); // Use classloader ReflectionTest.class.getClassLoader().loadClass("ReflectionTest$TestObject2").getMethod("test2"); // Store in variable, load from that Class<?> clazz = Class.forName("ReflectionTest$TestObject3"); clazz.getMethod("test3"); /* * We cannot determine the class by looking at a String literal, so we should look to the * type - in this case Class<? extends TestObject4>. We should therefore identify both * TestObject4 and TestObject4a as live. */ getClass4().getMethod("test4"); } public static Class<? extends TestObject4> getClass4() { return TestObject4.class; } }
1,259
29
120
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/JMXTest.java
import java.lang.management.ManagementFactory; import javax.management.ObjectName; public class JMXTest { public static interface FooMBean { public String sometimesLiveMethod(String arg); public String liveMethod2(String arg); } public static class FooIntermediate implements FooMBean { // This method is dead, because it is overridden in FooImpl, which is the registered MBean. public String sometimesLiveMethod(String arg) { return "foo"; } // This method is live, because it is the most specific method for FooImpl public String liveMethod2(String arg) { return "foo"; } } // MBean registered class public static class FooImpl extends FooIntermediate { // This method is live, because it is declared in FooMBean. public String sometimesLiveMethod(String arg) { return "foo"; } } public static void register(Object o) throws Exception { ManagementFactory.getPlatformMBeanServer().registerMBean(o, new ObjectName("foo")); } public static void main(String[] args) throws Exception { register(new FooImpl()); } }
1,050
30.848485
93
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/ArbitraryXMLLiveness.java
public class ArbitraryXMLLiveness { public ArbitraryXMLLiveness() { } public static void main(String[] args) { // Ensure the class is live, otherwise the dead methods will not be reported. } }
201
19.2
79
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/DefaultConstructorTest.java
public class DefaultConstructorTest { }
40
12.666667
37
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadMethod/ReflectionTest.java
public class ReflectionTest { public static class TestObject1 { public TestObject1() { } } public static class TestObject2 { public TestObject2() { } } public static class TestObject3 { public TestObject3() { } } public static class TestObject4 { public TestObject4() { } } public static class TestObject4a extends TestObject4 { public TestObject4a() { } } public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Get class by name Class.forName("ReflectionTest$TestObject1").newInstance(); // Use classloader ReflectionTest.class.getClassLoader().loadClass("ReflectionTest$TestObject2").newInstance(); // Store in variable, load from that Class<?> clazz = Class.forName("ReflectionTest$TestObject3"); clazz.newInstance(); /* * We cannot determine the class by looking at a String literal, so we should look to the * type - in this case Class<? extends TestObject4>. We should therefore identify both * TestObject4 and TestObject4a as live. */ getClass4().newInstance(); } public static Class<? extends TestObject4> getClass4() { return TestObject4.class; } }
1,187
27.285714
119
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/NamespaceTest.java
public class NamespaceTest { /** * A namespace class because it only includes static members. It should * be live, because it has a live inner class. */ public static class NamespaceClass { /** * Empty constructor provided to suppress the default public constructor. Should not prevent this * from being idenfitied as namespace class. */ protected NamespaceClass() { } public static class LiveInnerClass { } public static boolean deadStaticField = false; public static void deadStaticMethod() { } } /** * A namespace class that uses enums. It should be live, because it has a live inner class. * It extends another namespace class, which is permitted. */ public static class NamespaceEnumClass extends NamespaceClass { public static enum LiveInnerClass3 { } } /** * This class is not a namespace class, because it has an instance method. The nested live class * should not make the NonNamespaceClass live. */ public static class NonNamespaceClass { public static class LiveInnerClass2 { } public boolean deadInstanceField = false; public void deadMethod() { } } public static void main(String[] args){ new NamespaceClass.LiveInnerClass(); new NonNamespaceClass.LiveInnerClass2(); NamespaceEnumClass.LiveInnerClass3.values(); } }
1,370
25.365385
101
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/InternalDeadCodeCycle.java
/** * This class should be marked as entirely unused. */ public class InternalDeadCodeCycle { public void foo() { bar(); } public void bar() { foo(); } }
166
10.928571
50
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/ExternalDeadRoot.java
public class ExternalDeadRoot { /** * This class should be marked as only being used by the "outerDeadRoot()". The * "innerDeadRoot()" should not be reported as a dead root, as it is internal to the class. */ public static class DeadClass { public static void innerDeadRoot() { } public static void innerDeadMethod() { } } public static void outerDeadRoot() { DeadClass.innerDeadMethod(); } public static void main(String[] args) { // Make outer class live. } }
492
19.541667
92
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/DeadEnumTest.java
public class DeadEnumTest { public enum DeadEnum { A } public enum LiveEnum { A } public static void main(String[] args) { LiveEnum.values(); } }
172
11.357143
42
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/AnnotationTest.java
import java.lang.SuppressWarnings; public class AnnotationTest { @SuppressWarnings("unchecked") public static class AnnotatedClass { } public static void main(String[] args) { AnnotatedClass.class.getAnnotation(SuppressWarnings.class); } }
256
20.416667
63
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadClass/ExternalDeadCodeCycle.java
public class ExternalDeadCodeCycle { /** * This class should be marked as being only used from a dead code cycle, because the dead-code * cycle is external to the class. */ public static class DeadClass { public static void deadMethod() { } } public static void cyclicDeadMethodA() { DeadClass.deadMethod(); cyclicDeadMethodB(); } public static void cyclicDeadMethodB() { cyclicDeadMethodA(); } public static void main(String[] args) { // Make outer class live. } }
498
18.192308
96
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/UselessParameter/Test.java
interface I { // NOT OK: no overriding method uses x void foo(int x); // OK: no concrete implementation void bar(String y); // OK: no concrete implementation void baz(float f); // OK: some overriding method uses x int qux(boolean b); } abstract class A implements I { // OK: I.foo is already flagged @Override public void foo(int x) {} // OK: no concrete implementation @Override public abstract void baz(float f); // OK: uses b @Override public int qux(boolean b) { return b ? 42 : 23; } } abstract class B extends A { // OK: I.foo is already flagged @Override public void foo(int x) {} } abstract class C implements I { // OK: overrides I.qux @Override public int qux(boolean b) { return 56; } } interface F { void doSomething(int arg2); } public class Test { // OK: external interface public static void main(String[] args) {} // OK: external interface public static void premain(String arg) {} // OK: external interface public static void premain(String arg, java.lang.instrument.Instrumentation i) {} // OK: Pseudo-abstract method public static void foo(Object bar) { throw new UnsupportedOperationException(); } public static F getF() { return Test::myFImplementation; } // OK: mentioned in member reference private static void myFImplementation(int foo) {} // OK: native method native int baz(int x); { class MyMap extends java.util.HashMap<String,String> { // OK: method overrides super-class method @Override public void putAll(java.util.Map<? extends String,? extends String> m) {}; } class MyComparable<T> implements Comparable<T> { // OK: method overrides super-interface method @Override public int compareTo(T o) { return 0; } }; class MyComparable2 implements Comparable<Boolean> { // OK: method overrides super-interface method @Override public int compareTo(Boolean o) { return 0; } }; class MySub<T> implements java.util.concurrent.ScheduledFuture<T> { public int compareTo(java.util.concurrent.Delayed o) { return 0; } public long getDelay(java.util.concurrent.TimeUnit unit) { return 0; } // OK: method overrides super-super-interface method @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } public T get() { return null; } // OK: method overrides super-super-interface method @Override public T get(long timeout, java.util.concurrent.TimeUnit unit) { return null; } public boolean isCancelled() { return false; }; public boolean isDone() { return false; }; } } }
2,594
21.763158
82
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadField/AnnotationValueTest.java
public class AnnotationValueTest { public static @interface TestAnnotation { public String[] value(); } @TestAnnotation(value = AnnotationValueUtil.LIVE_STRING_CONSTANT_FIELD) public static String liveField = ""; @TestAnnotation(value = AnnotationValueUtil.DEAD_STRING_CONSTANT_FIELD) public static String deadField = ""; @TestAnnotation(value = { AnnotationValueUtil.LIVE_STRING_CONSTANT_METHOD }) public static void liveMethod() { } @TestAnnotation(value = AnnotationValueUtil.DEAD_STRING_CONSTANT_METHOD) public static void deadMethod() { } /** * Class is live because it is constructed in the main method, which in turn should make this * annotation live, causing LIVE_STRING_CONSTANT_CLASS to be live because it is read in the * annotation. */ @TestAnnotation(value = AnnotationValueUtil.LIVE_STRING_CONSTANT_CLASS + "..") public static class LiveClass { } /** * This class is dead, so the annotation is dead, and the field read of * DEAD_STRING_CONSTANT_CLASS will not make the field live. */ @TestAnnotation(value = AnnotationValueUtil.DEAD_STRING_CONSTANT_CLASS) public static class DeadClass { } public static void main(String[] args) { System.out.println(liveField); liveMethod(); new LiveClass(); } }
1,264
27.75
94
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadField/BasicTest.java
public class BasicTest { private static String deadStaticField = "Dead"; private static String liveStaticField = "Live"; private String deadField; private String deadCycleField; private String liveField; public BasicTest(String deadField, String liveField) { this.deadField = deadField; this.liveField = liveField; } public String getDeadField() { return deadField; } public String getLiveField() { return liveField; } public String useDeadCycleFielda() { return useDeadCycleFieldb(deadCycleField); } public String useDeadCycleFieldb(String val) { return val + useDeadCycleFielda(); } public static String getDeadStaticField() { return deadStaticField; } public static String getLiveStaticField() { return liveStaticField; } public static void main(String[] args) { new BasicTest("dead", "live").getLiveField(); getLiveStaticField(); } }
887
20.142857
55
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadField/AnnotationValueUtil.java
public class AnnotationValueUtil { /** * Live because it is used as an annotation value on a live field. */ public static final String LIVE_STRING_CONSTANT_FIELD = "A string constant."; /** * Live because it is used as annotation values on a live method. */ public static final String LIVE_STRING_CONSTANT_METHOD = "A string constant."; /** * Live because it is used as annotation values on a live class. */ public static final String LIVE_STRING_CONSTANT_CLASS = "A string constant."; /** * These three should be dead because they are used as annotation values on dead fields/methods/classes. */ public static final String DEAD_STRING_CONSTANT_FIELD = "A string constant."; public static final String DEAD_STRING_CONSTANT_METHOD = "A string constant."; public static final String DEAD_STRING_CONSTANT_CLASS = "A string constant."; public static void main(String[] args) { // Ensure outer class is live. } }
944
30.5
105
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadField/ReflectionTest.java
public class ReflectionTest { public static class ParentClass { // Not live private int notInheritedField; // Live because it is accessed through ChildClass public int inheritedField; // Not live because it is shadowed by the child public int shadowedField; } public static class ChildClass extends ParentClass { // Live field, accessed directly private int notInheritedField; // Live field, accessed directly public int shadowedField; } public static void main(String[] args) { // Ensure the two classes are live, otherwise we might hide some results new ParentClass(); new ChildClass(); ChildClass.class.getDeclaredField("notInheritedField"); ChildClass.class.getField("inheritedField"); ChildClass.class.getField("shadowedField"); } }
780
25.931034
74
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadEnumConstant/DeadEnumConstantTest.java
import java.util.*; public class DeadEnumConstantTest { public @interface MyAnnotation{}; public static enum E1{ unused1, unused2, @MyAnnotation ok1, // constants with reflective annotations should be ignored ok2, ok3, ok4, ok5, } @MyAnnotation public static enum Ignore{ ok1, ok2, ok3; } public static void main(String[] args){ method1(E1.unused1 == E1.unused2); // does not count as use, since constants can't be stored this way method2(E1.ok2); // constant could potentially be stored method2(1 != 2 ? E1.ok3 : E1. ok4); method3(); } public static void method1(boolean a){} public static void method2(E1 e1){} public static E1 method3(){ return E1.ok5; // returns constant, which could possibly be stored by the caller } }
874
24
107
java
codeql
codeql-master/java/ql/test/query-tests/dead-code/DeadCallable/Main.java
public class Main { private static String ss = "a"; private static String ss2 = "b"; private final String is = "a"; private final String is2 = "b"; private void unused() { indirectlyUnused(); } private void indirectlyUnused() {} private void foo() { bar(); } private void bar() { foo(); } public static void main(String[] args) {} }
351
18.555556
42
java
codeql
codeql-master/java/ql/test/query-tests/RangeAnalysis/A.java
public class A { private static final int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; private final int[] arr2; private final int[] arr3; public A(int[] arr2, int n) { if (arr2.length % 2 != 0) throw new Exception(); this.arr2 = arr2; this.arr3 = new int[n << 1]; } void m1(int[] a) { int sum = 0; for (int i = 0; i <= a.length; i++) { sum += a[i]; // Out of bounds } } void m2(int[] a) { int sum = 0; for (int i = 0; i < a.length; i += 2) { sum += a[i] + a[i + 1]; // Out of bounds (unless len%2==0) } } void m3(int[] a) { if (a.length % 2 != 0) return; int sum = 0; for (int i = 0; i < a.length; ) { sum += a[i++]; // OK sum += a[i++]; // OK } for (int i = 0; i < arr1.length; ) { sum += arr1[i++]; // OK sum += arr1[i++]; // OK i += 2; } for (int i = 0; i < arr2.length; ) { sum += arr2[i++]; // OK sum += arr2[i++]; // OK - FP } for (int i = 0; i < arr3.length; ) { sum += arr3[i++]; // OK sum += arr3[i++]; // OK - FP } int[] b; if (sum > 3) b = a; else b = arr1; for (int i = 0; i < b.length; i++) { sum += b[i]; // OK sum += b[++i]; // OK - FP } } void m4(int[] a, int[] b) { assert a.length % 2 == 0; int sum = 0; for (int i = 0; i < a.length; ) { sum += a[i++]; // OK sum += a[i++]; // OK - FP } int len = b.length; if ((len & 1) != 0) return; for (int i = 0; i < len; ) { sum += b[i++]; // OK sum += b[i++]; // OK } } void m5(int n) { int[] a = new int[3 * n]; int sum = 0; for (int i = 0; i < a.length; i += 3) { sum += a[i] + a[i + 1] + a[i + 2]; // OK } } int m6(int[] a, int ix) { if (ix < 0 || ix > a.length) return 0; return a[ix]; // Out of bounds } void m7() { int[] xs = new int[11]; int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { sum += xs[i]; // OK sum += xs[j]; // OK if (i < j) sum += xs[i + 11 - j]; // OK - FP else sum += xs[i - j]; // OK } } } void m8(int[] a) { if ((a.length - 4) % 3 != 0) return; int sum = 0; for (int i = 4; i < a.length; i += 3) { sum += a[i]; // OK sum += a[i + 1]; // OK - FP sum += a[i + 2]; // OK - FP } } void m9() { int[] a = new int[] { 1, 2, 3, 4, 5 }; int sum = 0; for (int i = 0; i < 10; i++) { if (i < 5) sum += a[i]; // OK else sum += a[9 - i]; // OK - FP } } void m10(int n, int m) { int len = Math.min(n, m); int[] a = new int[n]; int sum = 0; for (int i = n - 1; i >= 0; i--) { sum += a[i]; // OK for (int j = i + 1; j < len; j++) { sum += a[j]; // OK sum += a[i + 1]; // OK - FP } } } void m11(int n) { int len = n*2; int[] a = new int[len]; int sum = 0; for (int i = 0; i < len; i = i + 2) { sum += a[i+1]; // OK for (int j = i; j < len - 2; j = j + 2) { sum += a[j]; // OK sum += a[j+1]; // OK sum += a[j+2]; // OK sum += a[j+3]; // OK } } } void m12() { int[] a = new int[] { 1, 2, 3, 4, 5, 6 }; int sum = 0; for (int i = 0; i < a.length; i += 2) { sum += a[i] + a[i + 1]; // OK } int[] b = new int[8]; for (int i = 2; i < 8; i += 2) { sum += b[i] + b[i + 1]; // OK } } void m13(int n) { int[] a = null; if (n > 0) { a = n > 0 ? new int[3 * n] : null; } int sum; if (a != null) { for (int i = 0; i < a.length; i += 3) { sum += a[i + 2]; // OK } } } void m14(int[] xs) { for (int i = 0; i < xs.length + 1; i++) { if (i == 0 && xs.length > 0) { xs[i]++; // OK - FP } } } void m15(int[] xs) { for (int i = 0; i < xs.length; i++) { int x = ++i; int y = ++i; if (y < xs.length) { xs[x]++; // OK - FP xs[y]++; // OK } } } }
4,152
19.974747
73
java
codeql
codeql-master/java/ql/test/query-tests/Finally/Finally.java
class InFinally { void returnVoidInFinally() { try { } finally { return; } } int returnIntInFinally(boolean b1, boolean b2) { try { if (b1) { return 4; } } finally { if (b2) { return 5; } } return 3; } int throwInFinally(boolean b1, boolean b2) { try { if (b1) { throw new RuntimeException("Foo 1"); } } finally { if (b2) { throw new RuntimeException("Foo 2"); } } throw new RuntimeException("Foo 3"); } void breakInFinally(boolean b) { for (int i = 0; i < 10; i++) { if(b) { break; } } try { for (int i = 0; i < 10; i++) { if(b) { break; } } } finally { for (int i = 0; i < 10; i++) { if(b) { break; } } } for (int i = 0; i < 10; i++) { try { if(b) { break; } } finally { if(b) { break; } } } try { } finally { for (int i = 0; i < 10; i++) { try { if(b) { break; } } finally { if(b) { break; } } } } } void continueInFinally(boolean b) { for (int i = 0; i < 10; i++) { if(b) { continue; } } try { for (int i = 0; i < 10; i++) { if(b) { continue; } } } finally { for (int i = 0; i < 10; i++) { if(b) { continue; } } } for (int i = 0; i < 10; i++) { try { if(b) { continue; } } finally { if(b) { continue; } } } try { } finally { for (int i = 0; i < 10; i++) { try { if(b) { continue; } } finally { if(b) { continue; } } } } } }
1,619
11.180451
49
java
codeql
codeql-master/java/ql/test/query-tests/Declarations/Test.java
public class Test { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { switch(args.length) { case -2: return; case -1: continue; case 0: System.out.println("No args"); break; case 1: case 2: System.out.println("1-2 args"); // missing break. case 3: System.out.println("3 or more args"); // fall-through case 4: System.out.println("4 or more args"); if (i > 1) break; // conditionally missing break. case 5: System.out.println("foo"); // Missing break, but switch ends. } } } }
601
17.8125
41
java
codeql
codeql-master/java/ql/test/query-tests/SpuriousJavadocParam/Test.java
public class Test<V> { // no javadoc public void ok0(){ } /* no javadoc */ public void ok1(){ } /** * no tags */ public void ok2(){ } /** * @param p1 correctly spelled */ public void ok3(int p1){ } /** * @param <T> type parameter */ public <T> T ok4(){ return null; } /** * @param <T> several type * @param <V> parameters */ public <T,V> T ok5(V p){ return null; } /** * @param <T> several type * @param <V> parameters * @param p mixed with normal parameters */ public <T,V> T ok6(V p){ return null; } /** * weird parameter name * @param <V> * @param V */ private <V> void ok7(V V){ V = null; } /** * not a param * param something */ protected void ok8(){ } /** * param param * @param param */ protected void ok9(int...param){ } /** * @param prameter typo */ public void problem1(int parameter){ } /** * @param Parameter capitalization */ public void problem2(int parameter){ } /** * @param parameter unmatched */ public void problem3(){ } /** * @param someOtherParameter matched * @param parameter unmatched */ public void problem4(int someOtherParameter){ } /** * @param <V> unmatched type parameter */ private <T> T problem5(){ return null; } /** * @param <V> matched type parameter * @param <P> unmatched type parameter * @param n unmatched normal parameter */ private <T,V> T problem6(V p){ return null; } /** * param with immediate newline * @param */ protected void problem7(){ } /** * param without a value (followed by blanks) * @param */ protected void problem8(){ } class SomeClass { /** * @param i exists * @param k does not */ SomeClass(int i, int j) {} } }
1,852
16
49
java
codeql
codeql-master/java/ql/test/query-tests/ReadOnlyContainer/Test.java
import java.util.*; public class Test { boolean containsDuplicates(Object[] array) { Set<Object> seen = new HashSet<Object>(); for (Object o : array) { // should be flagged if (seen.contains(o)) return true; } return false; } void foo(List<Integer> l) { // should not be flagged l.contains(23); } void bar(Collection<List<Integer>> c) { for (List<Integer> l : c) // should not be flagged l.contains(c); } List<Integer> l = new LinkedList<Integer>(); List<Integer> getL() { return l; } { getL().add(23); // should not be flagged l.contains(23); } void add23(List<Integer> l) { l.add(23); } void baz() { List<Integer> l = new LinkedList<Integer>(); add23(l); // should not be flagged l.contains(23); } { List<Integer> l2 = new LinkedList<Integer>(l); // should not be flagged l2.contains(23); List<Integer> l3 = new LinkedList<Integer>(); l3.add(42); // should not be flagged l3.contains(23); List<Integer> l4 = new LinkedList<Integer>(); l4.addAll(l); // should not be flagged l4.contains(23); Stack<Integer> l5 = new Stack<Integer>(); l5.push(23); // should not be flagged l5.contains(23); } List<Boolean> g() { List<Boolean> bl = new ArrayList<Boolean>(); // should be flagged bl.contains(false); return bl; } // should not be flagged private Set<Integer> sneakySet = new LinkedHashSet<Integer>() {{ add(23); add(42); }}; boolean inSneakySet(int x) { return sneakySet.contains(x); } }
1,531
17.238095
65
java
codeql
codeql-master/java/ql/test/query-tests/StaticArray/StaticArray.java
class StaticArray { public static final int[] bad = new int[42]; //NOT OK protected static final int[] good_protected = new int[42]; //OK (protected arrays are ok) /* default */ static final int[] good_default = new int[42]; //OK (default access arrays are ok) private static final int[] good_private = new int[42]; //OK (private arrays are ok) public final /* static */ int[] good_nonstatic = new int[42]; //OK (non-static arrays are ok) public /* final */ static int[] good_nonfinal = new int[42]; //OK (non-final arrays are ok) public static final Object good_not_array = new int[42]; //OK (non-arrays are ok) public static final int[][][] bad_multidimensional = new int[42][42][42]; //NOT OK public static final int[][][] bad_multidimensional_partial_init = new int[42][][]; //NOT OK public static final int[] bad_separate_init; //NOT OK static { bad_separate_init = new int[42]; } public static final int[] good_empty = new int[0]; //OK (empty array creation) public static final int[] good_empty2 = {}; //OK (empty array literal) public static final int[][] good_empty_multidimensional = new int[0][42]; //OK (empty array) public static final int[][] bad_nonempty = { {} }; //NOT OK (first dimension is 1, so not empty) }
1,302
43.931034
100
java
codeql
codeql-master/java/ql/test/query-tests/Iterable/Test.java
import java.util.*; class Test { void useIterable(Iterable<String> i) { for (String s : i) { } for (String s : i) { } } List<String> someStrings; void m() { useIterable(new Iterable<String>() { final Iterator<String> i = someStrings.iterator(); // bad @Override public Iterator<String> iterator() { return new Iterator<String>() { @Override public boolean hasNext() { return i.hasNext(); } @Override public String next() { return "foo " + i.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }); useIterable(new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { final Iterator<String> i = someStrings.iterator(); // ok @Override public boolean hasNext() { return i.hasNext(); } @Override public String next() { return "foo " + i.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }); } class Value { } class ValueIterator implements Iterator<Value> { private Value val = new Value(); @Override public boolean hasNext() { return val != null; } @Override public Value next() { Value v = val; val = null; return v; } @Override public void remove() { } } protected class ValueIterableBad implements Iterable<Value> { private ValueIterator iterator = new ValueIterator(); // bad @Override public Iterator<Value> iterator() { return iterator; } } protected class ValueIterableOk implements Iterable<Value> { @Override public Iterator<Value> iterator() { ValueIterator iterator = new ValueIterator(); // ok return iterator; } } class MyCollectionOk implements Iterable<Integer> { final Iterator<Integer> emptyIter = new Iterator<Integer>() { // ok @Override public boolean hasNext() { return false; } @Override public Integer next() { throw new UnsupportedOperationException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; private List<Integer> ints; MyCollectionOk(List<Integer> ints) { this.ints = ints; } public Iterator<Integer> iterator() { if (ints.size() == 0) return emptyIter; return ints.iterator(); } } class IntIteratorBad implements Iterable<Integer>, Iterator<Integer> { private int[] ints; private int idx = 0; IntIteratorBad(int[] ints) { this.ints = ints; } @Override public boolean hasNext() { return idx < ints.length; } @Override public Integer next() { return ints[idx++]; } @Override public void remove() { throw new UnsupportedOperationException(); } public Iterator<Integer> iterator() { return this; // bad } } class IntIteratorOk implements Iterable<Integer>, Iterator<Integer> { private int[] ints; private int idx = 0; private boolean returnedIterator = false; IntIteratorOk(int[] ints) { this.ints = ints; } @Override public boolean hasNext() { return idx < ints.length; } @Override public Integer next() { return ints[idx++]; } @Override public void remove() { throw new UnsupportedOperationException(); } public Iterator<Integer> iterator() { // ok if (returnedIterator || idx > 0) throw new IllegalStateException(); returnedIterator = true; return this; } } class EmptyIntIterator implements Iterable<Integer>, Iterator<Integer> { @Override public boolean hasNext() { return false; } @Override public Integer next() { throw new UnsupportedOperationException(); } @Override public void remove() { throw new UnsupportedOperationException(); } public Iterator<Integer> iterator() { // ok return this; } } }
4,306
22.535519
78
java
codeql
codeql-master/java/ql/test/query-tests/SuspiciousDateFormat/A.java
import java.text.SimpleDateFormat; import java.util.Date; public class A { public static void main(String[] args) { System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(new Date())); // OK System.out.println(new SimpleDateFormat("YYYY-ww").format(new Date())); // OK System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(new Date())); // BAD } }
370
32.727273
83
java
codeql
codeql-master/java/ql/test/query-tests/LShiftLargerThanTypeWidth/A.java
public class A { void test1(byte b, char c, short s, int i, long l) { long b1 = b << 31; // OK long b2 = b << 32; // BAD long b3 = b << 33; // BAD long b4 = b << 64; // BAD long c1 = c << 22; // OK long c2 = c << 42; // BAD long s1 = s << 22; // OK long s2 = s << 42; // BAD long i1 = i << 22; // OK long i2 = i << 32; // BAD long i3 = i << 42; // BAD long i4 = i << 64; // BAD long i5 = i << 65; // BAD long l1 = l << 22; // OK long l2 = l << 32; // OK long l3 = l << 42; // OK long l4 = l << 64; // BAD long l5 = l << 65; // BAD } void test2(Byte b, Character c, Short s, Integer i, Long l) { long b1 = b << 31; // OK long b2 = b << 32; // BAD long b3 = b << 33; // BAD long b4 = b << 64; // BAD long c1 = c << 22; // OK long c2 = c << 42; // BAD long s1 = s << 22; // OK long s2 = s << 42; // BAD long i1 = i << 22; // OK long i2 = i << 32; // BAD long i3 = i << 42; // BAD long i4 = i << 64; // BAD long i5 = i << 65; // BAD long l1 = l << 22; // OK long l2 = l << 32; // OK long l3 = l << 42; // OK long l4 = l << 64; // BAD long l5 = l << 65; // BAD } }
1,221
22.5
63
java
codeql
codeql-master/java/ql/test/query-tests/HashedButNoHash/Test.java
import java.util.HashMap; import java.util.IdentityHashMap; class Test { { IdentityHashMap<Object, String> map = new IdentityHashMap<>(); A a = new A(); map.put(a, "value"); HashMap<Object, String> map2 = new HashMap<>(); map2.put(a, "value"); } } class A { int i; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof A)) { return false; } A other = (A) obj; if (i != other.i) { return false; } return true; } }
546
14.628571
64
java
codeql
codeql-master/java/ql/test/query-tests/AlertSuppression/TestSuppressWarnings.java
@SuppressWarnings("lgtm[java/non-sync-override]") @Deprecated class TestSuppressWarnings { @SuppressWarnings("lgtm[]") public void test() { } @Deprecated @SuppressWarnings({"lgtm[java/confusing-method-name] not confusing","lgtm[java/non-sync-override]"}) public void test2() { } @SuppressWarnings("lgtm") public void test3() { } @SuppressWarnings({"lgtm[java/confusing-method-name] blah blah lgtm[java/non-sync-override]"}) public void test4() { } }
539
22.478261
104
java
codeql
codeql-master/java/ql/test/query-tests/AlertSuppression/Test.java
class Test {} // lgtm // lgtm[java/confusing-method-name] // lgtm[java/confusing-method-name, java/non-short-circuit-evaluation] // lgtm[@tag:exceptions] // lgtm[@tag:exceptions,java/confusing-method-name] // lgtm[@expires:2017-06-11] // lgtm[java/confusing-method-name] does not seem confusing despite alert by lgtm // lgtm: blah blah // lgtm blah blah #falsepositive //lgtm [java/confusing-method-name] /* lgtm */ // lgtm[] // lgtmfoo //lgtm // lgtm // lgtm [java/confusing-method-name] // foolgtm[java/confusing-method-name] // foolgtm // foo; lgtm // foo; lgtm[java/confusing-method-name] // foo lgtm // foo lgtm[java/confusing-method-name] // foo lgtm bar // foo lgtm[java/confusing-method-name] bar // LGTM! // LGTM[java/confusing-method-name] //lgtm[java/confusing-method-name] and lgtm[java/non-short-circuit-evaluation] //lgtm[java/confusing-method-name]; lgtm /* lgtm[] */ /* lgtm[java/confusing-method-name] */ /* lgtm */ /* lgtm */ /* lgtm[@tag:nullness,java/confusing-method-name] */ /* lgtm[@tag:nullness] */ /** lgtm[] */
1,039
25.666667
81
java
codeql
codeql-master/java/ql/test/query-tests/AlertSuppression/TestWindows.java
class TestWindows {} // lgtm // lgtm[java/confusing-method-name] // lgtm[java/confusing-method-name, java/non-short-circuit-evaluation] // lgtm[@tag:exceptions] // lgtm[@tag:exceptions,java/confusing-method-name] // lgtm[@expires:2017-06-11] // lgtm[java/confusing-method-name] does not seem confusing despite alert by lgtm // lgtm: blah blah // lgtm blah blah #falsepositive //lgtm [java/confusing-method-name] /* lgtm */ // lgtm[] // lgtmfoo //lgtm // lgtm // lgtm [java/confusing-method-name] // foolgtm[java/confusing-method-name] // foolgtm // foo; lgtm // foo; lgtm[java/confusing-method-name] // foo lgtm // foo lgtm[java/confusing-method-name] // foo lgtm bar // foo lgtm[java/confusing-method-name] bar // LGTM! // LGTM[java/confusing-method-name] //lgtm[java/confusing-method-name] and lgtm[java/non-short-circuit-evaluation] //lgtm[java/confusing-method-name]; lgtm /* lgtm[] */ /* lgtm[java/confusing-method-name] */ /* lgtm */ /* lgtm */ /* lgtm[@tag:nullness,java/confusing-method-name] */ /* lgtm[@tag:nullness] */ /** lgtm[] */
1,046
25.846154
81
java