/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } }
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticReturnsTrueOrFalse()) { if (data != null) { /* POTENTIAL FLAW: Input not verified before inclusion in header */ response.setHeader("Location", "/author.jsp?lang=" + data); } } else { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = URLEncoder.encode(data, "UTF-8"); response.setHeader("Location", "/author.jsp?lang=" + data); } } }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } if (IO.staticReturnsTrueOrFalse()) { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = URLEncoder.encode(data, "UTF-8"); response.setHeader("Location", "/author.jsp?lang=" + data); } } else { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = URLEncoder.encode(data, "UTF-8"); response.setHeader("Location", "/author.jsp?lang=" + data); } } }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } else { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } if (IO.staticReturnsTrueOrFalse()) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = URLEncoder.encode(data, "UTF-8"); response.addHeader("Location", "/author.jsp?lang=" + data); } } else { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = URLEncoder.encode(data, "UTF-8"); response.addHeader("Location", "/author.jsp?lang=" + data); } } }
public void bad() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Set data to a random value */ data = (new SecureRandom()).nextInt(); } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { if (data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Integer.MIN_VALUE, this will underflow */ int result = (int) (data * 2); IO.writeLine("result: " + result); } } else { if (data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Integer.MIN_VALUE, this will underflow */ int result = (int) (data * 2); IO.writeLine("result: " + result); } } }
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Input from file not verified */ if (data != null) { response.addHeader("Location", "/author.jsp?lang=" + data); } } else { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = URLEncoder.encode(data, "UTF-8"); response.addHeader("Location", "/author.jsp?lang=" + data); } } }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void goodB2G() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Set data to a random value */ data = (new SecureRandom()).nextInt(); } else { /* POTENTIAL FLAW: Set data to a random value */ data = (new SecureRandom()).nextInt(); } if (IO.staticReturnsTrueOrFalse()) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = {0, 1, 2, 3, 4}; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } }
public void bad() throws Throwable { float data; if (IO.staticReturnsTrueOrFalse()) { data = -1.0f; /* Initialize data */ /* retrieve the property */ Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) { try { data = Float.parseFloat(stringNumber.trim()); } catch (NumberFormatException exceptNumberFormat) { IO.logger.log( Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } else { /* FIX: Use a hardcoded number that won't a divide by zero */ data = 2.0f; } if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Possibly modulo by zero */ int result = (int) (100.0 % data); IO.writeLine(result); } else { /* FIX: Check for value of or near zero before modulo */ if (Math.abs(data) > 0.000001) { int result = (int) (100.0 % data); IO.writeLine(result); } else { IO.writeLine("This would result in a modulo by zero"); } } }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (data != null) { /* This prevents \r\n (and other chars) and should prevent incidentals such * as HTTP Response Splitting and HTTP Header Injection. */ URI uri; try { uri = new URI(data); } catch (URISyntaxException exceptURISyntax) { response.getWriter().write("Invalid redirect URL"); return; } /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */ response.sendRedirect(data); return; } }
/* uses badsource and badsink - see how tools report flaws that don't always occur */ public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (data != null) { /* POTENTIAL FLAW: script code (e.g. id=<script>alert('xss')</script>) is sent to the client; * The built-in J2EE server automatically does some HTML entity encoding. * Therefore, to test this, change response.sendError to response.getWriter().println and remove the 404, */ response.sendError(404, "<br>bad() - Parameter name has value " + data); } }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } Connection dbConnection = null; try { dbConnection = IO.getDBConnection(); /* POTENTIAL FLAW: Set the catalog name with the value of data * allowing a nonexistent catalog name or unauthorized access to a portion of the DB */ dbConnection.setCatalog(data); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
/* uses badsource and badsink - see how tools report flaws that don't always occur */ public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* read input from URLConnection */ { URLConnection urlConnection = (new URL("http://www.example.org/")).openConnection(); BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { readerInputStream = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ /* This will be reading the first "line" of the response body, * which could be very long if there are no newlines in the HTML */ data = readerBuffered.readLine(); } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* clean up stream reading objects */ try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (data != null) { /* This prevents \r\n (and other chars) and should prevent incidentals such * as HTTP Response Splitting and HTTP Header Injection. */ URI uri; try { uri = new URI(data); } catch (URISyntaxException exceptURISyntax) { response.getWriter().write("Invalid redirect URL"); return; } /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */ response.sendRedirect(data); return; } }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } else { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } if (IO.staticReturnsTrueOrFalse()) { int numberOfLoops; try { numberOfLoops = Integer.parseInt(data); } catch (NumberFormatException exceptNumberFormat) { IO.writeLine("Invalid response. Numeric input expected. Assuming 1."); numberOfLoops = 1; } /* FIX: loop number thresholds validated */ if (numberOfLoops >= 0 && numberOfLoops <= 5) { for (int i = 0; i < numberOfLoops; i++) { IO.writeLine("hello world"); } } } else { int numberOfLoops; try { numberOfLoops = Integer.parseInt(data); } catch (NumberFormatException exceptNumberFormat) { IO.writeLine("Invalid response. Numeric input expected. Assuming 1."); numberOfLoops = 1; } /* FIX: loop number thresholds validated */ if (numberOfLoops >= 0 && numberOfLoops <= 5) { for (int i = 0; i < numberOfLoops; i++) { IO.writeLine("hello world"); } } } }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Zero denominator will cause an issue. An integer division will result in an exception. */ IO.writeLine("bad: 100/" + data + " = " + (100 / data) + "\n"); } else { /* POTENTIAL FLAW: Zero denominator will cause an issue. An integer division will result in an exception. */ IO.writeLine("bad: 100/" + data + " = " + (100 / data) + "\n"); } }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { float data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded number that won't a divide by zero */ data = 2.0f; } else { /* FIX: Use a hardcoded number that won't a divide by zero */ data = 2.0f; } if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Possibly modulo by zero */ int result = (int) (100.0 % data); IO.writeLine(result); } else { /* POTENTIAL FLAW: Possibly modulo by zero */ int result = (int) (100.0 % data); IO.writeLine(result); } }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded int as a string */ data = "5"; } else { /* FIX: Use a hardcoded int as a string */ data = "5"; } if (IO.staticReturnsTrueOrFalse()) { int numberOfLoops; try { numberOfLoops = Integer.parseInt(data); } catch (NumberFormatException exceptNumberFormat) { IO.writeLine("Invalid response. Numeric input expected. Assuming 1."); numberOfLoops = 1; } for (int i = 0; i < numberOfLoops; i++) { /* POTENTIAL FLAW: user supplied input used for loop counter test */ IO.writeLine("hello world"); } } else { int numberOfLoops; try { numberOfLoops = Integer.parseInt(data); } catch (NumberFormatException exceptNumberFormat) { IO.writeLine("Invalid response. Numeric input expected. Assuming 1."); numberOfLoops = 1; } for (int i = 0; i < numberOfLoops; i++) { /* POTENTIAL FLAW: user supplied input used for loop counter test */ IO.writeLine("hello world"); } } }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* POTENTIAL FLAW: Create a HashSet using data as the initial size. data may be very large, creating memory issues */ HashSet intHashSet = new HashSet(data); }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticReturnsTrueOrFalse()) { if (data != null) { /* POTENTIAL FLAW: Input not verified before inclusion in header */ response.setHeader("Location", "/author.jsp?lang=" + data); } } else { if (data != null) { /* POTENTIAL FLAW: Input not verified before inclusion in header */ response.setHeader("Location", "/author.jsp?lang=" + data); } } }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (data != null) { /* POTENTIAL FLAW: script code (e.g. id=<script>alert('xss')</script>) is sent to the client; * The built-in J2EE server automatically does some HTML entity encoding. * Therefore, to test this, change response.sendError to response.getWriter().println and remove the 404, */ response.sendError(404, "<br>bad() - Parameter name has value " + data); } }
public void bad() throws Throwable { if (IO.staticReturnsTrueOrFalse()) { /* FLAW: Differentiating by name is not enough, since different classes in different packages may use the same name */ testcases.CWE486_Compare_Classes_by_Name.HelperClass.CWE486_Compare_Classes_by_Name__Helper helperClass = new testcases.CWE486_Compare_Classes_by_Name.HelperClass .CWE486_Compare_Classes_by_Name__Helper(); testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper helperClassRoot = new testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper(); if (helperClassRoot .getClass() .getSimpleName() .equals(helperClass.getClass().getSimpleName())) { IO.writeLine("Classes are the same"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Classes are different"); } } else { testcases.CWE486_Compare_Classes_by_Name.HelperClass.CWE486_Compare_Classes_by_Name__Helper helperClass = new testcases.CWE486_Compare_Classes_by_Name.HelperClass .CWE486_Compare_Classes_by_Name__Helper(); testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper helperClassRoot = new testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper(); /* FIX: Compare the class types and not the names */ if (helperClassRoot.getClass().equals(helperClass.getClass())) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Classes are the same"); } else { IO.writeLine("Classes are different"); } } }
/* good1() changes the "if" so that both branches use the GoodSink */ private void good1() throws Throwable { if (IO.staticReturnsTrueOrFalse()) { testcases.CWE486_Compare_Classes_by_Name.HelperClass.CWE486_Compare_Classes_by_Name__Helper helperClass = new testcases.CWE486_Compare_Classes_by_Name.HelperClass .CWE486_Compare_Classes_by_Name__Helper(); testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper helperClassRoot = new testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper(); /* FIX: Compare the class types and not the names */ if (helperClassRoot.getClass().equals(helperClass.getClass())) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Classes are the same"); } else { IO.writeLine("Classes are different"); } } else { testcases.CWE486_Compare_Classes_by_Name.HelperClass.CWE486_Compare_Classes_by_Name__Helper helperClass = new testcases.CWE486_Compare_Classes_by_Name.HelperClass .CWE486_Compare_Classes_by_Name__Helper(); testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper helperClassRoot = new testcases.CWE486_Compare_Classes_by_Name.CWE486_Compare_Classes_by_Name__Helper(); /* FIX: Compare the class types and not the names */ if (helperClassRoot.getClass().equals(helperClass.getClass())) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Classes are the same"); } else { IO.writeLine("Classes are different"); } } }
/* uses badsource and badsink - see how tools report flaws that don't always occur */ public void bad() throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } Connection dbConnection = null; try { dbConnection = IO.getDBConnection(); /* POTENTIAL FLAW: Set the catalog name with the value of data * allowing a nonexistent catalog name or unauthorized access to a portion of the DB */ dbConnection.setCatalog(data); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
public void bad() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { data = Integer.MIN_VALUE; /* Initialize data */ /* read input from URLConnection */ { URLConnection urlConnection = (new URL("http://www.example.org/")).openConnection(); BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { readerInputStream = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ /* This will be reading the first "line" of the response body, * which could be very long if there are no newlines in the HTML */ String stringNumber = readerBuffered.readLine(); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch (NumberFormatException exceptNumberFormat) { IO.logger.log( Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* clean up stream reading objects */ try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } } } } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { if (data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Integer.MIN_VALUE, this will underflow */ int result = (int) (data * 2); IO.writeLine("result: " + result); } } else { if (data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Integer.MIN_VALUE / 2)) { int result = (int) (data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } }
public void bad() throws Throwable { if (IO.staticReturnsTrueOrFalse()) { BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { readerInputStream = new InputStreamReader(System.in, "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* read user input from console */ IO.writeLine("Enter string1: "); /* enter "test" */ String string1 = readerBuffered.readLine(); IO.writeLine("Enter string2: "); /* enter "test" */ String string2 = readerBuffered.readLine(); if (string1 != null && string2 != null) { /* output comparison results */ if (string1 == string2) /* FLAW: using == operator instead of .equals() object method */ { IO.writeLine("bad(): Strings are equal"); } else { IO.writeLine("bad(): Strings are not equal"); /* This will always display */ } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error!", exceptIO); } finally { try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } } } else { BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { readerInputStream = new InputStreamReader(System.in, "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* read user input from console */ IO.writeLine("Enter string1: "); /* enter "test" */ String string1 = readerBuffered.readLine(); IO.writeLine("Enter string2: "); /* enter "test" */ String string2 = readerBuffered.readLine(); if (string1 != null && string2 != null) { /* output comparison */ if (string1.equals(string2)) /* FIX: use of equals() instead of == operator */ { IO.writeLine("good(): Strings are equal"); } else { IO.writeLine("good(): Strings are not equal"); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error!", exceptIO); } finally { try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } } } }
public void bad() throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticReturnsTrueOrFalse()) { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); for (int i = 0; i < names.length; i++) { /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */ sqlStatement.addBatch( "update users set hitcount=hitcount+1 where name='" + names[i] + "'"); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } }
/* uses badsource and badsink - see how tools report flaws that don't always occur */ public void bad() throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } String root; if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ root = "C:\\uploads\\"; } else { /* running on non-Windows */ root = "/home/user/uploads/"; } if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ File file = new File(root + data); FileInputStream streamFileInputSink = null; InputStreamReader readerInputStreamSink = null; BufferedReader readerBufferdSink = null; if (file.exists() && file.isFile()) { try { streamFileInputSink = new FileInputStream(file); readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8"); readerBufferdSink = new BufferedReader(readerInputStreamSink); IO.writeLine(readerBufferdSink.readLine()); } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading objects */ try { if (readerBufferdSink != null) { readerBufferdSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStreamSink != null) { readerInputStreamSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } try { if (streamFileInputSink != null) { streamFileInputSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ private void goodG2B() throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } String root; if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ root = "C:\\uploads\\"; } else { /* running on non-Windows */ root = "/home/user/uploads/"; } if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ File file = new File(root + data); FileInputStream streamFileInputSink = null; InputStreamReader readerInputStreamSink = null; BufferedReader readerBufferdSink = null; if (file.exists() && file.isFile()) { try { streamFileInputSink = new FileInputStream(file); readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8"); readerBufferdSink = new BufferedReader(readerInputStreamSink); IO.writeLine(readerBufferdSink.readLine()); } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading objects */ try { if (readerBufferdSink != null) { readerBufferdSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStreamSink != null) { readerInputStreamSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } try { if (streamFileInputSink != null) { streamFileInputSink.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } }
public void bad() throws Throwable { int data; if (IO.staticReturnsTrueOrFalse()) { data = Integer.MIN_VALUE; /* Initialize data */ /* read input from URLConnection */ { URLConnection urlConnection = (new URL("http://www.example.org/")).openConnection(); BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { readerInputStream = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ /* This will be reading the first "line" of the response body, * which could be very long if there are no newlines in the HTML */ String stringNumber = readerBuffered.readLine(); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch (NumberFormatException exceptNumberFormat) { IO.logger.log( Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* clean up stream reading objects */ try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } } } } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.staticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Zero denominator will cause an issue. An integer division will result in an exception. */ IO.writeLine("bad: 100/" + data + " = " + (100 / data) + "\n"); } else { /* FIX: test for a zero denominator */ if (data != 0) { IO.writeLine("100/" + data + " = " + (100 / data) + "\n"); } else { IO.writeLine("This would result in a divide by zero"); } } }
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (IO.staticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* Read data using an outbound tcp connection */ { Socket socket = null; BufferedReader readerBuffered = null; InputStreamReader readerInputStream = null; try { /* Read data using an outbound tcp connection */ socket = new Socket("host.example.org", 39544); /* read input from socket */ readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8"); readerBuffered = new BufferedReader(readerInputStream); /* POTENTIAL FLAW: Read data using an outbound tcp connection */ data = readerBuffered.readLine(); } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* clean up stream reading objects */ try { if (readerBuffered != null) { readerBuffered.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO); } try { if (readerInputStream != null) { readerInputStream.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO); } /* clean up socket objects */ try { if (socket != null) { socket.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticReturnsTrueOrFalse()) { if (data != null) { /* POTENTIAL FLAW: Input not verified before inclusion in header */ response.setHeader("Location", "/author.jsp?lang=" + data); } } else { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = URLEncoder.encode(data, "UTF-8"); response.setHeader("Location", "/author.jsp?lang=" + data); } } }