/* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_FIVE==5 to PRIVATE_STATIC_FINAL_FIVE!=5 */
  private void goodB2G1() throws Throwable {
    short data;
    if (PRIVATE_STATIC_FINAL_FIVE == 5) {
      /* POTENTIAL FLAW: Use a random value */
      data =
          (short)
              ((new java.security.SecureRandom()).nextInt(1 + Short.MAX_VALUE - Short.MIN_VALUE)
                  + Short.MIN_VALUE);
    } 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 = 0;
    }

    if (PRIVATE_STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Short.MAX_VALUE))) {
        short result = (short) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data_copy;
    {
      int data;

      Logger log_bad = Logger.getLogger("local-logger");

      /* init Data$ */
      data = -1;

      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        String s_data = cookieSources[0].getValue();
        data = Integer.parseInt(s_data.trim());
      }

      data_copy = data;
    }
    {
      int data = data_copy;

      /* FIX: test for a zero modulus */
      if (data != 0) {
        IO.writeLine("100%" + String.valueOf(data) + " = " + (100 % data) + "\n");
      } 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() 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);
      }
    }
  }
  /* 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() throws Throwable {

    String fn =
        ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\insecureDir"; /* may have to be changed depending on script */
    /* POSSIBLE FLAW: potentially insecure directory permissions */
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  public void bad() throws Throwable {
    int data;
    if (IO.STATIC_FINAL_TRUE) {
      data = Integer.MIN_VALUE; /* Initialize data */
      /* get system property user.home */
      /* POTENTIAL FLAW: Read data from a system property */
      {
        String stringNumber = System.getProperty("user.home");
        try {
          data = Integer.parseInt(stringNumber.trim());
        } catch (NumberFormatException exceptNumberFormat) {
          IO.logger.log(
              Level.WARNING,
              "Number format exception parsing data from string",
              exceptNumberFormat);
        }
      }
    } 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 = 0;
    }

    if (IO.STATIC_FINAL_TRUE) {
      /* 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: Verify that data < array.length, but don't verify that data > 0, so may be attempting to read out of the array bounds */
      if (data < array.length) {
        IO.writeLine(array[data]);
      } else {
        IO.writeLine("Array index out of bounds");
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second true to false */
  private void goodB2G1() throws Throwable {
    short data;
    if (true) {
      /* POTENTIAL FLAW: Use a random value */
      data =
          (short)
              ((new java.security.SecureRandom()).nextInt(1 + Short.MAX_VALUE - Short.MIN_VALUE)
                  + Short.MIN_VALUE);
    } 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 = 0;
    }

    if (false) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      if (data < Short.MAX_VALUE) {
        short result = (short) (data + 1);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform addition.");
      }
    }
  }
 public void bad() throws Throwable {
   if (privateFive == 5) {
     FileInputStream fis = null;
     try {
       int bytesToRead = 1024;
       byte[] byteArray = new byte[bytesToRead];
       fis = new FileInputStream("c:\\file.txt");
       /* FLAW: Incorrect check on result of read().  Should check if the return value is -1 or is less than bytesToRead. */
       if (fis.read(byteArray) == 0) {
         IO.writeLine("Error reading file.");
       } else {
         IO.writeLine(new String(byteArray, "UTF-8"));
       }
     } catch (FileNotFoundException exceptFileNotFound) {
       IO.logger.log(Level.WARNING, "FileNotFoundException opening file", exceptFileNotFound);
     } catch (IOException exceptIO) {
       IO.logger.log(Level.WARNING, "IOException reading file", exceptIO);
     } finally {
       try {
         if (fis != null) {
           fis.close();
         }
       } catch (IOException exceptIO) {
         IO.logger.log(Level.WARNING, "IOException closing FileInputStream", exceptIO);
       }
     }
   }
 }
  /* 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.static_returns_t_or_f()) {
      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 {

      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;
    }
    if (IO.static_returns_t_or_f()) {
      int valueToMult = (new SecureRandom()).nextInt(98) + 2; /* multiply by at least 2 */
      if (data < 0) /* ensure we don't have an overflow */ {
        /* POTENTIAL FLAW: if (data*valueToMult) < MIN_VALUE, this will overflow */
        int result = (data * valueToMult);
        IO.writeLine("result: " + result);
      }
    } else {

      int valueToMult = (new SecureRandom()).nextInt(98) + 2; /* multiply by at least 2 */

      if (data < 0) /* ensure we don't have an overflow */ {
        /* POTENTIAL FLAW: if (data*valueToMult) < MIN_VALUE, this will overflow */
        int result = (data * valueToMult);
        IO.writeLine("result: " + result);
      }
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");

      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=33" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          try {
            data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
          } catch (NumberFormatException exceptNumberFormat) {
            IO.logger.log(
                Level.WARNING,
                "Number format exception reading id from query string",
                exceptNumberFormat);
          }
          break; /* exit while loop */
        }
      }
    }

    if (data > 0) /* ensure we won't have an underflow */ {
      /* FIX: Add a check to prevent an overflow from occurring */
      if (data < (Integer.MAX_VALUE / 2)) {
        int result = (int) (data * 2);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform multiplication.");
      }
    }
  }
 /* good2() reverses the bodies in the if statement */
 private void good2() throws Throwable {
   if (privateFive == 5) {
     FileInputStream fis = null;
     try {
       int bytesToRead = 1024;
       byte[] byteArray = new byte[bytesToRead];
       fis = new FileInputStream("c:\\file.txt");
       int numberOfBytesRead = fis.read(byteArray);
       /* FIX: Check the return value of read() and handle possible errors */
       if (numberOfBytesRead == -1) {
         IO.writeLine("The end of the file has been reached.");
       } else {
         if (numberOfBytesRead < bytesToRead) {
           IO.writeLine("Could not read " + bytesToRead + " bytes.");
         } else {
           IO.writeLine(new String(byteArray, "UTF-8"));
         }
       }
     } catch (FileNotFoundException exceptFileNotFound) {
       IO.logger.log(Level.WARNING, "FileNotFoundException opening file", exceptFileNotFound);
     } catch (IOException exceptIO) {
       IO.logger.log(Level.WARNING, "IOException reading file", exceptIO);
     } finally {
       try {
         if (fis != null) {
           fis.close();
         }
       } catch (IOException exceptIO) {
         IO.logger.log(Level.WARNING, "IOException closing FileInputStream", exceptIO);
       }
     }
   }
 }
  /* 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);
          }
        }
      }
    }
  }
  /* goodB2G() - use badsource and goodsink by changing the conditions on
  the second and third for statements */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* POTENTIAL FLAW: data may be set to null */
    data = request.getParameter("CWE690");

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: Set data to a fixed, non-null String */
      data = "CWE690";
    }

    for (int for_index_j = 0; for_index_j < 0; for_index_j++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* POTENTIAL FLAW: data could be null */
      String sOut = data.trim();
      IO.writeLine(sOut);
    }

    for (int for_index_k = 0; for_index_k < 1; for_index_k++) {
      /* FIX: explicit check for null */
      if (data != null) {
        String sOut = data.trim();
        IO.writeLine(sOut);
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* We need to have one source outside of a for loop in order
    to prevent the Java compiler from generating an error because
    data is uninitialized */

    /* POTENTIAL FLAW: data may be set to null */
    data = request.getParameter("CWE690");

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: Set data to a fixed, non-null String */
      data = "CWE690";
    }

    for (int for_index_j = 0; for_index_j < 1; for_index_j++) {
      /* POTENTIAL FLAW: data could be null */
      String sOut = data.trim();
      IO.writeLine(sOut);
    }

    for (int for_index_k = 0; for_index_k < 0; for_index_k++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: explicit check for null */
      if (data != null) {
        String sOut = data.trim();
        IO.writeLine(sOut);
      }
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger log_bad = Logger.getLogger("local-logger");

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */
      byte[] hashv = hash.digest("hash me".getBytes());
      IO.writeLine(IO.toHex(hashv));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      SecureRandom r = new SecureRandom();

      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */
      byte[] hashv = hash.digest("hash me".getBytes());

      IO.writeLine(IO.toHex(hashv));
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } 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 (privateFive == 5) {
      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");
      }
    }
  }
コード例 #17
0
  /* goodG2B1() - use goodsource and badsink by changing first IO.static_five==5 to IO.static_five!=5 */
  private void goodG2B1() throws Throwable {
    int data;
    if (IO.static_five != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* POTENTIAL FLAW: Use the maximum value for this type */
      data = Integer.MAX_VALUE;
    } else {

      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;
    }
    if (IO.static_five == 5) {
      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);
    } else {
      /* 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.");
      }
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      /* FIX: Use a hardcoded int as a string */
      data = "5";
    } 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 (privateFive == 5) {
      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 conditions on the first and second while statements */
  private void goodG2B() throws Throwable {
    String data;
    boolean local_f = false;

    while (true) {
      /* FIX: call getStringG(), which will never return null */
      data = CWE690_NULL_Deref_from_Return__Class__Helper.getStringGood();
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* POTENTIAL FLAW: Call getStringG(), which may return null */
      data = CWE690_NULL_Deref_from_Return__Class__Helper.getStringBad();
      break;
    }

    while (true) {
      /* POTENTIAL FLAW: data could be null */
      String sOut = data.trim();
      IO.writeLine(sOut);
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: explicit check for null */
      if (data != null) {
        String sOut = data.trim();
        IO.writeLine(sOut);
      }
      break;
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    if (IO.static_returns_t_or_f()) {
      /* POTENTIAL FLAW: Input from file not verified */
      response.addHeader("Location", "/author.jsp?lang=" + data);
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.staticReturnsTrue() to IO.staticReturnsFalse() */
  private void goodB2G1() throws Throwable {
    long data;
    if (IO.staticReturnsTrue()) {
      /* POTENTIAL FLAW: Use the maximum size of the data type */
      data = Long.MAX_VALUE;
    } 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 = 0L;
    }

    if (IO.staticReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      if (data < Long.MAX_VALUE) {
        long result = (long) (data + 1);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform addition.");
      }
    }
  }
  /* 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.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    } else {

      Logger log_bad = Logger.getLogger("local-logger");

      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    }
    if (IO.static_returns_t_or_f()) {
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    int data;

    if (IO.staticReturnsTrue()) {
      /* 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
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = 0;
    }

    if (IO.staticReturnsTrue()) {
      int array[] = null;
      /* POTENTIAL FLAW: Verify that data is non-negative, but still allow it to be 0 */
      if (data >= 0) {
        array = new int[data];
      } else {
        IO.writeLine("Array size is negative");
      }
      /* do something with the array */
      array[0] = 5;
      IO.writeLine(array[0]);
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing first private_final_t to private_final_f */
  private void goodG2B1() throws Throwable {
    int data;
    /* INCIDENTAL: CWE 570 Statement is Always False */
    if (private_final_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      SecureRandom r = new SecureRandom();
      data = r.nextInt();
    } else {

      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_t) {
      /* POTENTIAL FLAW: Zero denominator will cause an issue.  An integer division will
      result in an exception. */
      IO.writeLine("bad: 100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* FIX: test for a zero denominator */
      if (data != 0) {
        IO.writeLine("100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
      } else {
        IO.writeLine("This would result in a divide by zero");
      }
    }
  }
  private void good1() throws Throwable {

    String fn = ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\basic\\insecureDir";
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }

    /* FIX: explicitly set directory permissions */
    dir.setExecutable(false, true);
    dir.setReadable(true);
    dir.setWritable(false, true);
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  public void bad() throws Throwable {
    String data;

    /* We need to have one source outside of a for loop in order
    to prevent the Java compiler from generating an error because
    data is uninitialized */

    /* POTENTIAL FLAW: string is null */
    data = null;

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: hardcode string to non-null */
      data = "This is not null";
    }

    for (int for_index_j = 0; for_index_j < 1; for_index_j++) {
      /* POTENTIAL FLAW: null dereference will occur if data is null */
      IO.writeLine("" + data.length());
    }

    for (int for_index_k = 0; for_index_k < 0; for_index_k++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: validate that data is non-null */
      if (data != null) {
        IO.writeLine("" + data.length());
      } else {
        IO.writeLine("data is null");
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String data) throws Throwable {

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
      int rowCount =
          sqlStatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      IO.writeLine("Updated " + rowCount + " rows successfully.");
    } 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 Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
  /* goodB2G() - use badsource and goodsink by changing the conditions on
  the second and third for statements */
  private void goodB2G() throws Throwable {
    String data;

    /* POTENTIAL FLAW: string is null */
    data = null;

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: hardcode string to non-null */
      data = "This is not null";
    }

    for (int for_index_j = 0; for_index_j < 0; for_index_j++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* POTENTIAL FLAW: null dereference will occur if data is null */
      IO.writeLine("" + data.length());
    }

    for (int for_index_k = 0; for_index_k < 1; for_index_k++) {
      /* FIX: validate that data is non-null */
      if (data != null) {
        IO.writeLine("" + data.length());
      } else {
        IO.writeLine("data is null");
      }
    }
  }
  /* 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
         * but ensure data is inititialized before the Sink to avoid compiler errors */
        data = 0;
        break;
      default:
        /* 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:
        /* POTENTIAL FLAW: if data == Integer.MAX_VALUE, this will overflow */
        int result = (int) (data + 1);
        IO.writeLine("result: " + result);
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        IO.writeLine("Benign, fixed string");
        break;
    }
  }
  /* 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");
      }
    }
  }