private static Connection getConnection() throws SQLException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(DBSample1.class.getName()).log(Level.SEVERE, null, ex); } String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST"); String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT"); String username = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME"); String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD"); String name = "dbsample1"; String url = "jdbc:mysql://" + host + ":" + port + "/" + name; return DriverManager.getConnection(url, username, password); }
/* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */ private void goodB2G1() throws Throwable { String data; if (IO.STATIC_FINAL_FIVE == 5) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.STATIC_FINAL_FIVE != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } 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); } } } } }
/* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */ private void goodB2G1() throws Throwable { String data; if (IO.staticTrue) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; ResultSet resultSet = null; try { /* FIX: Use prepared statement and executeQuery (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("select * from users where name=?"); sqlStatement.setString(1, data); resultSet = sqlStatement.executeQuery(); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } 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); } } } }
public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); // get("/hello", (req, res) -> "Hello World"); // get("/hello", (req, res) -> { // RelativisticModel.select(); // String energy = System.getenv().get("ENERGY"); // Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM); // return "E=mc^2: " + energy + " = " + m.toString(); // }); // get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); get( "/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add("Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } } }, new FreeMarkerEngine()); }
/* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */ private void goodB2G1() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"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); } } } }
/* goodB2G1() - use BadSource and GoodSink by setting the variable to false instead of true */ private void goodB2G1() throws Throwable { String data; /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); goodB2G1Private = false; goodB2G1Sink(data); }
public void bad() throws Throwable { String data; /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); badPrivate = true; badSink(data); }
public void bad() throws Throwable { String data; if (IO.STATIC_FINAL_FIVE == 5) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.STATIC_FINAL_FIVE == 5) { 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); } } } } }
// Extract connection URL from environment variable as setup by docker (or manually) private String getConnectionUrl() { String dbPort = System.getenv("DB_PORT"); // Fallback for alexec Plugin which does not support configuration of link aliases if (dbPort == null) { dbPort = System.getenv("SHOOTOUT_DOCKER_MAVEN_DB_PORT"); } if (dbPort == null) { throw new IllegalArgumentException( "No DB_PORT or SHOOTOUT_DOCKER_MAVEN_DB_PORT environment variable set. Please check you docker link parameters."); } Pattern pattern = Pattern.compile("^[^/]*//(.*)"); Matcher matcher = pattern.matcher(dbPort); if (!matcher.matches()) { throw new IllegalArgumentException( "Invalid format of DB_PORT variable: Expected tcp://host:port and not " + dbPort); } String hostAndPort = matcher.group(1); return "jdbc:postgresql://" + hostAndPort + "/postgres"; }
/* goodG2B1() - use goodsource and badsink by changing the first switch to switch(5) */ private void goodG2B1() throws Throwable { int data; switch (5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } } break; default: { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } break; } switch (7) { case 7: { int valueToAdd = (new SecureRandom()).nextInt(99) + 1; /* adding at least 1 */ /* POTENTIAL FLAW: if (data+valueToAdd) > MAX_VALUE, this will overflow */ int result = (data + valueToAdd); IO.writeLine("result: " + result); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { int result = 0; int valueToAdd = (new SecureRandom()).nextInt(99) + 1; /* adding at least 1 */ /* FIX: Add a check to prevent an overflow from occurring */ if (data <= (Integer.MAX_VALUE - valueToAdd)) { result = (data + valueToAdd); IO.writeLine("result: " + result); } else { IO.writeLine("Input value is too large to perform addition."); } } break; } }
public void bad() throws Throwable { String data; if (IO.staticTrue) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticTrue) { Connection dbConnection = null; Statement sqlStatement = null; ResultSet resultSet = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */ resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'"); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
public void bad() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */ Boolean result = sqlStatement.execute( "insert into users (status) values ('updated') where name='" + data + "'"); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { int data; if (IO.static_five == 5) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } } if (IO.static_five == 5) { int valueToMult = (new SecureRandom()).nextInt(98) + 2; /* multiply by at least 2 */ if (data > 0) /* ensure we don't have an underflow */ { /* POTENTIAL FLAW: if (data*valueToMult) > MAX_VALUE, this will overflow */ int result = (data * valueToMult); IO.writeLine("result: " + result); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int valueToMult = (new SecureRandom()).nextInt(98) + 2; /* multiply by at least 2 */ if (data > 0) /* ensure we don't have an underflow */ { int result = 0; /* FIX: Add a check to prevent an overflow from occurring */ if (data <= (Integer.MAX_VALUE / valueToMult)) { result = (data * valueToMult); IO.writeLine("result: " + result); } else { IO.writeLine("Input value is too large to perform multiplication."); } } } }
/* goodB2G() - use badsource and goodsink */ private void goodB2G() throws Throwable { Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } (new CWE191_Integer_Underflow__Environment_multiply_68b()).goodB2G_sink(); }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { int data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_five == 5) { Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_five == 5) { int valueToSub = (new SecureRandom()).nextInt(99) + 1; /* subtracting at least 1 */ int result = 0; /* FIX: Add a check to prevent an underflow from occurring */ if (data >= (Integer.MIN_VALUE + valueToSub)) { result = (data - valueToSub); IO.writeLine("result: " + result); } else { IO.writeLine("Input value is too small to perform subtraction."); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int valueToSub = (new SecureRandom()).nextInt(99) + 1; /* subtracting at least 1 */ /* POTENTIAL FLAW: if (data-valueToSub) < MIN_VALUE this will underflow */ int result = (data - valueToSub); IO.writeLine("result: " + result); } }
/* goodB2G() - use badsource and goodsink */ private void goodB2G() throws Throwable { int data; Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } (new CWE369_Divide_By_Zero__Environment_modulo_51b()).goodB2G_sink(data); }
public void bad() throws Throwable { int data; Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } (new CWE190_Integer_Overflow__Environment_square_51b()).bad_sink(data); }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { int data; if (IO.static_final_five == 5) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); /* init data */ data = -1; /* get environment variable ADD */ String s_data = System.getenv("ADD"); try { data = Integer.parseInt(s_data.trim()); } catch (NumberFormatException nfe) { log_bad.warning("Error with number parsing"); } } if (IO.static_final_five == 5) { /* POTENTIAL FLAW: if (data*data) > MAX_VALUE, this will overflow */ int result = (data * data); IO.writeLine("result: " + result); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int result = 0; /* FIX: Add a check to prevent an overflow from occurring * NOTE: Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE so we must ensure the random value in * data is not equal to Integer.MIN_VALUE */ if ((Math.abs(data) != Integer.MIN_VALUE) && (Math.abs(data) <= (int) Math.sqrt(Integer.MAX_VALUE))) { result = (data * data); IO.writeLine("result: " + result); } else { IO.writeLine("Input value is too large to perform squaring."); } } }
public static void main(String[] args) throws Exception { Date dteTemp; SimpleDateFormat sdfTemp = new SimpleDateFormat("yyyy_MM_dd-E-hh:mm:ss_a"); AddressBook adbContacts = new AddressBook(); String strTempName; String strTempVMID; String strTempVMTS; Class.forName("org.sqlite.JDBC"); Connection conn = DriverManager.getConnection( "jdbc:sqlite:" + System.getenv("HOME") + "/iPhone_fake/Voicemail/voicemail.db"); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT * FROM voicemail ORDER BY date;"); while (rs.next()) { strTempVMID = rs.getString("ROWID"); dteTemp = SQLLiteData.convertDate(rs.getString("date")); strTempVMTS = sdfTemp.format(dteTemp); strTempName = adbContacts.lookupContact(rs.getString("sender")); createContactDir(strTempName); moveVoicemail(strTempName, strTempVMID, strTempVMTS); // dteTemp = SQLLiteData.convertDate(rs.getString("expiration")); // System.out.print(sdfTemp.format(dteTemp) + " "); // System.out.print(adbContacts.lookupContact(rs.getString("callback_num")) // + " "); // System.out.print(rs.getString("duration") + " "); // System.out.print(rs.getString("flags") + " "); // System.out.println(); } stat.close(); rs.close(); conn.close(); }
public class VoiceMail { private static String strSrcVMDir = System.getenv("HOME") + "/iPhone_fake/Voicemail/"; private static String strDestVMDir = System.getenv("HOME") + "/iPhone/Voicemail/"; public static void main(String[] args) throws Exception { Date dteTemp; SimpleDateFormat sdfTemp = new SimpleDateFormat("yyyy_MM_dd-E-hh:mm:ss_a"); AddressBook adbContacts = new AddressBook(); String strTempName; String strTempVMID; String strTempVMTS; Class.forName("org.sqlite.JDBC"); Connection conn = DriverManager.getConnection( "jdbc:sqlite:" + System.getenv("HOME") + "/iPhone_fake/Voicemail/voicemail.db"); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT * FROM voicemail ORDER BY date;"); while (rs.next()) { strTempVMID = rs.getString("ROWID"); dteTemp = SQLLiteData.convertDate(rs.getString("date")); strTempVMTS = sdfTemp.format(dteTemp); strTempName = adbContacts.lookupContact(rs.getString("sender")); createContactDir(strTempName); moveVoicemail(strTempName, strTempVMID, strTempVMTS); // dteTemp = SQLLiteData.convertDate(rs.getString("expiration")); // System.out.print(sdfTemp.format(dteTemp) + " "); // System.out.print(adbContacts.lookupContact(rs.getString("callback_num")) // + " "); // System.out.print(rs.getString("duration") + " "); // System.out.print(rs.getString("flags") + " "); // System.out.println(); } stat.close(); rs.close(); conn.close(); } private static void createContactDir(String strContact) { File dirCurrent = new File(strDestVMDir + strContact); if (!dirCurrent.exists()) { try { boolean success = (dirCurrent).mkdir(); if (!success) { throw new Exception("Well that wasn't planned for..."); } } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.err.println(); System.err.println(e.getStackTrace()); System.exit(0); } } } private static void moveVoicemail(String strContact, String strID, String strTempVMTS) { System.out.println(strContact + " " + strID + " " + strTempVMTS); try { File fSrc = new File(strSrcVMDir + "/" + strID + ".amr"); File fDest = new File(strDestVMDir + strContact + "/" + strTempVMTS + ".amr"); InputStream isSrc = new FileInputStream(fSrc); OutputStream osDest = new FileOutputStream(fDest); byte[] buf = new byte[1024]; int len; while ((len = isSrc.read(buf)) > 0) { osDest.write(buf, 0, len); } isSrc.close(); osDest.close(); System.out.println("File copied."); } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.err.println(); System.err.println(e.getStackTrace()); System.exit(0); } } }
public class GenerateSeq { static final String JDBC_DRIVER = "com.postgresql.jdbc.Driver"; static final String DB_TYPE = "postgresql"; static final String DB_DRIVER = "jdbc"; static final String DB_NAME = "food_truck"; static final String DB_HOST = "localhost"; static final String DB_URL = String.format("%s:%s://%s/%s", DB_DRIVER, DB_TYPE, DB_HOST, DB_NAME); static final String DB_USER = System.getenv("DB_USER"); static final String DB_PASSWORD = System.getenv("DB_PASSWORD"); private static final long serialVersionUID = 1L; static Connection conn; static int round; static List<Integer> data; static int year; // /** test **/ // public GenerateSeq(){ // data = new LinkedList<Integer>(); // /** dummy data**/ // Random rand = new Random(); // year = 2016; // for(int i=0; i<20; i++){ // data.add(rand.nextInt(60)+70); //random number b/w 70 and 130 as ID // } // } // public List<Integer[]> test(){ // try { // conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return initiate(data.size()); // } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} /** * populate round and sequence with the latest round and generated sequence based on the number of * trucks * * @param number of trucks * @throws SQLException */ private static void initiate(int size) { // TODO Auto-generated method stub Statement st = null; ResultSet rs1 = null; ResultSet rs2 = null; ResultSet rs3 = null; try { Class.forName("org.postgresql.Driver"); st = conn.createStatement(); // Sql to retrieve last roundnum last: String sql1 = "SELECT MAX(round_number) FROM rounds WHERE year = " + year; rs1 = st.executeQuery(sql1); rs1.next(); int last = rs1.getInt(1); round = last + 1; // Create new round String sql2 = "INSERT INTO rounds (year, round_number) values (" + year + ", " + round + ")"; st.executeUpdate(sql2); // Create new sequence based on food truck for (int i = 1; i < size + 1; i++) { String temp = getSeqQuery(i, round); st.executeUpdate(temp); } // insert into Lottery // Get truck name and email for lottery insert Map<Integer, String[]> truckinfo = new HashMap<Integer, String[]>(); String sql4 = "SELECT owner_name, email, id FROM foodtruck"; rs2 = st.executeQuery(sql4); while (rs2.next()) { String name = rs2.getString(1).trim(); String email = rs2.getString(2).trim(); int id = rs2.getInt(3); String[] temp = {name, email}; truckinfo.put(id, temp); } // insert into lottery insertLottery(truckinfo); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void insertLottery(Map<Integer, String[]> truckinfo) { try { Class.forName("org.postgresql.Driver"); Statement st = conn.createStatement(); // randomly generate order Collections.shuffle(data); int position = 0; while (position < data.size()) { int temp = data.get(position); String s = getLotteryQuery(temp, truckinfo, position + 1); st.executeUpdate(s); position++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String getLotteryQuery(int id, Map<Integer, String[]> truckinfo, int position) { // TODO Auto-generated method stub String[] array = truckinfo.get(id); String name = array[0]; String email = array[1]; return "INSERT INTO lottery (name, email, id, year, round_number, position) values ('" + name + "', '" + email + "', " + id + ", " + year + ", " + round + ", " + position + ")"; } /** * return query line for inserting sequence * * @param number * @param last * @return */ private static String getSeqQuery(int number, int last) { return "INSERT INTO sequence (year, round_number, position) values (" + year + ", " + last + 1 + ", " + number + ")"; } public static int getfirst() { // try { // Class.forName("org.postgresql.Driver"); // conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (SQLException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // data = new LinkedList<Integer>(); // /** dummy data**/ // Random rand = new Random(); // year = 2016; data.add(70); data.add(71); // data.add(72); // // //retrieve order of new round // initiate(data.size()); return data.get(0); } public static int getnext(int order) { System.out.println(data.get(order - 1)); return data.get(order - 1); } public static int getlength() { return data.size(); } public static void generate_sequence() {} }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { String data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_t) { Logger log_bad = Logger.getLogger("local-logger"); /* get environment variable ADD */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_t) { Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; PreparedStatement sqlstatement = null; ResultSet sqlrs = null; try { /* FIX: use prepared sqlstatement */ conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.prepareStatement("select * from users where name=?"); sqlstatement.setString(1, data); sqlrs = sqlstatement.executeQuery(); IO.writeString(sqlrs.toString()); } catch (SQLException se) { log2.warning("Error getting database connection"); } finally { try { if (sqlrs != null) { sqlrs.close(); } } catch (SQLException e) { log2.warning("Error closing sqlrs"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; Statement sqlstatement = null; ResultSet sqlrs = null; try { conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.createStatement(); /* POTENTIAL FLAW: take user input and place into dynamic sql query */ sqlrs = sqlstatement.executeQuery("select * from users where name='" + data + "'"); IO.writeString(sqlrs.toString()); } catch (SQLException se) { log2.warning("Error getting database connection"); } finally { try { if (sqlrs != null) { sqlrs.close(); } } catch (SQLException e) { log2.warning("Error closing sqlrs"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } } } }