/* 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_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);
      }
    }
  }
  /* 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]);
    }
  }
  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());
    }
  }
  /* 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.");
      }
    }
  }
Example #7
0
  /* Add a comment to an object description.		-CJS- */
  public static void scribe_object() {
    IntPointer item_val = new IntPointer();
    int j;
    String out_val, tmp_str;

    if (Treasure.inven_ctr > 0 || Treasure.equip_ctr > 0) {
      if (Moria1.get_item(item_val, "Which one? ", 0, Constants.INVEN_ARRAY_SIZE, "", "")) {
        tmp_str = Desc.objdes(Treasure.inventory[item_val.value()], true);
        out_val = String.format("Inscribing %s", tmp_str);
        IO.msg_print(out_val);
        if (!Treasure.inventory[item_val.value()].inscrip.isEmpty()) {
          out_val =
              String.format(
                  "Replace %s New inscription:", Treasure.inventory[item_val.value()].inscrip);
        } else {
          out_val = "Inscription: ";
        }
        j = 78 - tmp_str.length();
        if (j > 12) {
          j = 12;
        }
        IO.prt(out_val, 0, 0);
        if (!(out_val = IO.get_string(0, out_val.length(), j)).equals("")) {
          inscribe(Treasure.inventory[item_val.value()], out_val);
        }
      }
    } else {
      IO.msg_print("You are not carrying anything to inscribe.");
    }
  }
  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");
      }
    }
  }
  /* 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");
      }
    }
  }
  /* 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);
    }
  }
  /* 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");
      }
    }
  }
  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);
    }
  }
  /* 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");
      }
    }
  }
  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");
      }
    }
  }
Example #15
0
  /** Saves the displayed text. */
  private void save() {
    final BaseXFileChooser fc =
        new BaseXFileChooser(SAVE_AS, gui.gopts.get(GUIOptions.WORKPATH), gui).suffix(IO.XMLSUFFIX);

    final IO file = fc.select(Mode.FSAVE);
    if (file == null) return;
    gui.gopts.set(GUIOptions.WORKPATH, file.path());

    gui.cursor(CURSORWAIT, true);
    final MainOptions opts = gui.context.options;
    final int mh = opts.get(MainOptions.MAXHITS);
    opts.set(MainOptions.MAXHITS, -1);
    opts.set(MainOptions.CACHEQUERY, false);

    try (final PrintOutput out = new PrintOutput(file.toString())) {
      if (cmd != null) {
        cmd.execute(gui.context, out);
      } else if (ns != null) {
        ns.serialize(Serializer.get(out));
      } else {
        final byte[] txt = text.getText();
        for (final byte t : txt) if (t < 0 || t > ' ' || ws(t)) out.write(t);
      }
    } catch (final IOException ex) {
      BaseXDialog.error(gui, Util.info(FILE_NOT_SAVED_X, file));
    } finally {
      opts.set(MainOptions.MAXHITS, mh);
      opts.set(MainOptions.CACHEQUERY, true);
      gui.cursor(CURSORARROW, true);
    }
  }
  /* 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));
    }
  }
  /* 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.");
      }
    }
  }
  /* 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.");
      }
    }
  }
Example #19
0
 protected void assertTrue(final Boolean arg) {
   if (!(arg)) {
     IO.print("#Falso#\n");
   } else {
     IO.print("#Verdadeiro#\n");
   }
 }
  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");
      }
    }
  }
  /* 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);
      }
    }
  }
Example #22
0
  public static void testBump() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("p1");
      int size = project.getProperties().size();
      Version old = new Version(project.getProperty("Bundle-Version"));
      System.err.println("Old version " + old);
      project.bump("=+0");
      Version newv = new Version(project.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(old.getMajor(), newv.getMajor());
      assertEquals(old.getMinor() + 1, newv.getMinor());
      assertEquals(0, newv.getMicro());
      assertEquals(size, project.getProperties().size());
      assertEquals("sometime", newv.getQualifier());
    } finally {
      IO.deleteWithException(tmp);
    }
  }
Example #23
0
  static void reqListProperties(Client c) throws IOException {
    int foo, n;
    IO io = c.client;

    foo = io.readInt();
    Window w = c.lookupWindow(foo);
    c.length -= 2;
    if (w == null) {
      c.errorValue = foo;
      c.errorReason = 3; // BadWindow;
      return;
    }
    synchronized (io) {
      io.writeByte(1);
      Property p = w.getProperty();
      int i = 0;
      while (p != null) {
        i++;
        p = p.next;
      }

      io.writePad(1);
      io.writeShort(c.seq);
      io.writeInt(i);
      io.writeShort(i);
      io.writePad(22);

      p = w.getProperty();
      while (p != null) {
        io.writeInt(p.propertyName);
        p = p.next;
      }
      io.flush();
    }
  }
Example #24
0
  public static void testBumpIncludeFile() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-included");
      project.setTrace(true);
      Version old = new Version(project.getProperty("Bundle-Version"));
      assertEquals(new Version(1, 0, 0), old);
      project.bump("=+0");

      Processor processor = new Processor();
      processor.setProperties(project.getFile("include.txt"));

      Version newv = new Version(processor.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(1, newv.getMajor());
      assertEquals(1, newv.getMinor());
      assertEquals(0, newv.getMicro());
    } finally {
      IO.deleteWithException(tmp);
    }
  }
  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());
    }
  }
Example #26
0
  public static void testBumpSubBuilders() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-sub");
      project.setTrace(true);

      assertNull(project.getProperty("Bundle-Version"));

      project.bump("=+0");

      assertNull(project.getProperty("Bundle-Version"));

      for (Builder b : project.getSubBuilders()) {
        assertEquals(new Version(1, 1, 0), new Version(b.getVersion()));
      }
    } finally {
      IO.deleteWithException(tmp);
    }
  }
  /* 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);
      }
    }
  }
  /* 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;
    }
  }
  /* 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;
    }
  }
 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);
       }
     }
   }
 }