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/src/Likely Bugs/Comparison/InconsistentEqualsHashCodeGood.java | public class InconsistentEqualsHashCodeFix {
private int i = 0;
public InconsistentEqualsHashCodeFix(int i) {
this.i = i;
}
@Override
public int hashCode() {
return i;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InconsistentEqualsHashCodeFix that = (InconsistentEqualsHashCodeFix) obj;
return this.i == that.i;
}
} | 426 | 19.333333 | 75 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/CompareIdenticalValues.java | class Customer {
...
public boolean equals(Object o) {
if (o == null) return false;
if (Customer.class != o.getClass()) return false;
Customer other = (Customer)o;
if (!name.equals(o.name)) return false;
if (id != id) return false; // Comparison of identical values
return true;
}
}
class Customer {
...
public boolean equals(Object o) {
if (o == null) return false;
if (Customer.class != o.getClass()) return false;
Customer other = (Customer)o;
if (!name.equals(o.name)) return false;
if (id != o.id) return false; // Comparison corrected
return true;
}
} | 590 | 24.695652 | 64 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/IncomparableEquals.java | String[] anArray = new String[]{"a","b","c"}
String valueToFind = "b";
for(int i=0; i<anArray.length; i++){
if(anArray.equals(valueToFind){ // anArray[i].equals(valueToFind) was intended
return "Found value at index " + i;
}
}
return "Value not found"; | 265 | 25.6 | 83 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/HashedButNoHashBad.java | class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point q = (Point)o;
return x == q.x && y == q.y;
}
} | 260 | 16.4 | 45 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/EqualsUsesInstanceOf.java | class BadPoint {
int x;
int y;
BadPoint(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if(!(o instanceof BadPoint))
return false;
BadPoint q = (BadPoint)o;
return x == q.x && y == q.y;
}
}
class BadPointExt extends BadPoint {
String s;
BadPointExt(int x, int y, String s) {
super(x, y);
this.s = s;
}
// violates symmetry of equals contract
public boolean equals(Object o) {
if(!(o instanceof BadPointExt)) return false;
BadPointExt q = (BadPointExt)o;
return super.equals(o) && (q.s==null ? s==null : q.s.equals(s));
}
}
class GoodPoint {
int x;
int y;
GoodPoint(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (o != null && getClass() == o.getClass()) {
GoodPoint q = (GoodPoint)o;
return x == q.x && y == q.y;
}
return false;
}
}
class GoodPointExt extends GoodPoint {
String s;
GoodPointExt(int x, int y, String s) {
super(x, y);
this.s = s;
}
public boolean equals(Object o) {
if (o != null && getClass() == o.getClass()) {
GoodPointExt q = (GoodPointExt)o;
return super.equals(o) && (q.s==null ? s==null : q.s.equals(s));
}
return false;
}
}
BadPoint p = new BadPoint(1, 2);
BadPointExt q = new BadPointExt(1, 2, "info");
| 1,512 | 20.309859 | 76 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/NoComparisonOnFloatsGood.java | class NoComparisonOnFloats
{
public static void main(String[] args)
{
final double EPSILON = 0.001;
System.out.println(Math.abs((0.1 + 0.2) - 0.3) < EPSILON);
}
} | 190 | 22.875 | 66 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/InconsistentCompareToGood.java | public class InconsistentCompareToFix implements Comparable<InconsistentCompareToFix> {
private int i = 0;
public InconsistentCompareToFix(int i) {
this.i = i;
}
public int compareTo(InconsistentCompareToFix rhs) {
return i - rhs.i;
}
public boolean equals(InconsistentCompareToFix rhs) {
return i == rhs.i;
}
} | 327 | 22.428571 | 87 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/CovariantEquals.java | class BadPoint {
int x;
int y;
BadPoint(int x, int y) {
this.x = x;
this.y = y;
}
// overloaded equals method -- should be avoided
public boolean equals(BadPoint q) {
return x == q.x && y == q.y;
}
}
BadPoint p = new BadPoint(1, 2);
Object q = new BadPoint(1, 2);
boolean badEquals = p.equals(q); // evaluates to false
class GoodPoint {
int x;
int y;
GoodPoint(int x, int y) {
this.x = x;
this.y = y;
}
// correctly overrides Object.equals(Object)
public boolean equals(Object obj) {
if (obj != null && getClass() == obj.getClass()) {
GoodPoint q = (GoodPoint)obj;
return x == q.x && y == q.y;
}
return false;
}
}
GoodPoint r = new GoodPoint(1, 2);
Object s = new GoodPoint(1, 2);
boolean goodEquals = r.equals(s); // evaluates to true
| 887 | 20.142857 | 58 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/RefEqBoxedBad.java | boolean refEq(Integer i, Integer j) {
return i == j;
} | 55 | 17.666667 | 37 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/StringComparison.java | void printHeader(String headerStyle) {
if (headerStyle == null || headerStyle == "") {
// No header
return;
}
// ... print the header
}
| 143 | 17 | 48 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/NoComparisonOnFloats.java | class NoComparisonOnFloats
{
public static void main(String[] args)
{
System.out.println((0.1 + 0.2) == 0.3);
}
} | 133 | 18.142857 | 47 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/HashedButNoHash.java | class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point q = (Point)o;
return x == q.x && y == q.y;
}
// Implement hashCode so that equivalent points (with the same values of x and y) have the
// same hash code
public int hashCode() {
int hash = 7;
hash = 31*hash + x;
hash = 31*hash + y;
return hash;
}
}
| 521 | 19.88 | 94 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/BitwiseSignCheck.java | int x = -1;
int n = 31;
boolean bad = (x & (1<<n)) > 0; | 56 | 13.25 | 31 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/CovariantCompareTo.java | public class CovariantCompareTo {
static class Super implements Comparable<Super> {
public int compareTo(Super rhs) {
return -1;
}
}
static class Sub extends Super {
public int compareTo(Sub rhs) { // Definition of compareTo uses a different parameter type
return 0;
}
}
public static void main(String[] args) {
Super a = new Sub();
Super b = new Sub();
System.out.println(a.compareTo(b));
}
} | 424 | 21.368421 | 93 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/NoAssignInBooleanExprs.java | public class ScreenView
{
private static int BUF_SIZE = 1024;
private Screen screen;
public void notify(Change change) {
boolean restart = false;
if (change.equals(Change.MOVE)
|| v.equals(Change.REPAINT)
|| (restart = v.equals(Change.RESTART)) // AVOID: Confusing assignment in condition
|| v.equals(Change.FLIP))
{
if (restart)
WindowManager.restart();
screen.update();
}
}
// ...
public void readConfiguration(InputStream config) {
byte[] buf = new byte[BUF_SIZE];
int read;
while ((read = config.read(buf)) > 0) { // OK: Assignment whose result is compared to
// another value
// ...
}
// ...
}
}
| 843 | 26.225806 | 96 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/BitwiseSignCheckGood.java | int x = -1;
int n = 31;
boolean good = (x & (1<<n)) != 0; | 58 | 13.75 | 33 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/UselessComparisonTest.java | void method(int x) {
while(x >= 0) {
// do stuff
x--;
}
if (x < 0) { // BAD: always true
// do more stuff
}
} | 119 | 12.333333 | 33 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/InconsistentEqualsHashCode.java | public class InconsistentEqualsHashCode {
private int i = 0;
public InconsistentEqualsHashCode(int i) {
this.i = i;
}
public int hashCode() {
return i;
}
} | 165 | 15.6 | 43 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/InconsistentCompareTo.java | public class InconsistentCompareTo implements Comparable<InconsistentCompareTo> {
private int i = 0;
public InconsistentCompareTo(int i) {
this.i = i;
}
public int compareTo(InconsistentCompareTo rhs) {
return i - rhs.i;
}
} | 235 | 22.6 | 81 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/StringComparisonGood.java | void printHeader(String headerStyle) {
if (headerStyle == null || headerStyle.equals("")) {
// No header
return;
}
// ... print the header
}
| 148 | 17.625 | 53 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/MissingInstanceofInEquals.java | class A {
// ...
public final boolean equals(Object obj) {
if (!(obj instanceof A)) {
return false;
}
A a = (A)obj;
// ...further checks...
}
// ...
} | 207 | 17.909091 | 45 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/DefineEqualsWhenAddingFields.java | public class DefineEqualsWhenAddingFields {
static class Square {
protected int width = 0;
public Square(int width) {
this.width = width;
}
@Override
public boolean equals(Object thatO) { // This method works only for squares.
if(thatO != null && getClass() == thatO.getClass() ) {
Square that = (Square)thatO;
return width == that.width;
}
return false;
}
}
static class Rectangle extends Square {
private int height = 0;
public Rectangle(int width, int height) {
super(width);
this.height = height;
}
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle(4, 3);
Rectangle r2 = new Rectangle(4, 5);
System.out.println(r1.equals(r2)); // Outputs 'true'
}
}
| 903 | 28.16129 | 85 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/EqualsArray.java | public void arrayExample(){
String[] array1 = new String[]{"a", "b", "c"};
String[] array2 = new String[]{"a", "b", "c"};
// Reference equality tested: prints 'false'
System.out.println(array1.equals(array2));
// Equality of array elements tested: prints 'true'
System.out.println(Arrays.equals(array1, array2));
} | 344 | 33.5 | 55 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Comparison/RefEqBoxed.java | boolean realEq(Integer i, Integer j) {
return i.equals(j);
} | 61 | 19.666667 | 38 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Termination/ConstantLoopConditionBad.java | Object getField(Object obj, String name) throws NoSuchFieldError {
Class clazz = obj.getClass();
while (clazz != null) {
for (Field f : clazz.getDeclaredFields()) {
if (f.getName().equals(name)) {
f.setAccessible(true);
return f.get(obj);
}
}
}
throw new NoSuchFieldError(name);
}
| 325 | 24.076923 | 66 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Termination/SpinOnField.java | class Spin {
public boolean done = false;
public void spin() {
while(!done){
}
}
}
class Spin { // optimized
public boolean done = false;
public void spin() {
boolean cond = done;
while(!cond){
}
}
}
| 267 | 13.105263 | 32 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Termination/ConstantLoopConditionGood.java | Object getField(Object obj, String name) throws NoSuchFieldError {
Class clazz = obj.getClass();
if (clazz != null) {
for (Field f : clazz.getDeclaredFields()) {
if (f.getName().equals(name)) {
f.setAccessible(true);
return f.get(obj);
}
}
}
throw new NoSuchFieldError(name);
}
| 322 | 23.846154 | 66 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-190/ArithmeticTainted.java | class Test {
public static void main(String[] args) {
{
int data;
BufferedReader readerBuffered = new BufferedReader(
new InputStreamReader(System.in, "UTF-8"));
String stringNumber = readerBuffered.readLine();
if (stringNumber != null) {
data = Integer.parseInt(stringNumber.trim());
} else {
data = 0;
}
// BAD: may overflow if input data is very large, for example
// 'Integer.MAX_VALUE'
int scaled = data * 10;
//...
// GOOD: use a guard to ensure no overflows occur
int scaled2;
if (data < Integer.MAX_VALUE / 10)
scaled2 = data * 10;
else
scaled2 = Integer.MAX_VALUE;
}
}
} | 655 | 21.62069 | 64 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-190/ArithmeticWithExtremeValues.java | class Test {
public static void main(String[] args) {
{
long i = Long.MAX_VALUE;
// BAD: overflow
long j = i + 1;
}
{
int i = Integer.MAX_VALUE;
// GOOD: no overflow
long j = (long)i + 1;
}
}
} | 225 | 14.066667 | 42 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-190/ArithmeticUncontrolled.java | class Test {
public static void main(String[] args) {
{
int data = (new java.security.SecureRandom()).nextInt();
// BAD: may overflow if data is large
int scaled = data * 10;
// ...
// GOOD: use a guard to ensure no overflows occur
int scaled2;
if (data < Integer.MAX_VALUE/10)
scaled2 = data * 10;
else
scaled2 = Integer.MAX_VALUE;
}
}
} | 380 | 19.052632 | 59 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-190/ComparisonWithWiderType.java | class Test {
public static void main(String[] args) {
{
int BIGNUM = Integer.MAX_VALUE;
long MAXGET = Short.MAX_VALUE + 1;
char[] buf = new char[BIGNUM];
short bytesReceived = 0;
// BAD: 'bytesReceived' is compared with a value of wider type.
// 'bytesReceived' overflows before reaching MAXGET,
// causing an infinite loop.
while (bytesReceived < MAXGET) {
bytesReceived += getFromInput(buf, bytesReceived);
}
}
{
long bytesReceived2 = 0;
// GOOD: 'bytesReceived2' has a type at least as wide as MAXGET.
while (bytesReceived2 < MAXGET) {
bytesReceived2 += getFromInput(buf, bytesReceived2);
}
}
}
public static int getFromInput(char[] buf, short pos) {
// write to buf
// ...
return 1;
}
} | 781 | 20.722222 | 67 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-676/PotentiallyDangerousFunction.java | private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
| 311 | 17.352941 | 47 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-681/NumericCastTainted.java | class Test {
public static void main(String[] args) throws IOException {
{
long data;
BufferedReader readerBuffered = new BufferedReader(
new InputStreamReader(System.in, "UTF-8"));
String stringNumber = readerBuffered.readLine();
if (stringNumber != null) {
data = Long.parseLong(stringNumber.trim());
} else {
data = 0;
}
// AVOID: potential truncation if input data is very large,
// for example 'Long.MAX_VALUE'
int scaled = (int)data;
//...
// GOOD: use a guard to ensure no truncation occurs
int scaled2;
if (data > Integer.MIN_VALUE && data < Integer.MAX_VALUE)
scaled2 = (int)data;
else
throw new IllegalArgumentException("Invalid input");
}
}
} | 726 | 24.068966 | 62 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-327/BrokenCryptoAlgorithm.java | // BAD: DES is a weak algorithm
Cipher des = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
// ...
// GOOD: AES is a strong algorithm
Cipher des = Cipher.getInstance("AES");
// ... | 274 | 21.916667 | 59 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-319/HttpsUrls.java | public static void main(String[] args) {
{
try {
String protocol = "http://";
URL u = new URL(protocol + "www.secret.example.org/");
// BAD: This causes a 'ClassCastException' at runtime, because the
// HTTP URL cannot be used to make an 'HttpsURLConnection',
// which enforces SSL.
HttpsURLConnection hu = (HttpsURLConnection) u.openConnection();
hu.setRequestMethod("PUT");
hu.connect();
OutputStream os = hu.getOutputStream();
hu.disconnect();
}
catch (IOException e) {
// fail
}
}
{
try {
String protocol = "https://";
URL u = new URL(protocol + "www.secret.example.org/");
// GOOD: Opening a connection to a URL using HTTPS enforces SSL.
HttpsURLConnection hu = (HttpsURLConnection) u.openConnection();
hu.setRequestMethod("PUT");
hu.connect();
OutputStream os = hu.getOutputStream();
hu.disconnect();
}
catch (IOException e) {
// fail
}
}
} | 929 | 25.571429 | 69 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-319/UseSSL.java | public static void main(String[] args) {
{
try {
URL u = new URL("http://www.secret.example.org/");
HttpURLConnection httpcon = (HttpURLConnection) u.openConnection();
httpcon.setRequestMethod("PUT");
httpcon.connect();
// BAD: output stream from non-HTTPS connection
OutputStream os = httpcon.getOutputStream();
httpcon.disconnect();
}
catch (IOException e) {
// fail
}
}
{
try {
URL u = new URL("https://www.secret.example.org/");
HttpsURLConnection httpscon = (HttpsURLConnection) u.openConnection();
httpscon.setRequestMethod("PUT");
httpscon.connect();
// GOOD: output stream from HTTPS connection
OutputStream os = httpscon.getOutputStream();
httpscon.disconnect();
}
catch (IOException e) {
// fail
}
}
} | 781 | 24.225806 | 73 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-319/UseSSLSocketFactories.java | public static void main(String[] args) {
{
try {
TestImpl obj = new TestImpl();
// BAD: default socket factory is used
Test stub = (Test) UnicastRemoteObject.exportObject(obj, 0);
} catch (Exception e) {
// fail
}
}
{
try {
TestImpl obj = new TestImpl();
SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
// GOOD: SSL factories are used
Test stub = (Test) UnicastRemoteObject.exportObject(obj, 0, csf, ssf);
} catch (Exception e) {
// fail
}
}
}
| 713 | 26.461538 | 82 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-079/XSS.java | public class XSS extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 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.");
}
}
| 368 | 40 | 79 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-312/CleartextStorage.java | public static void main(String[] args) {
{
String data;
PasswordAuthentication credentials =
new PasswordAuthentication("user", "BP@ssw0rd".toCharArray());
data = credentials.getUserName() + ":" + new String(credentials.getPassword());
// BAD: store data in a cookie in cleartext form
response.addCookie(new Cookie("auth", data));
}
{
String data;
PasswordAuthentication credentials =
new PasswordAuthentication("user", "GP@ssw0rd".toCharArray());
String salt = "ThisIsMySalt";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.reset();
String credentialsToHash =
credentials.getUserName() + ":" + credentials.getPassword();
byte[] hashedCredsAsBytes =
messageDigest.digest((salt+credentialsToHash).getBytes("UTF-8"));
data = bytesToString(hashedCredsAsBytes);
// GOOD: store data in a cookie in encrypted form
response.addCookie(new Cookie("auth", data));
}
}
| 950 | 31.793103 | 81 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-022/TaintedPath.java | public void sendUserFile(Socket sock, String user) {
BufferedReader filenameReader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), "UTF-8"));
String filename = filenameReader.readLine();
// BAD: read from a file using a path controlled by the user
BufferedReader fileReader = new BufferedReader(
new FileReader("/home/" + user + "/" + filename));
String fileLine = fileReader.readLine();
while(fileLine != null) {
sock.getOutputStream().write(fileLine.getBytes());
fileLine = fileReader.readLine();
}
}
public void sendUserFileFixed(Socket sock, String user) {
// ...
// GOOD: remove all dots and directory delimiters from the filename before using
String filename = filenameReader.readLine().replaceAll("\.", "").replaceAll("/", "");
BufferedReader fileReader = new BufferedReader(
new FileReader("/home/" + user + "/" + filename));
// ...
} | 890 | 36.125 | 86 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-022/ZipSlipBad.java | void writeZipEntry(ZipEntry entry, File destinationDir) {
File file = new File(destinationDir, entry.getName());
FileOutputStream fos = new FileOutputStream(file); // BAD
// ... write entry to fos ...
}
| 215 | 35 | 61 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-022/ZipSlipGood.java | void writeZipEntry(ZipEntry entry, File destinationDir) {
File file = new File(destinationDir, entry.getName());
if (!file.toPath().normalize().startsWith(destinationDir.toPath()))
throw new Exception("Bad zip entry");
FileOutputStream fos = new FileOutputStream(file); // OK
// ... write entry to fos ...
}
| 332 | 40.625 | 71 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-835/InfiniteLoopBad.java | for (int i=0; i<10; i++) {
for (int j=0; i<10; j++) {
// do stuff
if (shouldBreak()) break;
}
}
| 120 | 16.285714 | 33 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-835/InfiniteLoopGood.java | for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
// do stuff
if (shouldBreak()) break;
}
}
| 120 | 16.285714 | 33 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-335/PredictableSeed.java | SecureRandom prng = new SecureRandom();
int randomData = 0;
// BAD: Using a constant value as a seed for a random number generator means all numbers it generates are predictable.
prng.setSeed(12345L);
randomData = prng.next(32);
// BAD: System.currentTimeMillis() returns the system time which is predictable.
prng.setSeed(System.currentTimeMillis());
randomData = prng.next(32);
// GOOD: SecureRandom implementations seed themselves securely by default.
prng = new SecureRandom();
randomData = prng.next(32);
| 513 | 33.266667 | 118 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-833/LockOrderInconsistency.java | class Test {
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;
}
}
| 849 | 24 | 60 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-611/XXEGood.java | public void disableDTDParse(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
}
| 324 | 45.428571 | 83 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-611/XXEBad.java | public void parse(Socket sock) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.parse(sock.getInputStream()); //unsafe
}
| 232 | 37.833333 | 72 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-134/ExternallyControlledFormatString.java | public class ResponseSplitting extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Calendar expirationDate = new GregorianCalendar(2017, GregorianCalendar.SEPTEMBER, 1);
// User provided value
String cardSecurityCode = request.getParameter("cardSecurityCode");
if (notValid(cardSecurityCode)) {
/*
* BAD: user provided value is included in the format string.
* A malicious user could provide an extra format specifier, which causes an
* exception to be thrown. Or they could provide a %1$tm or %1$te format specifier to
* access the month or day of the expiration date.
*/
System.out.format(cardSecurityCode +
" is not the right value. Hint: the card expires in %1$ty.",
expirationDate);
// GOOD: %s is used to include the user-provided cardSecurityCode in the output
System.out.format("%s is not the right value. Hint: the card expires in %2$ty.",
cardSecurityCode,
expirationDate);
}
}
} | 1,180 | 42.740741 | 91 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-807/TaintedPermissionsCheck.java | public static void main(String[] args) {
String whatDoTheyWantToDo = args[0];
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();
} | 358 | 28.916667 | 65 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-807/ConditionalBypass.java | public boolean doLogin(String user, String password) {
Cookie adminCookie = getCookies()[0];
// BAD: login is executed only if the value of 'adminCookie' is 'false',
// but 'adminCookie' is controlled by the user
if(adminCookie.getValue()=="false")
return login(user, password);
return true;
}
public boolean doLogin(String user, String password) {
Cookie adminCookie = getCookies()[0];
// GOOD: use server-side information based on the credentials to decide
// whether user has privileges
boolean isAdmin = queryDbForAdminStatus(user, password);
if(!isAdmin)
return login(user, password);
return true;
} | 628 | 27.590909 | 74 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-601/UrlRedirect.java | public class UrlRedirect extends HttpServlet {
private static final String VALID_REDIRECT = "http://cwe.mitre.org/data/definitions/601.html";
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);
}
}
}
| 596 | 38.8 | 95 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-020/ExternalAPISinkExample.java | public class XSS extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 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.");
}
}
| 368 | 40 | 79 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-020/ExternalAPITaintStepExample.java | public class SQLInjection extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM user WHERE user_id='");
sqlQueryBuilder.append(request.getParameter("user_id"));
sqlQueryBuilder.append("'");
// ...
}
}
| 393 | 29.307692 | 79 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-421/SocketAuthRace.java | 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 connection
connection1.getOutputStream().write(secretData);
}
}
public void doConnect(int desiredPort, String username) {
ServerSocket listenSocket = new ServerSocket(desiredPort);
Socket connection2 = listenSocket.accept();
// GOOD: authentication happens over the socket
if (doAuthenticate(connection2, username)) {
connection2.getOutputStream().write(secretData);
}
} | 625 | 31.947368 | 59 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-129/ImproperValidationOfArrayConstructionCodeSpecified.java | public class PossibleArrayIndexOutOfBounds {
public static void main(String[] args) {
int numberOfItems = new Random().nextInt(10);
if (numberOfItems >= 0) {
/*
* BAD numberOfItems may be zero, which would cause the array indexing operation to
* throw an ArrayIndexOutOfBoundsException
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
if (numberOfItems > 0) {
/*
* GOOD numberOfItems must be greater than zero, so the indexing succeeds.
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
}
} | 657 | 27.608696 | 91 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-129/ImproperValidationOfArrayIndexCodeSpecified.java | public class ImproperValidationOfArrayIndex extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Search for products in productDescriptions that match the search term
String searchTerm = request.getParameter("productSearchTerm");
int foundProductID = -1;
for (int i = 0; i < productDescriptions.length; i++) {
if (productDescriptions[i].contains(searchTerm)) {
// Found matching product
foundProductID = i;
break;
}
}
// BAD We may not have found a product in which case the index would be -1
response.getWriter().write(productDescriptions[foundProductID]);
if (foundProductID >= 0) {
// GOOD We have checked we found a product first
response.getWriter().write(productDescriptions[foundProductID]);
} else {
response.getWriter().write("No product found");
}
}
} | 954 | 35.730769 | 80 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-129/ImproperValidationOfArrayConstruction.java | public class ImproperValidationOfArrayIndex extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// User provided value
int numberOfItems = Integer.parseInt(request.getParameter("numberOfItems").trim());
if (numberOfItems >= 0) {
/*
* BAD numberOfItems may be zero, which would cause the array indexing operation to
* throw an ArrayIndexOutOfBoundsException
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
if (numberOfItems > 0) {
/*
* GOOD numberOfItems must be greater than zero, so the indexing succeeds.
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
} catch (NumberFormatException e) { }
}
} | 877 | 30.357143 | 91 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-129/ImproperValidationOfArrayIndex.java | public class ImproperValidationOfArrayIndex extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] productDescriptions = new String[] { "Chocolate bar", "Fizzy drink" };
// User provided value
String productID = request.getParameter("productID");
try {
int productID = Integer.parseInt(userProperty.trim());
/*
* BAD Array is accessed without checking if the user provided value is out of
* bounds.
*/
String productDescription = productDescriptions[productID];
if (productID >= 0 && productID < productDescriptions.length) {
// GOOD We have checked that the array index is valid first
productDescription = productDescriptions[productID];
} else {
productDescription = "No product for that ID";
}
response.getWriter().write(productDescription);
} catch (NumberFormatException e) { }
}
} | 1,025 | 34.37931 | 86 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-367/TOCTOURace.java | class Resource {
public synchronized boolean isReady() { ... }
public synchronized void setReady(boolean ready) { ... }
public synchronized void act() {
if (!isReady())
throw new IllegalStateException();
...
}
}
public synchronized void bad(Resource r) {
if (r.isReady()) {
// r might no longer be ready, another thread might
// have called setReady(false)
r.act();
}
}
public synchronized void good(Resource r) {
synchronized(r) {
if (r.isReady()) {
r.act();
}
}
} | 500 | 17.555556 | 57 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-614/InsecureCookie.java | 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);
}
} | 359 | 21.5 | 83 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-352/SpringCSRFProtection.java | import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf(csrf ->
// BAD - CSRF protection shouldn't be disabled
csrf.disable()
);
}
}
| 640 | 34.611111 | 101 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-090/LdapInjectionApache.java | import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import static org.apache.directory.ldap.client.api.search.FilterBuilder.equal;
public void ldapQueryGood(HttpServletRequest request, LdapConnection c) {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// GOOD: Organization name is encoded before being used in DN
Dn safeDn = new Dn(new Rdn("OU", "People"), new Rdn("O", organizationName));
// GOOD: User input is encoded before being used in search filter
String safeFilter = equal("username", username);
SearchRequest searchRequest = new SearchRequestImpl();
searchRequest.setBase(safeDn);
searchRequest.setFilter(safeFilter);
c.search(searchRequest);
} | 1,004 | 44.681818 | 78 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-090/LdapInjectionUnboundId.java | import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.DN;
import com.unboundid.ldap.sdk.RDN;
import com.unboundid.ldap.sdk.Filter;
public void ldapQueryGood(HttpServletRequest request, LDAPConnection c) {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// GOOD: Organization name is encoded before being used in DN
DN safeDn = new DN(new RDN("OU", "People"), new RDN("O", organizationName));
// GOOD: User input is encoded before being used in search filter
Filter safeFilter = Filter.createEqualityFilter("username", username);
c.search(safeDn.toString(), SearchScope.ONE, safeFilter);
} | 703 | 40.411765 | 78 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-090/LdapInjectionJndi.java | import javax.naming.directory.DirContext;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.reference.DefaultEncoder;
public void ldapQueryBad(HttpServletRequest request, DirContext ctx) throws NamingException {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// BAD: User input used in DN (Distinguished Name) without encoding
String dn = "OU=People,O=" + organizationName;
// BAD: User input used in search filter without encoding
String filter = "username=" + userName;
ctx.search(dn, filter, new SearchControls());
}
public void ldapQueryGood(HttpServletRequest request, DirContext ctx) throws NamingException {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// ESAPI encoder
Encoder encoder = DefaultEncoder.getInstance();
// GOOD: Organization name is encoded before being used in DN
String safeOrganizationName = encoder.encodeForDN(organizationName);
String safeDn = "OU=People,O=" + safeOrganizationName;
// GOOD: User input is encoded before being used in search filter
String safeUsername = encoder.encodeForLDAP(username);
String safeFilter = "username=" + safeUsername;
ctx.search(safeDn, safeFilter, new SearchControls());
} | 1,337 | 38.352941 | 94 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-090/LdapInjectionSpring.java | import static org.springframework.ldap.query.LdapQueryBuilder.query;
import org.springframework.ldap.support.LdapNameBuilder;
public void ldapQueryGood(@RequestParam String organizationName, @RequestParam String username) {
// GOOD: Organization name is encoded before being used in DN
String safeDn = LdapNameBuilder.newInstance()
.add("O", organizationName)
.add("OU=People")
.build().toString();
// GOOD: User input is encoded before being used in search filter
LdapQuery query = query()
.base(safeDn)
.where("username").is(username);
ldapTemplate.search(query, new AttributeCheckAttributesMapper());
} | 638 | 36.588235 | 97 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-113/NettyResponseSplitting.java | import io.netty.handler.codec.http.DefaultHttpHeaders;
public class ResponseSplitting {
// BAD: Disables the internal response splitting verification
private final DefaultHttpHeaders badHeaders = new DefaultHttpHeaders(false);
// GOOD: Verifies headers passed don't contain CRLF characters
private final DefaultHttpHeaders goodHeaders = new DefaultHttpHeaders();
// BAD: Disables the internal response splitting verification
private final DefaultHttpResponse badResponse = new DefaultHttpResponse(version, httpResponseStatus, false);
// GOOD: Verifies headers passed don't contain CRLF characters
private final DefaultHttpResponse goodResponse = new DefaultHttpResponse(version, httpResponseStatus);
}
| 738 | 45.1875 | 112 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-113/ResponseSplitting.java | public class ResponseSplitting extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// BAD: setting a cookie with an unvalidated parameter
Cookie cookie = new Cookie("name", request.getParameter("name"));
response.addCookie(cookie);
// GOOD: remove special characters before putting them in the header
String name = removeSpecial(request.getParameter("name"));
Cookie cookie2 = new Cookie("name", name);
response.addCookie(cookie2);
}
private static String removeSpecial(String str) {
return str.replaceAll("[^a-zA-Z ]", "");
}
}
| 640 | 34.611111 | 79 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-502/UnsafeDeserializationGood.java | public MyObject deserialize(Socket sock) {
try(DataInputStream in = new DataInputStream(sock.getInputStream())) {
return new MyObject(in.readInt());
}
}
| 161 | 26 | 72 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-502/UnsafeDeserializationBad.java | public MyObject {
public int field;
MyObject(int field) {
this.field = field;
}
}
public MyObject deserialize(Socket sock) {
try(ObjectInputStream in = new ObjectInputStream(sock.getInputStream())) {
return (MyObject)in.readObject(); // unsafe
}
}
| 267 | 19.615385 | 76 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-089/SqlTainted.java | {
// BAD: the category might have SQL special characters in it
String category = System.getenv("ITEM_CATEGORY");
Statement statement = connection.createStatement();
String query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='"
+ category + "' ORDER BY PRICE";
ResultSet results = statement.executeQuery(query1);
}
{
// GOOD: use a prepared query
String category = System.getenv("ITEM_CATEGORY");
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();
} | 693 | 39.823529 | 90 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-089/SqlTaintedPersistence.java | {
// BAD: the category might have Java Persistence Query Language special characters in it
String category = System.getenv("ITEM_CATEGORY");
Statement statement = connection.createStatement();
String query1 = "SELECT p FROM Product p WHERE p.category LIKE '"
+ category + "' ORDER BY p.price";
Query q = entityManager.createQuery(query1);
}
{
// GOOD: use a named parameter and set its value
String category = System.getenv("ITEM_CATEGORY");
String query2 = "SELECT p FROM Product p WHERE p.category LIKE :category ORDER BY p.price"
Query q = entityManager.createQuery(query2);
q.setParameter("category", category);
}
{
// GOOD: use a positional parameter and set its value
String category = System.getenv("ITEM_CATEGORY");
String query3 = "SELECT p FROM Product p WHERE p.category LIKE ?1 ORDER BY p.price"
Query q = entityManager.createQuery(query3);
q.setParameter(1, category);
}
{
// GOOD: use a named query with a named parameter and set its value
@NamedQuery(
name="lookupByCategory",
query="SELECT p FROM Product p WHERE p.category LIKE :category ORDER BY p.price")
private static class NQ {}
...
String category = System.getenv("ITEM_CATEGORY");
Query namedQuery1 = entityManager.createNamedQuery("lookupByCategory");
namedQuery1.setParameter("category", category);
}
{
// GOOD: use a named query with a positional parameter and set its value
@NamedQuery(
name="lookupByCategory",
query="SELECT p FROM Product p WHERE p.category LIKE ?1 ORDER BY p.price")
private static class NQ {}
...
String category = System.getenv("ITEM_CATEGORY");
Query namedQuery2 = entityManager.createNamedQuery("lookupByCategory");
namedQuery2.setParameter(1, category);
} | 1,834 | 37.229167 | 94 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-089/SqlUnescaped.java | {
// BAD: the category might have SQL special characters in it
String category = getCategory();
Statement statement = connection.createStatement();
String query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='"
+ category + "' ORDER BY PRICE";
ResultSet results = statement.executeQuery(query1);
}
{
// GOOD: use a prepared query
String category = getCategory();
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();
} | 659 | 37.823529 | 90 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-798/HardcodedAWSCredentials.java | import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
public class HardcodedAWSCredentials {
public static void main(String[] args) {
//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"); //sensitive call
}
}
| 471 | 41.909091 | 142 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-798/HardcodedCredentialsApiCall.java | private static final String p = "123456"; // hard-coded credential
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost/test";
String u = "admin"; // hard-coded credential
getConn(url, u, p);
}
public static void getConn(String url, String v, String q) throws SQLException {
DriverManager.getConnection(url, v, q); // sensitive call
}
| 399 | 29.769231 | 80 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-209/StackTraceExposure.java | protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
doSomeWork();
} catch (NullPointerException ex) {
// BAD: printing a stack trace back to the response
ex.printStackTrace(response.getWriter());
return;
}
try {
doSomeWork();
} catch (NullPointerException ex) {
// GOOD: log the stack trace, and send back a non-revealing response
log("Exception occurred", ex);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Exception occurred");
return;
}
}
| 529 | 24.238095 | 80 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-078/ExecRelative.java | class Test {
public static void main(String[] args) {
// BAD: relative path
Runtime.getRuntime().exec("make");
// GOOD: absolute path
Runtime.getRuntime().exec("/usr/bin/make");
// GOOD: build an absolute path from known values
Runtime.getRuntime().exec(Paths.MAKE_PREFIX + "/bin/make");
}
} | 357 | 28.833333 | 67 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-078/ExecTainted.java | class Test {
public static void main(String[] args) {
String script = System.getenv("SCRIPTNAME");
if (script != null) {
// BAD: The script to be executed is controlled by the user.
Runtime.getRuntime().exec(script);
}
}
} | 278 | 30 | 72 | java |
codeql | codeql-master/java/ql/src/Security/CWE/CWE-078/ExecUnescaped.java | class Test {
public static void main(String[] args) {
// BAD: user input might include special characters such as ampersands
{
String latlonCoords = args[1];
Runtime rt = Runtime.getRuntime();
Process exec = rt.exec("cmd.exe /C latlon2utm.exe " + latlonCoords);
}
// GOOD: use an array of arguments instead of executing a string
{
String latlonCoords = args[1];
Runtime rt = Runtime.getRuntime();
Process exec = rt.exec(new String[] {
"c:\\path\to\latlon2utm.exe",
latlonCoords });
}
}
}
| 657 | 31.9 | 80 | java |
codeql | codeql-master/java/ql/src/experimental/CWE-939/IncorrectURLVerification.java | public boolean shouldOverrideUrlLoading(WebView view, String url) {
{
Uri uri = Uri.parse(url);
// BAD: partial domain match, which allows an attacker to register a domain like myexample.com to circumvent the verification
if (uri.getHost() != null && uri.getHost().endsWith("example.com")) {
return false;
}
}
{
Uri uri = Uri.parse(url);
// GOOD: full domain match
if (uri.getHost() != null && uri.getHost().endsWith(".example.com")) {
return false;
}
}
}
| 561 | 30.222222 | 133 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-327/SaferTLSVersion.java | public SSLSocket connect(String host, int port)
throws NoSuchAlgorithmException, IOException {
SSLContext context = SSLContext.getInstance("TLSv1.3");
return (SSLSocket) context.getSocketFactory().createSocket(host, port);
} | 245 | 40 | 75 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-327/UnsafeTLSVersion.java | public SSLSocket connect(String host, int port)
throws NoSuchAlgorithmException, IOException {
SSLContext context = SSLContext.getInstance("SSLv3");
return (SSLSocket) context.getSocketFactory().createSocket(host, port);
} | 243 | 39.666667 | 75 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-917/OgnlInjection.java | import ognl.Ognl;
import ognl.OgnlException;
public void evaluate(HttpServletRequest request, Object root) throws OgnlException {
String expression = request.getParameter("expression");
// BAD: User provided expression is evaluated
Ognl.getValue(expression, root);
// GOOD: The name is validated and expression is evaluated in sandbox
System.setProperty("ognl.security.manager", ""); // Or add -Dognl.security.manager to JVM args
if (isValid(expression)) {
Ognl.getValue(expression, root);
} else {
// Reject the request
}
} | 554 | 31.647059 | 96 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-522/InsecureBasicAuth.java | public class InsecureBasicAuth {
/**
* Test basic authentication with Apache HTTP request.
*/
public void testApacheHttpRequest(String username, String password) {
{
// BAD: basic authentication over HTTP
String url = "http://www.example.com/rest/getuser.do?uid=abcdx";
}
{
// GOOD: basic authentication over HTTPS
String url = "https://www.example.com/rest/getuser.do?uid=abcdx";
}
HttpPost post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Java HTTP URL connection.
*/
public void testHttpUrlConnection(String username, String password) {
{
// BAD: basic authentication over HTTP
String urlStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
}
{
// GOOD: basic authentication over HTTPS
String urlStr = "https://www.example.com/rest/getuser.do?uid=abcdx";
}
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
}
| 1,592 | 30.86 | 87 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-074/JndiInjection.java | import javax.naming.Context;
import javax.naming.InitialContext;
public void jndiLookup(HttpServletRequest request) throws NamingException {
String name = request.getParameter("name");
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://trusted-server:1099");
InitialContext ctx = new InitialContext(env);
// BAD: User input used in lookup
ctx.lookup(name);
// GOOD: The name is validated before being used in lookup
if (isValid(name)) {
ctx.lookup(name);
} else {
// Reject the request
}
} | 668 | 30.857143 | 95 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-094/UnsafeMvelExpressionEvaluation.java | public void evaluate(Socket socket) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
String expression = reader.readLine();
MVEL.eval(expression);
}
} | 241 | 29.25 | 56 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-094/UnsafeSpelExpressionEvaluation.java | public Object evaluate(Socket socket) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
String string = reader.readLine();
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(string);
return expression.getValue();
}
} | 364 | 35.5 | 59 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-094/SaferSpelExpressionEvaluation.java | public Object evaluate(Socket socket) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
String string = reader.readLine();
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(string);
SimpleEvaluationContext context
= SimpleEvaluationContext.forReadWriteDataBinding().build();
return expression.getValue(context);
}
} | 477 | 38.833333 | 68 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-094/ScriptEngine.java | // Bad: ScriptEngine allows arbitrary code injection
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension("js");
Object result = scriptEngine.eval(code); | 238 | 58.75 | 75 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-036/OpenStream.java | public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// BAD: a URL from a remote source is opened with URL#openStream()
URL url = new URL(request.getParameter("url"));
InputStream inputStream = new URL(url).openStream();
}
}
| 373 | 40.555556 | 82 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-299/DefaultRevocationChecking.java | public void validate(KeyStore cacerts, CertPath chain) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
validator.validate(chain, params);
} | 244 | 48 | 73 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-299/NoRevocationChecking.java | public void validateUnsafe(KeyStore cacerts, CertPath chain) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
validator.validate(chain, params);
} | 290 | 47.5 | 79 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-299/CustomRevocationChecking.java | public void validate(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
checker.setOcspResponder(OCSP_RESPONDER_URL);
checker.setOcspResponderCert(OCSP_RESPONDER_CERT);
params.addCertPathChecker(checker);
validator.validate(certPath, params);
} | 529 | 52 | 93 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-273/UnsafeCertTrust.java | public static void main(String[] args) {
{
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
try { //GOOD: verify the certificate
Certificate[] certs = session.getPeerCertificates();
X509Certificate x509 = (X509Certificate) certs[0];
check(new String[]{host}, x509);
return true;
} catch (SSLException e) {
return false;
}
}
};
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
}
{
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // BAD: accept even if the hostname doesn't match
}
};
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
}
{
X509TrustManager trustAllCertManager = new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
// BAD: trust any server cert
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; //BAD: doesn't check cert issuer
}
};
}
{
X509TrustManager trustCertManager = new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
pkixTrustManager.checkServerTrusted(chain, authType); //GOOD: validate the server cert
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]; //GOOD: Validate the cert issuer
}
};
}
{
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); //GOOD: Set a valid endpointIdentificationAlgorithm for SSL engine to trigger hostname verification
sslEngine.setSSLParameters(sslParameters);
}
{
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine(); //BAD: No endpointIdentificationAlgorithm set
}
{
SSLContext sslContext = SSLContext.getInstance("TLS");
final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket("www.example.com", 443);
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); //GOOD: Set a valid endpointIdentificationAlgorithm for SSL socket to trigger hostname verification
socket.setSSLParameters(sslParameters);
}
{
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.useSslProtocol();
connectionFactory.enableHostnameVerification(); //GOOD: Enable hostname verification for rabbitmq ConnectionFactory
}
{
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.useSslProtocol(); //BAD: Hostname verification for rabbitmq ConnectionFactory is not enabled
}
} | 3,421 | 32.881188 | 160 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-297/SimpleMail.java | import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
class SimpleMail {
public static void main(String[] args) throws EmailException {
// BAD: Don't have setSSLCheckServerIdentity set or set as false
{
Email email = new SimpleEmail();
email.setHostName("hostName");
email.setSmtpPort(25);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSLOnConnect(true);
//email.setSSLCheckServerIdentity(false);
email.setFrom("fromAddress");
email.setSubject("subject");
email.setMsg("body");
email.addTo("toAddress");
email.send();
}
// GOOD: Have setSSLCheckServerIdentity set to true
{
Email email = new SimpleEmail();
email.setHostName("hostName");
email.setSmtpPort(25);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSLOnConnect(true);
email.setSSLCheckServerIdentity(true);
email.setFrom("fromAddress");
email.setSubject("subject");
email.setMsg("body");
email.addTo("toAddress");
email.send();
}
}
} | 1,331 | 32.3 | 81 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-297/JavaMail.java | import java.util.Properties;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import org.apache.logging.log4j.util.PropertiesUtil;
class JavaMail {
public static void main(String[] args) {
// BAD: Don't have server certificate check
{
final Properties properties = PropertiesUtil.getSystemProperties();
properties.put("mail.transport.protocol", "protocol");
properties.put("mail.smtp.host", "hostname");
properties.put("mail.smtp.socketFactory.class", "classname");
final Authenticator authenticator = buildAuthenticator("username", "password");
if (null != authenticator) {
properties.put("mail.smtp.auth", "true");
}
final Session session = Session.getInstance(properties, authenticator);
}
// GOOD: Have server certificate check
{
final Properties properties = PropertiesUtil.getSystemProperties();
properties.put("mail.transport.protocol", "protocol");
properties.put("mail.smtp.host", "hostname");
properties.put("mail.smtp.socketFactory.class", "classname");
final Authenticator authenticator = buildAuthenticator("username", "password");
if (null != authenticator) {
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.checkserveridentity", "true");
}
final Session session = Session.getInstance(properties, authenticator);
}
}
} | 1,501 | 33.930233 | 81 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-016/SpringBootActuators.java | @Configuration(proxyBeanMethods = false)
public class SpringBootActuators extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// BAD: Unauthenticated access to Spring Boot actuator endpoints is allowed
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().permitAll());
}
}
@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// GOOD: only users with ENDPOINT_ADMIN role are allowed to access the actuator endpoints
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
}
} | 867 | 38.454545 | 93 | java |
codeql | codeql-master/java/ql/src/experimental/Security/CWE/CWE-643/XPathInjection.java | final String xmlStr = "<users>" +
" <user name=\"aaa\" pass=\"pass1\"></user>" +
" <user name=\"bbb\" pass=\"pass2\"></user>" +
"</users>";
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
//Document doc = builder.parse("user.xml");
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
// Injectable data
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if (user != null && pass != null) {
boolean isExist = false;
// Bad expression
String expression1 = "/users/user[@name='" + user + "' and @pass='" + pass + "']";
isExist = (boolean)xpath.evaluate(expression1, doc, XPathConstants.BOOLEAN);
System.out.println(isExist);
// Bad expression
XPathExpression expression2 = xpath.compile("/users/user[@name='" + user + "' and @pass='" + pass + "']");
isExist = (boolean)expression2.evaluate(doc, XPathConstants.BOOLEAN);
System.out.println(isExist);
// Bad expression
StringBuffer sb = new StringBuffer("/users/user[@name=");
sb.append(user);
sb.append("' and @pass='");
sb.append(pass);
sb.append("']");
String query = sb.toString();
XPathExpression expression3 = xpath.compile(query);
isExist = (boolean)expression3.evaluate(doc, XPathConstants.BOOLEAN);
System.out.println(isExist);
// Good expression
String expression4 = "/users/user[@name=$user and @pass=$pass]";
xpath.setXPathVariableResolver(v -> {
switch (v.getLocalPart()) {
case "user":
return user;
case "pass":
return pass;
default:
throw new IllegalArgumentException();
}
});
isExist = (boolean)xpath.evaluate(expression4, doc, XPathConstants.BOOLEAN);
System.out.println(isExist);
// Bad Dom4j
org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
org.dom4j.Document document = reader.read(new InputSource(new StringReader(xmlStr)));
isExist = document.selectSingleNode("/users/user[@name='" + user + "' and @pass='" + pass + "']").hasContent();
// or document.selectNodes
System.out.println(isExist);
}
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
} catch (XPathExpressionException e) {
} catch (org.dom4j.DocumentException e) {
} | 2,788 | 37.205479 | 119 | java |
codeql | codeql-master/java/ql/src/experimental/CWE-532/SensitiveInfoLog.java | public static void main(String[] args) {
{
private static final Logger logger = LogManager.getLogger(SensitiveInfoLog.class);
String password = "Pass@0rd";
// BAD: user password is written to debug log
logger.debug("User password is "+password);
}
{
private static final Logger logger = LogManager.getLogger(SensitiveInfoLog.class);
String password = "Pass@0rd";
// GOOD: user password is never written to debug log
}
}
| 500 | 25.368421 | 90 | java |
codeql | codeql-master/java/ql/test/library-tests/commentedcode/Test.java | import com.google.j2objc.security.IosRSASignature;
class Test {}
| 65 | 21 | 50 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.