/**
   * Load the class with the specified name, searching using the following algorithm until it finds
   * and returns the class. If the class cannot be found, returns <code>ClassNotFoundException
   * </code>.
   *
   * <ul>
   *   <li>Call <code>findLoadedClass(String)</code> to check if the class has already been loaded.
   *       If it has, the same <code>Class</code> object is returned.
   *   <li>If the <code>delegate</code> property is set to <code>true</code>, call the <code>
   *       loadClass()</code> method of the parent class loader, if any.
   *   <li>Call <code>findClass()</code> to find this class in our locally defined repositories.
   *   <li>Call the <code>loadClass()</code> method of our parent class loader, if any.
   * </ul>
   *
   * If the class was found using the above steps, and the <code>resolve</code> flag is <code>true
   * </code>, this method will then call <code>resolveClass(Class)</code> on the resulting Class
   * object.
   *
   * @param name Name of the class to be loaded
   * @param resolve If <code>true</code> then resolve the class
   * @exception ClassNotFoundException if the class was not found
   */
  public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {

    Class clazz = null;

    // (0) Check our previously loaded class cache
    clazz = findLoadedClass(name);
    if (clazz != null) {
      if (resolve) resolveClass(clazz);
      return (clazz);
    }

    // (.5) Permission to access this class when using a SecurityManager
    int dot = name.lastIndexOf('.');
    if (System.getSecurityManager() != null) {
      if (dot >= 0) {
        try {
          securityManager.checkPackageAccess(name.substring(0, dot));
        } catch (SecurityException se) {
          String error = "Security Violation, attempt to use " + "Restricted Class: " + name;
          System.out.println(error);
          throw new ClassNotFoundException(error);
        }
      }
    }

    // Class is in a package, delegate to thread context class loader
    if (!name.startsWith(Constants.JSP_PACKAGE_NAME)) {
      ClassLoader classLoader = null;
      if (System.getSecurityManager() != null) {
        classLoader = (ClassLoader) AccessController.doPrivileged(privLoadClass);
      } else {
        classLoader = Thread.currentThread().getContextClassLoader();
      }
      clazz = classLoader.loadClass(name);
      if (resolve) resolveClass(clazz);
      return clazz;
    }

    // Only load classes for this JSP page
    if (name.startsWith(className)) {
      String classFile = name.substring(Constants.JSP_PACKAGE_NAME.length() + 1) + ".class";
      byte[] cdata = loadClassDataFromFile(classFile);
      if (cdata == null) throw new ClassNotFoundException(name);
      if (System.getSecurityManager() != null) {
        ProtectionDomain pd = new ProtectionDomain(codeSource, permissionCollection);
        clazz = defineClass(name, cdata, 0, cdata.length, pd);
      } else {
        clazz = defineClass(name, cdata, 0, cdata.length);
      }
      if (clazz != null) {
        if (resolve) resolveClass(clazz);
        return clazz;
      }
    }

    throw new ClassNotFoundException(name);
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (privateTrue) {
      /* get system property user.home */
      /* POTENTIAL FLAW: Read data from a system property */
      data = System.getProperty("user.home");
    } 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 osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
  /* 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.staticReturnsTrueOrFalse()) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {

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

    if (IO.staticReturnsTrueOrFalse()) {
      if (data != null) {
        /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
        data = URLEncoder.encode(data, "UTF-8");
        response.setHeader("Location", "/author.jsp?lang=" + data);
      }
    } else {

      if (data != null) {
        /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
        data = URLEncoder.encode(data, "UTF-8");
        response.setHeader("Location", "/author.jsp?lang=" + data);
      }
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String strCallResult = "";
    resp.setContentType("text/plain");

    String strId = req.getParameter("id");
    String strCount = req.getParameter("count");
    int id = -1;
    int count = -1;
    try {
      id = Integer.valueOf(strId);
      count = Integer.valueOf(strCount);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }

    try {

      TopsCalculator.getTopUrlsForDay();
      TopsCalculator.getTopUrlsForMonth();
      TopsCalculator.getTopUrlsForYear();
      TopsCalculator.getTopHostsForDay();
      TopsCalculator.getTopHostsForMonth();
      TopsCalculator.getTopHostsForYear();

      if (id == 0) {
        DbHelper.setStartTime(System.currentTimeMillis());
      } else if (id == count - 1) {
        DbHelper.setRunTime(System.currentTimeMillis() - DbHelper.getStartTime());
      }

    } catch (Exception ex) {
      strCallResult = "FAIL: Fetching top lists";
      System.out.println(strCallResult);
    }
  }
Exemple #5
0
  // Velocity init
  public static void initVelocity() {
    if (velocityCatch == null) {
      System.out.println("init VM");
      velocityCatch = new Object();

      Properties props = new Properties();
      props.setProperty("input.encoding", "UTF-8");
      props.setProperty("output.encoding", "UTF-8");

      if (getConfig().getChild("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", getConfig().getChildText("vmtemplatepath"));
      }
      if (System.getProperty("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", System.getProperty("vmtemplatepath"));
        // Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
        // System.getProperty("vmtemplatepath"));//oder new FIle()?
      }
      System.out.println("vmtemplatepath=" + props.getProperty("vmtemplatepath"));
      try {
        Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, VeloLog.getInstance());
        Velocity.init(props);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
  /* 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);
          }
        }
      }
    }
  }
 // For war agent needs to be switched on
 private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
   // Check for system props, system env and agent config
   boolean sysProp =
       System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
   boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
   boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
   return sysProp || env || config;
 }
 // Try to find an URL for system props or config
 private String findAgentUrl(Configuration pConfig) {
   // System property has precedence
   String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
   if (url == null) {
     url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
     if (url == null) {
       url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
     }
   }
   return NetworkUtil.replaceExpression(url);
 }
  public void init(FilterConfig config) throws ServletException {

    Log log = LogFactory.getLog(this.getClass());
    log.info("PsqStoreConfigFilter: init(config) called");

    String path = "";

    try {
      URL pathUrl = config.getServletContext().getResource("/");

      path = new File(config.getServletContext().getRealPath("/")).getAbsolutePath();

      log.info(" protocol=" + pathUrl.getProtocol());
      log.info(" path=" + path);

    } catch (Exception ex) {
      ex.printStackTrace();
    }

    if (config.getInitParameter("derby-home") != null) {

      String myHome = config.getInitParameter("derby-home");
      if (!myHome.startsWith("/")) {
        myHome = path + File.separator + myHome;
      }

      log.info("derby-home(final)=" + myHome);
      System.setProperty("xpsq.derby.home", myHome);

      if (PsqContext.getStore("derby") != null) {
        PsqContext.getStore("derby").initialize();
      }
    }

    if (config.getInitParameter("bdb-home") != null) {

      String myHome = config.getInitParameter("bdb-home");
      if (!myHome.startsWith("/")) {
        myHome = path + File.separator + myHome;
      }

      log.info("bdb-home(final)=" + myHome);
      System.setProperty("xpsq.bdb.home", myHome);

      if (PsqContext.getStore("bdb") != null) {
        PsqContext.getStore("bdb").initialize();
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second privateReturnsTrue() to privateReturnsFalse() */
  private void goodB2G1() throws Throwable {
    String data;
    if (privateReturnsTrue()) {
      /* get system property user.home */
      /* POTENTIAL FLAW: Read data from a system property */
      data = System.getProperty("user.home");
    } 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 (privateReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      String xmlFile = null;
      if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        /* running on Windows */
        xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml";
      } else {
        /* running on non-Windows */
        xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml";
      }

      if (data != null) {
        /* assume username||password as source */
        String[] tokens = data.split("||");
        if (tokens.length < 2) {
          return;
        }
        /* FIX: validate input using StringEscapeUtils */
        String username = StringEscapeUtils.escapeXml(tokens[0]);
        String password = StringEscapeUtils.escapeXml(tokens[1]);
        /* build xpath */
        XPath xPath = XPathFactory.newInstance().newXPath();
        InputSource inputXml = new InputSource(xmlFile);
        String query =
            "//users/user[name/text()='"
                + username
                + "' and pass/text()='"
                + password
                + "']"
                + "/secret/text()";
        String secret = (String) xPath.evaluate(query, inputXml, XPathConstants.STRING);
      }
    }
  }
  public void bad() throws Throwable {
    int data;
    if (IO.staticReturnsTrue()) {
      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.staticReturnsTrue()) {
      /* POTENTIAL FLAW: if data == Integer.MIN_VALUE, this will overflow */
      int result = (int) (data - 1);
      IO.writeLine("result: " + result);
    }
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    int dataCopy;
    {
      int data;

      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);
        }
      }

      dataCopy = data;
    }
    {
      int data = dataCopy;

      /* POTENTIAL FLAW: Create a HashMap using data as the initial size.  data may be very large, creating memory issues */
      HashMap intHashMap = new HashMap(data);
    }
  }
  /* goodG2B() - use goodsource and badsink by changing the conditions on the first and second while statements */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    boolean local_f = false;

    while (true) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      /* get environment variable ADD */
      data = System.getenv("ADD");
      break;
    }

    while (true) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
      break;
    }
  }
  /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch  */
  private void goodB2G2() throws Throwable {
    String data;

    switch (6) {
      case 6:
        /* POTENTIAL FLAW: data may be set to null */
        data = System.getProperty("CWE690");
        break;
      default:
        /* 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;
        break;
    }

    switch (7) {
      case 7:
        /* FIX: call equals() on string literal (that is not null) */
        if ("CWE690".equals(data)) {
          IO.writeLine("data is CWE690");
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        IO.writeLine("Benign, fixed string");
        break;
    }
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    int data;
    if (IO.staticReturnsTrue()) {
      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.staticReturnsTrue()) {
      /* FIX: Add a check to prevent an overflow from occurring */
      if (data > Integer.MIN_VALUE) {
        int result = (int) (data - 1);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too small to perform subtraction.");
      }
    }
  }
  public void bad() throws Throwable {
    String data;

    switch (6) {
      case 6:
        /* POTENTIAL FLAW: data may be set to null */
        data = System.getProperty("CWE690");
        break;
      default:
        /* 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;
        break;
    }

    switch (7) {
      case 7:
        /* POTENTIAL FLAW: data could be null */
        if (data.equals("CWE690")) {
          IO.writeLine("data is CWE690");
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        IO.writeLine("Benign, fixed string");
        break;
    }
  }
  public void action(String data) throws Throwable {

    String xmlFile = null;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml";
    } else {
      /* running on non-Windows */
      xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml";
    }

    if (data != null) {
      /* assume username||password as source */
      String[] tokens = data.split("||");
      if (tokens.length < 2) {
        return;
      }
      String username = tokens[0];
      String password = tokens[1];
      /* build xpath */
      XPath xPath = XPathFactory.newInstance().newXPath();
      InputSource inputXml = new InputSource(xmlFile);
      /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
       *     The user input should be canonicalized before validation. */
      /* POTENTIAL FLAW: user input is used without validate */
      String query =
          "//users/user[name/text()='"
              + username
              + "' and pass/text()='"
              + password
              + "']"
              + "/secret/text()";
      String secret = (String) xPath.evaluate(query, inputXml, XPathConstants.STRING);
    }
  }
  public void bad() throws Throwable {
    int data;
    if (PRIVATE_STATIC_FINAL_FIVE == 5) {
      data = Integer.MIN_VALUE; /* Initialize data */
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      {
        String stringNumber = System.getenv("ADD");
        if (stringNumber != null) // avoid NPD incidental warnings
        {
          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 (PRIVATE_STATIC_FINAL_FIVE == 5) {
      if (data < 0) /* ensure we won't have an overflow */ {
        /* POTENTIAL FLAW: if (data * 2) < Integer.MIN_VALUE, this will underflow */
        int result = (int) (data * 2);
        IO.writeLine("result: " + result);
      }
    }
  }
  public static void main(String[] args) throws Exception {

    Server server = new Server(Integer.valueOf(System.getenv("PORT")));
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(
        new ServletHolder(
            new HttpServlet() {
              protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
                resp.getWriter()
                    .print(
                        "<h1>umlet-github web service</h1>"
                            + "<p>"
                            + "<a href=\"https://github.com/CalumJEadie/umlet-github/\">"
                            + "https://github.com/CalumJEadie/umlet-github/"
                            + "</a>"
                            + "</p>");
              }
            }),
        "/");

    context.addServlet(new ServletHolder(new UmletGithub()), "/convert/uxf/svg/");

    server.start();
    server.join();
  }
  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");
      }
    }
  }
 /**
  * Writes a log message.
  *
  * @param str strings to be written
  * @param time add performance info
  */
 public void log(final boolean time, final Object... str) {
   final Object[] obj = new Object[str.length + (time ? 2 : 1)];
   obj[0] = remote();
   System.arraycopy(str, 0, obj, 1, str.length);
   if (time) obj[obj.length - 1] = perf.toString();
   context.log.write(obj);
 }
  private int bad_source() throws Throwable {
    int data;

    if (badPrivate) {
      data = Integer.MIN_VALUE; /* Initialize data */
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      {
        String stringNumber = System.getenv("ADD");
        if (stringNumber != null) // avoid NPD incidental warnings
        {
          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;
    }

    return data;
  }
  /* goodG2B1() - use goodsource and badsink by changing privateTrue to privateFalse */
  private void goodG2B1() throws Throwable {
    String data;
    if (privateFalse) {
      /* 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";
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
  public void bad() throws Throwable {
    int data;

    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);
      }
    }

    /* 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: Attempt to write to array at location data, which may be outside the array bounds */
    array[data] = 42;

    /* Skip reading back data from array since that may be another out of bounds operation */

  }
  public void bad() throws Throwable {
    int data;
    if (privateReturnsTrue()) {
      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 (privateReturnsTrue()) {
      /* 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: Attempt to read from array at location data, which may be outside the array bounds */
      IO.writeLine(array[data]);
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2() throws Throwable {
    String data;
    if (IO.static_returns_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 */

      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");
          }
        }
      }
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process p = Runtime.getRuntime().exec(osCommand + data);
    p.waitFor();
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G() throws Throwable {
    int data;

    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);
      }
    }

    /* Need to ensure that the array is of size > 3  and < 101 due to the GoodSource and the large_fixed BadSource */
    int array[] = {0, 1, 2, 3, 4};

    /* FIX: Verify index before writing to array at location data */
    if (data >= 0 && data < array.length) {
      array[data] = 42;
    } else {
      IO.writeLine("Array index out of bounds");
    }
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;

    /* get system property user.home */
    /* POTENTIAL FLAW: Read data from a system property */
    data = System.getProperty("user.home");

    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);
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
  private void goodB2G1() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_FIVE == 5) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

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

      if (data != null) {
        String names[] = data.split("-");
        int successCount = 0;
        Connection dbConnection = null;
        PreparedStatement sqlStatement = null;
        try {
          /* FIX: Use prepared statement and executeBatch (properly) */
          dbConnection = IO.getDBConnection();
          sqlStatement =
              dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?");
          for (int i = 0; i < names.length; i++) {
            sqlStatement.setString(1, names[i]);
            sqlStatement.addBatch();
          }
          int resultsArray[] = sqlStatement.executeBatch();
          for (int i = 0; i < names.length; i++) {
            if (resultsArray[i] > 0) {
              successCount++;
            }
          }
          IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
        } finally {
          try {
            if (sqlStatement != null) {
              sqlStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
          }

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