/* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_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");

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

    String root = "C:\\uploads\\";
    /* POTENTIAL FLAW: no validation of concatenated value */
    File fIn = new File(root + data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
Exemplo n.º 2
0
  private void _loadConfig() {
    try {

      _configScope.set("__instance__", this);

      _loadConfigFromCloudObject(getSiteObject());
      _loadConfigFromCloudObject(getEnvironmentObject());

      File f;
      if (!_admin) {
        f = getFileSafe("_config.js");
        if (f == null || !f.exists()) f = getFileSafe("_config");
      } else
        f =
            new File(
                Module.getModule("core-modules/admin").getRootFile(getVersionForLibrary("admin")),
                "_config.js");

      _libraryLogger.info("config file [" + f + "] exists:" + f.exists());

      if (f == null || !f.exists()) return;

      Convert c = new Convert(f);
      JSFunction func = c.get();
      func.setUsePassedInScope(true);
      func.call(_configScope);

      _logger.debug("config things " + _configScope.keySet());
    } catch (Exception e) {
      throw new RuntimeException("couldn't load config", e);
    }
  }
Exemplo n.º 3
0
  /**
   * Maps a servlet-like URI to a jxp file.
   *
   * @param f File to check
   * @return new File with <root>.jxp if exists, orig file if not
   * @example /wiki/geir -> maps to wiki.jxp if exists
   */
  File tryServlet(File f) {
    if (f.exists()) return f;

    String uri = f.toString();

    if (uri.startsWith(_rootFile.toString())) uri = uri.substring(_rootFile.toString().length());

    if (_core != null && uri.startsWith(_core._base.toString()))
      uri = "/~~" + uri.substring(_core._base.toString().length());

    while (uri.startsWith("/")) uri = uri.substring(1);

    int start = 0;
    while (true) {

      int idx = uri.indexOf("/", start);
      if (idx < 0) break;
      String foo = uri.substring(0, idx);

      File temp = getFileSafe(foo + ".jxp");

      if (temp != null && temp.exists()) f = temp;

      start = idx + 1;
    }

    return f;
  }
Exemplo n.º 4
0
  /**
   * Tries to find the given file, assuming that it's missing the ".jxp" extension
   *
   * @param f File to check
   * @return same file if not found to be missing the .jxp, or a new File w/ the .jxp appended
   */
  File tryNoJXP(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    File temp = new File(f.toString() + ".jxp");
    return temp.exists() ? temp : f;
  }
  /* use badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data = bad_source(request, response);

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
Exemplo n.º 6
0
  /**
   * Returns the index.jxp for the File argument if it's an existing directory, and the index.jxp
   * file exists
   *
   * @param f directory to check
   * @return new File for index.jxp in that directory, or same file object if not
   */
  File tryIndex(File f) {

    if (!(f.isDirectory() && f.exists())) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f, "index" + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
Exemplo n.º 7
0
  File tryOtherExtensions(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f.toString() + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
Exemplo n.º 8
0
  JxpSource getSource(File f) throws IOException {

    if (DEBUG) System.err.println("getSource\n\t " + f);

    File temp = _findFile(f);

    if (DEBUG) System.err.println("\t " + temp);

    if (!temp.exists()) return handleFileNotFound(f);

    //  if it's a directory (and we know we can't find the index file)
    //  TODO : at some point, do something where we return an index for the dir?
    if (temp.isDirectory()) return null;

    // if we are at init time, save it as an initializaiton file
    loadedFile(temp);

    // Ensure that this is w/in the right tree for the context
    if (_localObject != null && _localObject.isIn(temp)) return _localObject.getSource(temp);

    // if not, is it core?
    if (_core.isIn(temp)) return _core.getSource(temp);

    throw new RuntimeException("what?  can't find:" + f);
  }
  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());
    }
  }
  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());
    }
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;

    /* get environment variable ADD */
    /* POTENTIAL FLAW: Read data from an environment variable */
    data = System.getenv("ADD");

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data) throws Throwable {

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data) throws Throwable {

    String root = "C:\\uploads\\";
    /* POTENTIAL FLAW: no validation of concatenated value */
    File fIn = new File(root + data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
Exemplo n.º 14
0
 public static boolean copyDir(String fromDir, String toDir) throws IOException {
   File contentFile = new File(toDir + ".INIT");
   if (!contentFile.exists()) {
     IO.copyDirTree(fromDir, toDir);
     contentFile.createNewFile();
     return true;
   }
   return false;
 }
Exemplo n.º 15
0
  /**
   * return OutputStream of JasperReport object, this page could only be viewed from localhost for
   * security concern. parameter can be (id), or (table and type)
   *
   * @param id - report id, or
   * @param table - table name
   * @param type - reporttype "s","l","o", case insensitive
   * @param client(*) - client domain
   * @param version - version number, default to -1
   */
  public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String clientName = request.getParameter("client");
    int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1);
    if (objectId == -1) {
      // try using table and type
      objectId =
          getReportId(clientName, request.getParameter("table"), request.getParameter("type"));
    }
    if (objectId == -1) {
      logger.error("report not found, request is:" + Tools.toString(request));
      throw new NDSException("report not found");
    }
    int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1);
    File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName));
    if (reportXMLFile.exists()) {
      // generate jasperreport if file not exists or not newer
      String reportName =
          reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf("."));
      File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper");
      if (!reportJasperFile.exists()
          || reportJasperFile.lastModified() < reportXMLFile.lastModified()) {
        JasperCompileManager.compileReportToFile(
            reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath());
      }
      InputStream is = new FileInputStream(reportJasperFile);
      response.setContentType("application/octetstream;");
      response.setContentLength((int) reportJasperFile.length());

      // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\"");
      ServletOutputStream os = response.getOutputStream();

      byte[] b = new byte[8192];
      int bInt;
      while ((bInt = is.read(b, 0, b.length)) != -1) {
        os.write(b, 0, bInt);
      }
      is.close();
      os.flush();
      os.close();
    } else {
      throw new NDSException("Not found report template");
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing 5==5 to 5!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (5 != 5) {
      /* 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;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateTrue) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } 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;
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Exemplo n.º 18
0
  private void _runInitFile(File f) throws IOException {
    if (f == null) return;

    if (!f.exists()) return;

    _initFlies.add(f);
    JxpSource s = getSource(f);
    JSFunction func = s.getFunction();
    func.setUsePassedInScope(true);
    func.call(_initScope);
  }
Exemplo n.º 19
0
 public URL getResource(String path) {
   try {
     File f = getFile(path);
     if (!f.exists()) return null;
     return f.toURL();
   } catch (FileNotFoundException fnf) {
     // the spec says to return null if we can't find it
     // even though this is weird...
     return null;
   } catch (IOException ioe) {
     throw new RuntimeException("error opening [" + path + "]", ioe);
   }
 }
Exemplo n.º 20
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param servlet called from here
   * @param req the request
   * @param res the response
   * @param file to serve
   * @param contentType content type, if null, will try to guess
   * @throws IOException on write error
   */
  public static void returnFile(
      HttpServlet servlet,
      HttpServletRequest req,
      HttpServletResponse res,
      File file,
      String contentType)
      throws IOException {

    // No file, nothing to view
    if (file == null) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // check that it exists
    if (!file.exists()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // not a directory
    if (!file.isFile()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0));
      res.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // Set the type of the file
    String filename = file.getPath();
    if (null == contentType) {
      if (filename.endsWith(".html")) contentType = "text/html; charset=iso-8859-1";
      else if (filename.endsWith(".xml")) contentType = "text/xml; charset=iso-8859-1";
      else if (filename.endsWith(".txt") || (filename.endsWith(".log"))) contentType = CONTENT_TEXT;
      else if (filename.indexOf(".log.") > 0) contentType = CONTENT_TEXT;
      else if (filename.endsWith(".nc")) contentType = "application/x-netcdf";
      else contentType = servlet.getServletContext().getMimeType(filename);

      if (contentType == null) contentType = "application/octet-stream";
    }

    returnFile(req, res, file, contentType);
  }
Exemplo n.º 21
0
  public static boolean saveFile(
      HttpServlet servlet,
      String contentPath,
      String path,
      HttpServletRequest req,
      HttpServletResponse res) {

    // @todo Need to use logServerAccess() below here.
    boolean debugRequest = Debug.isSet("SaveFile");
    if (debugRequest) log.debug(" saveFile(): path= " + path);

    String filename = contentPath + path; // absolute path
    File want = new File(filename);

    // backup current version if it exists
    int version = getBackupVersion(want.getParent(), want.getName());
    String fileSave = filename + "~" + version;
    File file = new File(filename);
    if (file.exists()) {
      try {
        IO.copyFile(filename, fileSave);
      } catch (IOException e) {
        log.error(
            "saveFile(): Unable to save copy of file "
                + filename
                + " to "
                + fileSave
                + "\n"
                + e.getMessage());
        return false;
      }
    }

    // save new file
    try {
      OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
      IO.copy(req.getInputStream(), out);
      out.close();
      if (debugRequest) log.debug("saveFile(): ok= " + filename);
      res.setStatus(HttpServletResponse.SC_CREATED);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1));
      return true;
    } catch (IOException e) {
      log.error(
          "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage());
      return false;
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String dataArray[]) throws Throwable {
    String data = dataArray[2];

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink by changing the "if" so that
  both branches use the GoodSource */
  private void goodG2B() throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2() throws Throwable {
    String data;
    if (IO.static_five == 5) {
      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 */

      /* retrieve the property */
      Properties props = new Properties();
      FileInputStream finstr = null;
      try {
        finstr = new FileInputStream("../common/config.properties");
        props.load(finstr);

        data = props.getProperty("data");
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (finstr != null) {
            finstr.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        }
      }
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing 5==5 to 5!=5 */
  private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (5 != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from request */
      data = request.getParameter("name");
    } else {

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    String root = "C:\\uploads\\";
    /* POTENTIAL FLAW: no validation of concatenated value */
    File fIn = new File(root + data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
Exemplo n.º 26
0
  private static int getBackupVersion(String dirName, String fileName) {
    int maxN = 0;
    File dir = new File(dirName);
    if (!dir.exists()) return -1;

    String[] files = dir.list();
    if (null == files) return -1;

    for (String name : files) {
      if (name.indexOf(fileName) < 0) continue;
      int pos = name.indexOf('~');
      if (pos < 0) continue;
      String ver = name.substring(pos + 1);
      int n = 0;
      try {
        n = Integer.parseInt(ver);
      } catch (NumberFormatException e) {
        log.error("Format Integer error on backup filename= " + ver);
      }
      maxN = Math.max(n, maxN);
    }
    return maxN + 1;
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (5 == 5) {
      data = ""; /* Initialize data */
      /* Read data using an outbound tcp connection */
      {
        Socket socket = null;
        BufferedReader readerBuffered = null;
        InputStreamReader readerInputStream = null;
        try {
          /* Read data using an outbound tcp connection */
          socket = new Socket("host.example.org", 39544);
          /* read input from socket */
          readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data using an outbound tcp connection */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* clean up stream reading objects */
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          /* clean up socket objects */
          try {
            if (socket != null) {
              socket.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO);
          }
        }
      }
    } else {
      /* 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;
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateReturnsTrue()) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } 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;
    }

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* uses badsource and badsink - see how tools report flaws that don't always occur */
  public void bad() throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      data = ""; /* Initialize data */
      /* Read data from a database */
      {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
          /* setup the connection */
          connection = IO.getDBConnection();
          /* prepare and execute a (hardcoded) query */
          preparedStatement = connection.prepareStatement("select name from users where id=0");
          resultSet = preparedStatement.executeQuery();
          /* POTENTIAL FLAW: Read data from a database query resultset */
          data = resultSet.getString(1);
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql);
        } finally {
          /* Close database objects */
          try {
            if (resultSet != null) {
              resultSet.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
          }

          try {
            if (preparedStatement != null) {
              preparedStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
          }

          try {
            if (connection != null) {
              connection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink by changing the "if" so that
   * both branches use the GoodSource */
  private void goodG2B() throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }