Ejemplo n.º 1
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (true) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    /* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */
    Class<?> tempClass = Class.forName(data);
    Object tempClassObject = tempClass.newInstance();

    IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    while (true) {
      data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=33" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            try {
              data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception reading id from query string",
                  exceptNumberFormat);
            }
            break; /* exit while loop */
          }
        }
      }
      break;
    }

    while (true) {
      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);
      }
      break;
    }
  }
Ejemplo n.º 4
0
  /**
   * 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]);
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;
    if (IO.staticFive == 5) {
      data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=33" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            try {
              data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception reading id from query string",
                  exceptNumberFormat);
            }
            break; /* exit while loop */
          }
        }
      }
    } 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.staticFive == 5) {
      /* POTENTIAL FLAW: if data == Integer.MAX_VALUE, this will overflow */
      int result = (int) (data + 1);
      IO.writeLine("result: " + result);
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } 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 (privateFive == 5) {
      int numberOfLoops;
      try {
        numberOfLoops = Integer.parseInt(data);
      } catch (NumberFormatException exceptNumberFormat) {
        IO.writeLine("Invalid response. Numeric input expected. Assuming 1.");
        numberOfLoops = 1;
      }
      for (int i = 0; i < numberOfLoops; i++) {
        /* POTENTIAL FLAW: user supplied input used for loop counter test */
        IO.writeLine("hello world");
      }
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");

      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=33" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          try {
            data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
          } catch (NumberFormatException exceptNumberFormat) {
            IO.logger.log(
                Level.WARNING,
                "Number format exception reading id from query string",
                exceptNumberFormat);
          }
          break; /* exit while loop */
        }
      }
    }

    if (data > 0) /* ensure we won't have an underflow */ {
      /* FIX: Add a check to prevent an overflow from occurring */
      if (data < (Integer.MAX_VALUE / 2)) {
        int result = (int) (data * 2);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform multiplication.");
      }
    }
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");

      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=33" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          try {
            data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
          } catch (NumberFormatException exceptNumberFormat) {
            IO.logger.log(
                Level.WARNING,
                "Number format exception reading id from query string",
                exceptNumberFormat);
          }
          break; /* exit while loop */
        }
      }
    }

    dataBad = data;
    badSink(request, response);
  }
Ejemplo n.º 9
0
 public DownloadRequest(ServletContext context, HttpServletRequest request) {
   _context = context;
   _httpRequest = request;
   _path = request.getRequestURI();
   _encoding = request.getHeader(ACCEPT_ENCODING);
   String context_path = request.getContextPath();
   if (context_path != null) _path = _path.substring(context_path.length());
   if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations
   if (_path == null) _path = "/"; // No path given
   _path = _path.trim();
   if (_context != null && !_path.endsWith("/")) {
     String realPath = _context.getRealPath(_path);
     // fix for 4474021 - getRealPath might returns NULL
     if (realPath != null) {
       File f = new File(realPath);
       if (f != null && f.exists() && f.isDirectory()) {
         _path += "/";
       }
     }
   }
   // Append default file for a directory
   if (_path.endsWith("/")) _path += "launch.jnlp";
   _version = getParameter(request, ARG_VERSION_ID);
   _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID);
   _os = getParameterList(request, ARG_OS);
   _arch = getParameterList(request, ARG_ARCH);
   _locale = getParameterList(request, ARG_LOCALE);
   _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
   String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
   _isPlatformRequest = (platformVersion != null);
   if (_isPlatformRequest) _version = platformVersion;
   _query = request.getQueryString();
   _testJRE = getParameter(request, TEST_JRE);
 }
Ejemplo n.º 10
0
  private static Properties createCGIEnvironment(
      HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException {

    URI full_request_uri =
        new URI(
            sreq.getScheme(),
            null,
            sreq.getServerName(),
            sreq.getServerPort(),
            sreq.getRequestURI(),
            sreq.getQueryString(),
            null);

    Properties p =
        createCGIEnvironment(
            sreq.getMethod(),
            sreq.getProtocol(),
            full_request_uri,
            new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()),
            new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()),
            sreq.getContextPath() + "/",
            root_uri,
            canonical_script_file);

    // Add request headers

    for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) {
      String h = (String) e.nextElement();
      p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h));
    }

    return p;
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    while (true) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
      break;
    }

    if (data != null) {
      /* POTENTIAL FLAW: script code (e.g. id=<script>alert('xss')</script>) is sent to the client;
       * The built-in J2EE server automatically does some HTML entity encoding.
       * Therefore, to test this, change response.sendError to response.getWriter().println and remove the 404,
       */
      response.sendError(404, "<br>bad() - Parameter name has value " + data);
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");

      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=33" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          try {
            data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
          } catch (NumberFormatException exceptNumberFormat) {
            IO.logger.log(
                Level.WARNING,
                "Number format exception reading id from query string",
                exceptNumberFormat);
          }
          break; /* exit while loop */
        }
      }
    }

    int[] dataArray = new int[5];
    dataArray[2] = data;
    (new CWE369_Divide_by_Zero__int_getQueryString_Servlet_modulo_66b())
        .goodB2GSink(dataArray, request, response);
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateTrue) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (data != null) {
      /* POTENTIAL FLAW: Display of data in web page without any encoding or validation */
      response.getWriter().println("<br>bad(): data = " + data);
    }
  }
Ejemplo n.º 14
0
 @Override
 public void parseRequestParameters(
     final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files)
     throws RequestParseException {
   try {
     if (isMultiPart()) {
       parseQueryString(params, req.getQueryString());
       @SuppressWarnings("unchecked")
       final List<FileItem> items = new ServletFileUpload().parseRequest(req);
       for (final FileItem item : items) {
         if (item.isFormField()) params.put(item.getFieldName(), item.getString());
         else files.put(item.getFieldName(), new FileItemWrapper(item));
       }
     } else {
       final Enumeration<String> en = req.getParameterNames();
       while (en.hasMoreElements()) {
         final String nm = en.nextElement();
         final String val = req.getParameter(nm);
         params.put(nm, val);
       }
     }
   } catch (final FileUploadException ex) {
     throw new RequestParseException("FileUploadException", ex);
   } catch (final Throwable ex) {
     throw new RequestParseException(ex.getMessage(), ex);
   }
 }
Ejemplo n.º 15
0
  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet:doGetPost():validating goto: "
                + gotoParameter
                + " and target: "
                + targetParameter);
      }
      for (String invalidStr : INVALID_SET) {
        if (gotoParameter != null && gotoParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "GOTO parameter has invalid characters");
          return;
        }
        if (targetParameter != null && targetParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "TARGET parameter has invalid characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    // collect advices in parsedRequestParams[0] String and rest of params
    // other than original goto url in parsedRequestParams[1] String.
    String[] parsedRequestParams = parseRequestParams(request);

    if ((token == null) || (parsedRequestParams[0] != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response, parsedRequestParams[0], parsedRequestParams[1]);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
Ejemplo n.º 16
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    System.out.println("queryString: " + request.getQueryString());
    out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL"));
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } 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 (privateFive == 5) {
      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      try {
        /* FIX: Use prepared statement and execute (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name=?");
        sqlStatement.setString(1, data);
        Boolean result = sqlStatement.execute();
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"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);
        }
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      debug.message("CDCServlet:doGetPost():goto or target is not null");
      for (Iterator it = invalidSet.iterator(); it.hasNext(); ) {
        String invalidStr = (String) it.next();
        if ((gotoParameter != null) && (gotoParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "GOTO parameter has invalid " + "characters");
          return;
        }
        if ((targetParameter != null)
            && (targetParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "TARGET parameter has invalid " + "characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    if (token == null) {
      policyAdviceList = null;
    }
    // collect advices in policyAdviceList String and rest of params
    // other than original goto url in "requestParams" String.
    parseRequestParams(request);
    if ((token == null) || (policyAdviceList != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int count;

    count = Integer.MIN_VALUE; /* initialize count in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");

      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=33" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          try {
            count = Integer.parseInt(token.substring(3)); /* set count to the int 33 */
          } catch (NumberFormatException exceptNumberFormat) {
            IO.logger.log(
                Level.WARNING,
                "Number format exception reading id from query string",
                exceptNumberFormat);
          }
          break; /* exit while loop */
        }
      }
    }

    /* serialize count to a byte array */
    ByteArrayOutputStream streamByteArrayOutput = null;
    ObjectOutput outputObject = null;

    try {
      streamByteArrayOutput = new ByteArrayOutputStream();
      outputObject = new ObjectOutputStream(streamByteArrayOutput);
      outputObject.writeObject(count);
      byte[] countSerialized = streamByteArrayOutput.toByteArray();
      (new CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_75b())
          .badSink(countSerialized, request, response);
    } catch (IOException exceptIO) {
      IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
    } finally {
      /* clean up stream writing objects */
      try {
        if (outputObject != null) {
          outputObject.close();
        }
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
      }

      try {
        if (streamByteArrayOutput != null) {
          streamByteArrayOutput.close();
        }
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println(
        "MyProtectedServlet.processRequest "
            + request.getRequestURI()
            + " "
            + request.getQueryString());

    String myUrl = request.getRequestURI();
    if (myUrl.indexOf("login") >= 0) {
      login(request, response);
      return;
    } else if (myUrl.indexOf("redirect") >= 0) {
      redirect(request, response);
      return;
    }

    if (request.getRemoteUser() == null) {
      String callUrl = request.getRequestURI();
      String query = request.getQueryString();
      if (query != null) {
        callUrl = callUrl + "?" + query;
      }
      String nextEncUrl = java.net.URLEncoder.encode(callUrl);
      String redirectUrl =
          request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl;
      response.sendRedirect(redirectUrl);
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet MyProtectedServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");

      out.close();
    }
  }
Ejemplo n.º 21
0
  /**
   * Forward this request to the CatalogServices servlet ("/catalog.html").
   *
   * @param req request
   * @param res response
   * @throws IOException on IO error
   * @throws ServletException other error
   */
  public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    String reqs = "catalog=" + getReletiveURL(req);
    String query = req.getQueryString();
    if (query != null) reqs = reqs + "&" + query;
    log.info("forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"");

    // dispatch to CatalogHtml servlet
    RequestForwardUtils.forwardRequestRelativeToCurrentContext("/catalog.html?" + reqs, req, res);
  }
Ejemplo n.º 22
0
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
Ejemplo n.º 23
0
  @SuppressWarnings("unchecked")
  private void handleAction(
      RenderVelocityAction action, String cmd, Vector[] args, HttpServletRequest request) {
    if (action != null) {
      // add parameter from path
      for (int p = 0; p < args[0].size(); p++) {
        action.putParam((String) args[0].get(p), (String) args[1].get(p));
      }

      VelocityContext c = new VelocityContext();
      try {
        c.put("action", action);
        c.put("encoding", action.encoding);
        c.put("cmd", cmd);

        // c.put("au", action.user);

        c.put("reqaddress", request.getRemoteAddr());
        c.put("scheme", request.getScheme());
        c.put("querystring", request.getQueryString());
        if (c.get("querystring") == null) {
          c.put("querystring", "");
        }

        String requesturl = request.getRequestURL().toString();

        // c.put("mid", ma.user.mandantid);
        c.put("request", request);
        c.put("requesturl", requesturl);
        c.put("server", request.getServerName());
        c.put("port", request.getServerPort());

        String ref = request.getHeader("Referer");
        if (ref == null) {
          ref = "#";
        }
        c.put("referer", ref);

        // process and render template
        action.process(c);

      } catch (Exception ex) {
        ex.printStackTrace();
        //	        		action.makeErrorOutput("Internal Error", null, c);
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.staticFive==5 to IO.staticFive!=5 */
  private void goodB2G1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;
    if (IO.staticFive == 5) {
      data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=33" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            try {
              data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception reading id from query string",
                  exceptNumberFormat);
            }
            break; /* exit while loop */
          }
        }
      }
    } 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.staticFive != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* 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: Fully verify data before reading from array at location data */
      if (data >= 0 && data < array.length) {
        IO.writeLine(array[data]);
      } else {
        IO.writeLine("Array index out of bounds");
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */
  private void goodB2G1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int count;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      count = Integer.MIN_VALUE; /* initialize count in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=33" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            try {
              count = Integer.parseInt(token.substring(3)); /* set count to the int 33 */
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception reading id from query string",
                  exceptNumberFormat);
            }
            break; /* exit while loop */
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure count is inititialized before the Sink to avoid compiler errors */
      count = 0;
    }

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

      int i = 0;

      /* FIX: Validate count before using it as the for loop variant */
      if (count > 0 && count <= 20) {
        for (i = 0; i < count; i++) {
          IO.writeLine("Hello");
        }
      }
    }
  }
  public URL getUrl(HttpServletRequest req) throws IOException {
    String servletPath = req.getServletPath();

    String selectedServerFullPath = getServerAddress(servletPath);
    String queryString = req.getQueryString();
    String newUrl = "";
    HttpSession session = req.getSession(false);

    newUrl = selectedServerFullPath + servletPath;

    if (req.getRequestedSessionId() != null)
      newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId();

    if (queryString != null) newUrl = newUrl + "?" + queryString;

    // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId();

    return new URL(newUrl);
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    data = ""; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          data = token.substring(3); /* set data to "foo" */
          break; /* exit while loop */
        }
      }
    }

    (new CWE83_XSS_Attribute__Servlet_getQueryString_Servlet_71b())
        .badSink((Object) data, request, response);
  }
  private String badSource(HttpServletRequest request, HttpServletResponse response)
      throws Throwable {
    String data;

    data = ""; /* initialize data in case id is not in query string */

    /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
    {
      StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
      while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
        if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
          data = token.substring(3); /* set data to "foo" */
          break; /* exit while loop */
        }
      }
    }

    return data;
  }
Ejemplo n.º 29
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

    req = rq;
    res = rs;
    params = new HTTPParams(this);

    method = rq.getMethod();

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log('[' + method + "] " + uri, null);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);
    segments = decode(toSegments(req.getPathInfo()));

    // adopt servlet-specific credentials or use global ones
    final GlobalOptions mprop = context().globalopts;
    user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER);
    pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD);

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.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]);
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

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

    /* parse the query string for value of 'id' */
    String id_str = null;
    StringTokenizer st = new StringTokenizer(request.getQueryString(), "&");
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      int i = token.indexOf("=");
      if ((i > 0) && (i < (token.length() - 1)) && (token.substring(0, i).equals("id"))) {
        id_str = token.substring(i + 1);
        break;
      }
    }

    if (id_str != null) {
      Connection conn = null;
      PreparedStatement statement = null;
      ResultSet rs = null;
      try {
        int id = Integer.parseInt(id_str);
        conn = IO.getDBConnection();
        statement = conn.prepareStatement("select * from pages where id=?");
        /* FLAW: no check to see whether the user has privileges to view the data */
        statement.setInt(1, id);
        rs = statement.executeQuery();
        data = rs.toString();
      } catch (SQLException se) {
        log_bad.warning("Error");
      } finally {
        /* 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");
            }
          }
        }
      }
    }

    (new CWE89_SQL_Injection__getQueryStringServlet_executeUpdate_53b())
        .bad_sink(data, request, response);
  }