/* 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 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);
    }
  }
  private String bad_source() throws Throwable {
    String data;

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

    /* get environment variable ADD */
    data = System.getenv("ADD");

    return data;
  }
  /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first switch  */
  private void goodG2B2() throws Throwable {
    String data;

    switch (6) {
      case 6:
        /* FIX: Use a hardcoded string */
        data = "foo";
        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:
        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);
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        IO.writeLine("Benign, fixed string");
        break;
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      /* 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;
    }

    if (PRIVATE_STATIC_FINAL_TRUE) {
      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);
      }
    }
  }
Esempio n. 6
0
  /**
   * TDTEngine - constructor for a new Tag Data Translation engine
   *
   * @param confdir the string value of the path to a configuration directory consisting of two
   *     subdirectories, <code>schemes</code> and <code>auxiliary</code>.
   *     <p>When the class TDTEngine is constructed, the path to a local directory must be
   *     specified, by passing it as a single string parameter to the constructor method (without
   *     any trailing slash or file separator). e.g. <code>
   *     <pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code>
   *     <p>The specified directory must contain two subdirectories named auxiliary and schemes. The
   *     Tag Data Translation definition files for the various coding schemes should be located
   *     inside the subdirectory called <code>schemes</code>. Any auxiliary lookup files (such as
   *     <code>ManagerTranslation.xml</code>) should be located inside the subdirectory called
   *     <code>auxiliary</code>.
   *     <p>Files within the schemes directory ending in <code>.xml</code> are read in and
   *     unmarshalled using <a href = "http://www.castor.org">Castor</a>.
   */
  public TDTEngine(String confdir)
      throws FileNotFoundException, MarshalException, ValidationException, TDTException {
    xmldir = confdir;

    long t = System.currentTimeMillis();
    File[] dir =
        new java.io.File(confdir + File.separator + "schemes").listFiles(new XMLFilenameFilter());
    // java.util.Arrays.sort(dir); // Sort it
    if (dir == null) throw new TDTException("Cannot find schemes in " + confdir);
    Unmarshaller unmar = new Unmarshaller();
    for (File f : dir) {
      EpcTagDataTranslation tdt =
          (EpcTagDataTranslation) unmar.unmarshal(EpcTagDataTranslation.class, new FileReader(f));

      initFromTDT(tdt);
    }

    // need to populate the hashmap gs1cpi from the ManagerTranslation.xml table in auxiliary.
    // Unmarshaller unmar = new Unmarshaller();
    GEPC64Table cpilookup =
        (GEPC64Table)
            unmar.unmarshal(
                GEPC64Table.class,
                new FileReader(
                    confdir
                        + File.separator
                        + "auxiliary"
                        + File.separator
                        + "ManagerTranslation.xml"));
    for (Enumeration e = cpilookup.enumerateEntry(); e.hasMoreElements(); ) {
      Entry entry = (Entry) e.nextElement();
      String comp = entry.getCompanyPrefix();
      String indx = Integer.toString(entry.getIndex());
      gs1cpi.put(indx, comp);
      gs1cpi.put(comp, indx);
    }

    // System.out.println("Loaded schemas in " +
    //		   (System.currentTimeMillis() - t)
    //		   + " millisecs");

  }
  public void bad() throws Throwable {
    String data;
    if (IO.staticFive == 5) {
      data = ""; /* Initialize data */
      {
        File file = new File("C:\\data.txt");
        FileInputStream streamFileInput = null;
        InputStreamReader readerInputStream = null;
        BufferedReader readerBuffered = null;
        try {
          /* read string from file into data */
          streamFileInput = new FileInputStream(file);
          readerInputStream = new InputStreamReader(streamFileInput, "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data from a file */
          /* 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 */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close 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);
          }

          try {
            if (streamFileInput != null) {
              streamFileInput.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", 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;
    }

    if (IO.staticFive == 5) {
      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 {
    String data;

    switch (6) {
      case 6:
        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);
            }
          }
        }
        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:
        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);
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        IO.writeLine("Benign, fixed string");
        break;
    }
  }
  public void bad() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_returns_t()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* get environment variable ADD */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_returns_t()) {
      final String xmldoc =
          "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";
      /* assume username||password as source */
      String[] tokens = data.split("||");
      if (tokens.length < 2) {
        return;
      }
      String uname = tokens[0];
      String pword = tokens[1];
      /* build xpath */
      XPath xp = XPathFactory.newInstance().newXPath();
      InputSource inxml = new InputSource(xmldoc);
      /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
       * 	The user input should be canonicalized before validation.
       */
      /* FLAW: user input is used without validate */
      String query =
          "//users/user[name/text()='"
              + uname
              + "' and pass/text()='"
              + pword
              + "']"
              + "/secret/text()";
      String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      final String xmldoc =
          "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";

      /* assume username||password as source */
      String[] tokens = data.split("||");
      if (tokens.length < 2) {
        return;
      }

      /* FIX: validate input using StringEscapeUtils */
      String uname = StringEscapeUtils.escapeXml(tokens[0]);
      String pword = StringEscapeUtils.escapeXml(tokens[1]);

      /* build xpath */
      XPath xp = XPathFactory.newInstance().newXPath();
      InputSource inxml = new InputSource(xmldoc);

      String query =
          "//users/user[name/text()='"
              + uname
              + "' and pass/text()='"
              + pword
              + "']"
              + "/secret/text()";
      String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
    }
  }