Beispiel #1
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);
    }
  }
  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);
    }
  }
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath());
    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4");
    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    BundleContext context = framework.getBundleContext();

    String[] bundles = {
      "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar",
      "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar",
      "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar"
    };

    for (String bundle : bundles) {
      String location = "reference:" + IO.getFile(bundle).toURI().toString();
      Bundle b = context.installBundle(location);
      if (!bundle.contains("slf4j-simple")) {
        b.start();
      }
    }

    super.setUp();
  }
  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);
    }
  }
  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);
    }
  }
Beispiel #6
0
  static void reqGetSelectionOwner(Client c) throws IOException {
    int foo;
    int selection;
    IO io = c.client;
    selection = io.readInt();

    c.length -= 2;

    if (!Atom.valid(selection)) {
      c.errorValue = selection;
      c.errorReason = 5; // BadAtom
      return;
    }

    synchronized (io) {
      io.writeByte(1);
      Selection s = getSelection(selection);
      io.writePad(1);
      io.writeShort(c.seq);
      io.writeInt(0);
      if (s != null) {
        io.writeInt(s.wid);
      } else {
        io.writeInt(0);
      }
      io.writePad(20);
      io.flush();
    }
  }
Beispiel #7
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();
    }
  }
  /* 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 (IO.static_t) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      File f = new File("C:\\data.txt");
      BufferedReader buffread = null;
      FileReader fread = null;
      try {
        /* read string from file into data */
        fread = new FileReader(f);
        buffread = new BufferedReader(fread);
        data = buffread.readLine(); // This will be reading the first "line" of the file, which
        // could be very long if there are little or no newlines in the file\
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } catch (NumberFormatException nfe) {
        log_bad.warning("Error with number parsing");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (fread != null) {
              fread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing fread");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      data = "Testing.test";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (IO.static_t) {
      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }
      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
  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 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 {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      URLConnection conn = (new URL("http://www.example.org/")).openConnection();
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        /* read input from URLConnection */
        instrread = new InputStreamReader(conn.getInputStream());
        buffread = new BufferedReader(instrread);
        data = buffread.readLine(); // This will be reading the first "line" of the response body,
        // which could be very long if there are no newlines in the HTML
      } 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");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      data = "Testing.test";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }

      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
  /* 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 (5 == 5) {
      data = "Testing.test";
    } 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 (5 == 5) {
      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }

      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
Beispiel #13
0
 private static void checkPackageInfoFiles(
     Project project, String packageName, boolean expectPackageInfo, boolean expectPackageInfoJava)
     throws Exception {
   File pkgInfo = IO.getFile(project.getSrc(), packageName + "/packageinfo");
   File pkgInfoJava = IO.getFile(project.getSrc(), packageName + "/package-info.java");
   assertEquals(expectPackageInfo, pkgInfo.exists());
   assertEquals(expectPackageInfoJava, pkgInfoJava.exists());
 }
Beispiel #14
0
 @Override
 public void delete(Project p) throws IOException {
   File root = p.getWorkspace().getFile("pom.xml");
   String rootPom = IO.collect(root);
   if (rootPom.contains(getTag(p))) {
     rootPom = rootPom.replaceAll("\n\\s*" + getTag(p) + "\\s*", "\n");
     IO.store(rootPom, root);
   }
 }
  /* goodG2B1() - use goodsource and badsink by changing the first switch to switch(5) */
  private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    switch (5) {
      case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        {
          /* POTENTIAL FLAW: sending login credentials information */
          data = "Your username is: user1\nYour password is: w8KNdsa9\n";
        }
        break;
      default:
        {
          /*FIX: send non-sensitive information */
          data = "The weather is San Diego is 75 and sunny";
        }
        break;
    }

    switch (7) {
      case 7:
        {
          PrintWriter out = null;
          try {
            out = response.getWriter();
            /* POTENTIAL FLAW: transmitting login credentials across a possibly non-SSL connection */
            out.println(data);
          } catch (IOException e) {
            IO.writeLine("There was a problem writing");
          } finally {
            if (out != null) {
              out.close();
            }
          }
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        {
          PrintWriter out = null;
          try {
            /* FIX: ensure the connection is secure */
            if (request.isSecure()) {
              out = response.getWriter();
              out.println(data);
            }
          } catch (IOException e) {
            IO.writeLine("There was a problem writing");
          } finally {
            if (out != null) {
              out.close();
            }
          }
        }
        break;
    }
  }
Beispiel #16
0
  /**
   * Scans an external ID.
   *
   * @param f full flag
   * @param r root flag
   * @return id
   * @throws IOException I/O exception
   */
  private byte[] externalID(final boolean f, final boolean r) throws IOException {
    byte[] cont = null;
    final boolean pub = consume(PUBLIC);
    if (pub || consume(SYSTEM)) {
      checkS();
      if (pub) {
        pubidLit();
        if (f) checkS();
      }
      final int qu = consume(); // [11]
      if (qu == '\'' || qu == '"') {
        int ch;
        final TokenBuilder tok = new TokenBuilder();
        while ((ch = nextChar()) != qu) tok.add(ch);
        if (!f) return null;
        final String name = string(tok.finish());
        if (!dtd && r) return cont;

        final XMLInput tin = input;
        try {
          final IO file = input.io().merge(name);
          cont = file.read();
        } catch (final IOException ex) {
          Util.debug(ex);
          // skip unknown DTDs/entities
          cont = new byte[] {'?'};
        }
        input = new XMLInput(new IOContent(cont, name));

        if (consume(XDECL)) {
          check(XML);
          s();
          if (version()) checkS();
          s();
          if (encoding() == null) error(TEXTENC);
          ch = nextChar();
          if (s(ch)) ch = nextChar();
          if (ch != '?') error(WRONGCHAR, '?', ch);
          ch = nextChar();
          if (ch != '>') error(WRONGCHAR, '>', ch);
          cont = Arrays.copyOfRange(cont, input.pos(), cont.length);
        }

        s();
        if (r) {
          extSubsetDecl();
          if (!consume((char) 0)) error(INVEND);
        }
        input = tin;
      } else {
        if (f) error(SCANQUOTE, (char) qu);
        prev(1);
      }
    }
    return cont;
  }
Beispiel #17
0
 /**
  * Parses a module.
  *
  * @param io input reference
  * @return query parser
  * @throws QueryException query exception
  */
 final QueryParser parseQuery(final IO io) throws QueryException {
   try (final QueryContext qctx = new QueryContext(qc)) {
     final String input = string(io.read());
     // parse query
     final QueryParser qp = new QueryParser(input, io.path(), qctx, null);
     module = QueryProcessor.isLibrary(input) ? qp.parseLibrary(true) : qp.parseMain();
     return qp;
   } catch (final IOException | QueryException ex) {
     throw IOERR_X.get(info, ex);
   }
 }
Beispiel #18
0
 @Override
 protected void tearDown() throws Exception {
   super.tearDown();
   framework.stop();
   IO.delete(tmp);
   Main.stop();
   IO.delete(IO.getFile("generated/cache"));
   IO.delete(IO.getFile("generated/storage"));
   framework.waitForStop(100000);
   super.tearDown();
 }
  /* good2() reverses the bodies in the if statement */
  private void good2() throws Throwable {
    if (IO.static_final_five == 5) {
      /* FIX: don't have those types of comments :) */
      IO.writeLine("This a test of the emergency broadcast system");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* FLAW: This is the suspicious comment */
      /* LATER: There is a bug at this location...I'm not sure why! */
      IO.writeLine("This a test of the emergency broadcast system");
    }
  }
  /** This method will process each argument and assign new varibles */
  public void processArgs(String[] args) {
    File file = null;
    Pattern pat = Pattern.compile("-[a-z]");
    for (int i = 0; i < args.length; i++) {
      String lcArg = args[i].toLowerCase();
      Matcher mat = pat.matcher(lcArg);
      if (mat.matches()) {
        char test = args[i].charAt(1);
        try {
          switch (test) {
            case 'f':
              file = new File(args[i + 1]);
              i++;
              break;
            case 'v':
              genomeVersion = args[i + 1];
              i++;
              break;
            case 's':
              sumScores = true;
              break;
            case 't':
              threshold = Float.parseFloat(args[++i]);
              break;
            case 'h':
              printDocs();
              System.exit(0);
            default:
              Misc.printExit("\nError, unknown option! " + mat.group());
          }
        } catch (Exception e) {
          System.out.print("\nSorry, something doesn't look right with this parameter: -" + test);
          System.out.println();
          System.exit(0);
        }
      }
    }
    if (file == null || file.exists() == false)
      Misc.printErrAndExit("Problem finding your bed files!\n");
    // pull files
    File[][] tot = new File[3][];
    tot[0] = IO.extractFiles(file, ".bed");
    tot[1] = IO.extractFiles(file, ".bed.zip");
    tot[2] = IO.extractFiles(file, ".bed.gz");
    bedFiles = IO.collapseFileArray(tot);
    if (bedFiles == null || bedFiles.length == 0)
      Misc.printErrAndExit("Problem finding your xxx.bed(.zip/.gz OK) files!\n");

    // genome version
    if (genomeVersion == null)
      Misc.printErrAndExit(
          "Please enter a genome version (e.g. H_sapiens_Mar_2006, see http://genome.ucsc.edu/FAQ/FAQreleases\n");
  }
Beispiel #21
0
  static void reqChangeProperty(Client c) throws IOException {
    int foo;
    byte mode;
    int prpty;
    byte frmt;
    int typ;
    int n;
    IO io = c.client;

    mode = (byte) c.data;
    if ((mode != PropModeReplace) && (mode != PropModeAppend) && (mode != PropModePrepend)) {
      // System.err.println("error!!");
      c.errorValue = mode;
      c.errorReason = 2; // BadValue;
    }

    n = c.length;
    ;
    foo = io.readInt();
    Window w = c.lookupWindow(foo);
    if (c.errorReason == 0 && w == null) {
      c.errorValue = foo;
      c.errorReason = 3; // BadWindow;
    }
    prpty = io.readInt();
    typ = io.readInt();
    frmt = (byte) io.readByte();
    if (c.errorReason == 0 && (frmt != 8) && (frmt != 16) && (frmt != 32)) {
      c.errorValue = frmt;
      c.errorReason = 3; // BadWindow;
    }
    io.readPad(3);
    foo = io.readInt();
    int totalSize = foo * (frmt / 8);
    byte[] bar = null;
    if (totalSize > 0) {
      bar = new byte[totalSize];
      io.readByte(bar, 0, totalSize);
      if (c.swap) {
        switch (frmt) {
          case 16:
            swapS(bar, 0, totalSize);
            break;
          case 32:
            swapL(bar, 0, totalSize);
            break;
          default:
        }
      }
      io.readPad((-totalSize) & 3);
    }
    c.length = 0;
    if (c.errorReason != 0) {
      return;
    }
    changeWindowProperty(c, w, prpty, typ, frmt, mode, foo, bar, true);
  }
  /** This method will process each argument and assign new varibles */
  public void processArgs(String[] args) {
    Pattern pat = Pattern.compile("-[a-z]");
    File dir = null;
    for (int i = 0; i < args.length; i++) {
      String lcArg = args[i].toLowerCase();
      Matcher mat = pat.matcher(lcArg);
      if (mat.matches()) {
        char test = args[i].charAt(1);
        try {
          switch (test) {
            case 'f':
              dir = new File(args[i + 1]);
              i++;
              break;
            case 'v':
              genomeVersion = args[i + 1];
              i++;
              break;
            case 's':
              strand = args[++i];
              break;
            case 't':
              stairStep = true;
              break;
            case 'h':
              printDocs();
              System.exit(0);
            default:
              Misc.printExit("\nError: unknown option! " + mat.group());
          }
        } catch (Exception e) {
          Misc.printExit(
              "\nSorry, something doesn't look right with this parameter: -" + test + "\n");
        }
      }
    }
    if (dir == null || dir.canRead() == false)
      Misc.printExit("\nError: cannot find or read your sgr file/ directory.\n");
    File[][] tot = new File[3][];
    tot[0] = IO.extractFiles(dir, ".sgr");
    tot[1] = IO.extractFiles(dir, ".sgr.zip");
    tot[2] = IO.extractFiles(dir, ".sgr.gz");
    sgrFiles = IO.collapseFileArray(tot);

    if (sgrFiles == null || sgrFiles.length == 0)
      Misc.printExit("\nError: cannot find your xxx.sgr.zip file(s)");
    if (genomeVersion == null)
      Misc.printExit(
          "\nError: you must supply a genome version. Goto http://genome.ucsc.edu/cgi-"
              + "bin/hgGateway load your organism to find the associated genome version.\n");
  }
  /* good2() reverses the bodies in the if statement */
  private void good2() throws Throwable {
    if (IO.static_returns_t()) {
      /* FIX: use SecureRandom to be cryptographically secure */
      SecureRandom rand = new SecureRandom();
      IO.writeLine("Random int: " + rand.nextInt(100));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Random rand = new Random();
      /* FLAW: seed is static, making the numbers always occur in the same sequence */
      rand.setSeed(123456);
      IO.writeLine("Random int: " + rand.nextInt(100));
    }
  }
Beispiel #24
0
  static void reqSetSelectionOwner(Client c) throws IOException {
    int foo;
    int selection;
    IO io = c.client;
    foo = io.readInt();
    c.length -= 2;
    Window w = null;
    if (foo != 0) {
      w = c.lookupWindow(foo);
      if (w == null) {
        c.errorValue = foo;
        c.errorReason = 3; // BadWindow
        return;
      }
    }

    selection = io.readInt();
    foo = io.readInt();
    c.length -= 2;
    int time = 0;
    time = (int) System.currentTimeMillis();
    time = foo; // ??

    if (Atom.valid(selection)) {
      int i = 0;
      Selection s = getSelection(selection);
      if (s != null) {
        if (s.client != null && (w == null || (s.client != c))) {
          if (s.client != null) {
            c.cevent.mkSelectionClear(time, s.wid, s.selection);
            s.client.sendEvent(c.cevent, 1, Event.NoEventMask, Event.NoEventMask, null);
          }
        }
        s.window = w;
        s.wid = (w != null ? w.id : 0);
        s.lastTimeChanged = time;
        s.client = (w != null ? c : null);
      } else {
        // System.out.println("add");
        addSelection(selection, time, w, c);
      }
      return;
    } else {
      c.errorValue = selection;
      c.errorReason = 5;
      return;
    }
  }
Beispiel #25
0
 public static byte[] input(String fileName) {
   try {
     return input(Files.newInputStream(IO.path(fileName)));
   } catch (IOException e) {
     return Exceptions.handle(byte[].class, e);
   }
 }
Beispiel #26
0
  private void copy(File workspaceDir, InputStream in, Pattern glob, boolean overwrite)
      throws Exception {

    Jar jar = new Jar("dot", in);
    try {
      for (Entry<String, Resource> e : jar.getResources().entrySet()) {

        String path = e.getKey();
        bnd.trace("path %s", path);

        if (glob != null && !glob.matcher(path).matches()) continue;

        Resource r = e.getValue();
        File dest = Processor.getFile(workspaceDir, path);
        if (overwrite
            || !dest.isFile()
            || dest.lastModified() < r.lastModified()
            || r.lastModified() <= 0) {

          bnd.trace("copy %s to %s", path, dest);

          File dp = dest.getParentFile();
          if (!dp.exists() && !dp.mkdirs()) {
            throw new IOException("Could not create directory " + dp);
          }

          IO.copy(r.openInputStream(), dest);
        }
      }
    } finally {
      jar.close();
    }
  }
Beispiel #27
0
  /**
   * Stores the specified source to the specified file.
   *
   * @param in input source
   * @param file target file
   * @throws IOException I/O exception
   */
  public static void store(final InputSource in, final IOFile file) throws IOException {
    // add directory if it does not exist anyway
    file.dir().md();

    final PrintOutput po = new PrintOutput(file.path());
    try {
      final Reader r = in.getCharacterStream();
      final InputStream is = in.getByteStream();
      final String id = in.getSystemId();
      if (r != null) {
        for (int c; (c = r.read()) != -1; ) po.utf8(c);
      } else if (is != null) {
        for (int b; (b = is.read()) != -1; ) po.write(b);
      } else if (id != null) {
        final BufferInput bi = new BufferInput(IO.get(id));
        try {
          for (int b; (b = bi.read()) != -1; ) po.write(b);
        } finally {
          bi.close();
        }
      }
    } finally {
      po.close();
    }
  }
Beispiel #28
0
  /**
   * System command. Execute a command and insert the result.
   *
   * @param args
   * @param help
   * @param patterns
   * @param low
   * @param high
   */
  public String system_internal(boolean allowFail, String args[]) throws Exception {
    verifyCommand(
        args,
        "${"
            + (allowFail ? "system-allow-fail" : "system")
            + ";<command>[;<in>]}, execute a system command",
        null,
        2,
        3);
    String command = args[1];
    String input = null;

    if (args.length > 2) {
      input = args[2];
    }

    Process process = Runtime.getRuntime().exec(command, null, domain.getBase());
    if (input != null) {
      process.getOutputStream().write(input.getBytes("UTF-8"));
    }
    process.getOutputStream().close();

    String s = IO.collect(process.getInputStream(), "UTF-8");
    int exitValue = process.waitFor();
    if (exitValue != 0) return exitValue + "";

    if (!allowFail && (exitValue != 0)) {
      domain.error("System command " + command + " failed with " + exitValue);
    }
    return s.trim();
  }
 public void bad() throws Throwable {
   if (IO.staticReturnsTrue()) {
     String stringIntValue = "";
     int x = (new SecureRandom()).nextInt(3);
     switch (x) {
       case 0:
         stringIntValue = "0";
         break;
       case 1:
         stringIntValue = "1";
         break;
         /* FLAW: x could be 2, and there is no 'default' case for that */
     }
     IO.writeLine(stringIntValue);
   }
 }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2() throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* init data */
      /* FIX: Read data from the console using readLine() */
      try {
        InputStreamReader readerInputStream = new InputStreamReader(System.in, "UTF-8");
        BufferedReader readerBuffered = new BufferedReader(readerInputStream);
        /* POTENTIAL FLAW: Read data from the console using readLine */
        data = readerBuffered.readLine();
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
      }
      /* NOTE: Tools may report a flaw here because readerBuffered and readerInputStream are not closed.  Unfortunately, closing those will close System.in, which will cause any future attempts to read from the console to fail and throw an exception */
    } 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 (data != null) {
      KerberosPrincipal principal = new KerberosPrincipal("test");
      /* POTENTIAL FLAW: data used as password in KerberosKey() */
      KerberosKey key = new KerberosKey(principal, data.toCharArray(), null);
      IO.writeLine(key.toString());
    }
  }