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);
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b())
            .goodG2B_source(request, response);

    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);
  }
  public void bad_sink(
      CWE643_Unsafe_Treatment_of_XPath_Input__fromFile_67a.Container data_container)
      throws Throwable {
    String data = data_container.a;

    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);
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b())
            .goodB2G_source(request, response);

    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);
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(
      CWE643_Unsafe_Treatment_of_XPath_Input__fromFile_67a.Container data_container)
      throws Throwable {
    String data = data_container.a;

    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);
  }
  /* 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;
    }
  }
예제 #7
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
  /* 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(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);
      }
    }
  }
예제 #10
0
  public List getProjectList() {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl = rallyApiHost + "/project?" + "fetch=true&order=Name&start=1&pagesize=200";

      log.info("rallyApiUrl:" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        map.put("objId", objId);
        map.put("name", name);
        map.put("state", state);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
  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;
    }
  }
예제 #13
0
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

      log.info("getUserStoryList apiURL=" + apiURL);

      String responseXML = getRallyXML(apiURL);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

          String[] objectIdArr = taskRef.split("/");
          String objectId = objectIdArr[objectIdArr.length - 1];

          log.info("objectId=" + objectId);

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

        log.info("planEstimateStr=" + planEstimateStr);

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
예제 #14
0
  public List getIterationList(String projectId) {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl =
          rallyApiHost
              + "/iteration?"
              + "project="
              + rallyApiHost
              + "/project/"
              + projectId
              + "&fetch=true&order=Name%20desc&start=1&pagesize=100";

      String checkProjectRef = rallyApiHost + "/project/" + projectId;

      log.info("rallyApiUrl:" + apiUrl);
      log.info("checkProjectRef:" + checkProjectRef);

      String responseXML = getRallyXML(apiUrl);

      SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      Date currentDate = new Date();

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        String startDateStr = item.getChildText("StartDate");
        String endDateStr = item.getChildText("EndDate");

        Date startDate = ISO8601FORMAT.parse(startDateStr);
        Date endDate = ISO8601FORMAT.parse(endDateStr);

        boolean isCurrent = false;

        int startCheck = startDate.compareTo(currentDate);
        int endCheck = endDate.compareTo(currentDate);

        if (startCheck < 0 && endCheck > 0) {
          isCurrent = true;
        }

        log.info("name=" + name + " isCurrent=" + isCurrent);

        String releaseRef = item.getAttribute("ref").getValue();

        // In child project, parent object have to be filiered
        Element projectElement = item.getChild("Project");
        String projectRef = projectElement.getAttributeValue("ref");

        if (projectRef.equals(checkProjectRef)) {

          map.put("objId", objId);
          map.put("rallyRef", releaseRef);
          map.put("name", name);
          map.put("state", state);
          map.put("isCurrent", "" + isCurrent);

          list.add(map);
        }
      }

      log.info("-----------");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
예제 #15
0
  public List getUserTimeSpentByDate(String userObjectId, String startDate, String endDate) {
    List list = new ArrayList();

    log.info("userObjectId=" + userObjectId);
    log.info("startDate=" + startDate);
    log.info("endDate=" + endDate);

    try {

      String apiUrl =
          rallyApiHost
              + "/timeentryvalue?query=((TimeEntryItem.User.ObjectId%20=%20"
              + userObjectId
              + ")"
              + "%20and%20((DateVal%20%3E=%20"
              + startDate
              + ")%20and%20(DateVal%20%3C=%20"
              + endDate
              + ")))"
              + "&start=1&pagesize=100&fetch=true";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      log.info("responseXML=" + responseXML);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        // Map map=new HashMap();

        Element item = (Element) iter.next();

        String hours = item.getChildText("Hours");

        Element timeEntryItemElement = item.getChild("TimeEntryItem");
        String timeEntryItemRef = timeEntryItemElement.getAttributeValue("ref");

        Map map = getUserStoryTaskMap(timeEntryItemRef);

        String checkTaskId = (String) map.get("taskFormattedId");

        boolean isExist = false;
        for (int i = 0; i < list.size(); i++) {
          Map existMap = (Map) list.get(i);

          log.info("existMap=" + existMap);

          String existTaskId = (String) existMap.get("taskFormattedId");

          log.info("existTaskId=" + existTaskId);
          log.info("checkTaskId=" + checkTaskId);

          if (existTaskId != null && existTaskId.equals(checkTaskId)) {
            isExist = true;
            String existHours = (String) existMap.get("hours");
            double eHour = 0.0D;
            if (!"".equals(existHours)) {
              eHour = Double.parseDouble(existHours);
            }
            double nHour = 0.0D;

            if (!"".equals(hours)) {
              nHour = Double.parseDouble(hours);
            }

            log.info("nHour=" + nHour);
            log.info("eHour=" + eHour);

            nHour += eHour;
            log.info("2 nHour=" + nHour);
            existMap.put("hours", "" + nHour);

            break;
          }
        }

        if (!isExist) {
          map.put("hours", hours);
          list.add(map);
        }

        log.info("hours=" + hours);
        log.info("timeEntryItemRef=" + timeEntryItemRef);

        // list.add(map);

      }

      Collections.sort(
          list,
          new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> m1, Map<String, String> m2) {
              if (m1.get("projectName") == null || m2.get("projectName") == null) return -1;
              return m1.get("projectName").compareTo(m2.get("projectName"));
            }
          });

      // Sum up the total time
      double totalTaskEstimate = 0.0D;
      double totalTaskRemaining = 0.0D;
      double totalHours = 0.0D;
      for (int i = 0; i < list.size(); i++) {
        Map map = (Map) list.get(i);

        log.info("taskEstimate=" + (String) map.get("taskEstimate"));
        log.info("taskRemaining=" + (String) map.get("taskRemaining"));
        log.info("hours=" + (String) map.get("hours"));

        log.info("map==" + map);

        try {
          double taskEstimate = Double.parseDouble((String) map.get("taskEstimate"));
          double taskRemaining = Double.parseDouble((String) map.get("taskRemaining"));
          double hours = Double.parseDouble((String) map.get("hours"));

          totalTaskEstimate += taskEstimate;
          totalTaskRemaining += taskRemaining;
          totalHours += hours;
        } catch (Exception e) {
          log.info("ERROR in parsing number" + e);
        }
      }

      Map firstMap = new HashMap();

      firstMap.put("taskFormattedId", "");
      firstMap.put("taskName", "");
      firstMap.put("taskState", "");
      firstMap.put("owner", "");
      firstMap.put("taskEstimate", "" + totalTaskEstimate);
      firstMap.put("taskRemaining", "" + totalTaskRemaining);
      firstMap.put("hours", "" + totalHours);
      firstMap.put("projectName", "");
      firstMap.put("iterationName", "");

      list.add(0, firstMap);

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
  /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch  */
  private void goodB2G2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    switch (6) {
      case 6:
        {
          Logger log_bad = Logger.getLogger("local-logger");
          /* read parameter from request */
          data = request.getParameter("name");
        }
        break;
      default:
        /* 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";
        }
        break;
    }

    switch (7) {
      case 7:
        {
          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);
        }
        break;
      default:
        /* 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;
          }
          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);
        }
        break;
    }
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    String data;
    if (IO.static_returns_t()) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      Connection conn = null;
      PreparedStatement statement = null;
      ResultSet rs = null;
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        /* setup the connection */
        conn = IO.getDBConnection();
        /* prepare the query */
        statement = conn.prepareStatement("select name from users where id=?");
        /* get user input for the userid */
        IO.writeLine("Enter a userid to login as (number): ");
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        int num = Integer.parseInt(buffread.readLine());
        statement.setInt(1, num);
        rs = statement.executeQuery();
        data = rs.getString(1);
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }

        /* clean up database objects */
        try {
          if (rs != null) {
            rs.close();
          }
        } catch (SQLException se) {
          log_bad.warning("Error closing rs");
        } finally {
          try {
            if (statement != null) {
              statement.close();
            }
          } catch (SQLException se) {
            log_bad.warning("Error closing statement");
          } finally {
            try {
              if (conn != null) {
                conn.close();
              }
            } catch (SQLException se) {
              log_bad.warning("Error closing conn");
            }
          }
        }
      }
    } 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";
    }
    if (IO.static_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;
      }
      /* 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);
    } 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;
      }
      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);
    }
  }
  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);
    }
  }