Ejemplo n.º 1
0
 public void testSentence() {
   // sentence including unicode surrogate pair for character U+2070E
   String surrogate = "\u3042\u3044\u3046\uD841\uDF0E\u3042\u3044\u3046abc";
   String expected = "あいう𠜎あいうabc";
   assertEquals(expected, ESAPI.encoder().encodeForXML(surrogate));
   assertEquals(expected, ESAPI.encoder().encodeForXMLAttribute(surrogate));
 }
Ejemplo n.º 2
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheValue("vector");

    String bar = doSomething(param);

    try {
      java.util.Properties benchmarkprops = new java.util.Properties();
      benchmarkprops.load(
          this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
      String algorithm = benchmarkprops.getProperty("hashAlg2", "SHA5");
      java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
      byte[] input = {(byte) '?'};
      Object inputParam = bar;
      if (inputParam instanceof String) input = ((String) inputParam).getBytes();
      if (inputParam instanceof java.io.InputStream) {
        byte[] strInput = new byte[1000];
        int i = ((java.io.InputStream) inputParam).read(strInput);
        if (i == -1) {
          response
              .getWriter()
              .println(
                  "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
          return;
        }
        input = java.util.Arrays.copyOf(strInput, i);
      }
      md.update(input);

      byte[] result = md.digest();
      java.io.File fileTarget =
          new java.io.File(
              new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
      java.io.FileWriter fw =
          new java.io.FileWriter(fileTarget, true); // the true will append the new data
      fw.write(
          "hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
      fw.close();
      response
          .getWriter()
          .println(
              "Sensitive value '"
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                  + "' hashed and stored<br/>");
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing hash - TestCase");
      throw new ServletException(e);
    }

    response
        .getWriter()
        .println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
  } // end doPost
Ejemplo n.º 3
0
  public void testSingleLetter() {
    // unicode surrogate pair for character U+2070E
    String surrogate = "\uD841\uDF0E";
    String expected = "&#132878;";
    // "&#132878;" is the correct character reference for this surrogate pair.
    assertEquals(expected, ESAPI.encoder().encodeForXML(surrogate));
    assertEquals(expected, ESAPI.encoder().encodeForXMLAttribute(surrogate));

    // "&#xd841;&#xdf0e;" is wrong character references.
    // This surrogate pair should represent 1 character.
    //      assertEquals("&#xd841;&#xdf0e;", ESAPI.encoder().encodeForHTML(surrogate));
    //      assertEquals("&#xd841;&#xdf0e;", ESAPI.encoder().encodeForHTMLAttribute(surrogate));
  }
Ejemplo n.º 4
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getParameter("vector");
    if (param == null) param = "";

    String bar;

    // Simple ? condition that assigns constant to bar on true condition
    int num = 106;

    bar = (7 * 18) + num > 200 ? "This_should_always_happen" : param;

    String fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;
    java.io.InputStream is = null;

    try {
      java.nio.file.Path path = java.nio.file.Paths.get(fileName);
      is = java.nio.file.Files.newInputStream(path, java.nio.file.StandardOpenOption.READ);
      byte[] b = new byte[1000];
      int size = is.read(b);
      response
          .getWriter()
          .write(
              "The beginning of file: '"
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName)
                  + "' is:\n\n");
      response
          .getWriter()
          .write(org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(b, 0, size)));
      is.close();
    } catch (Exception e) {
      System.out.println("Couldn't open InputStream on file: '" + fileName + "'");
      response
          .getWriter()
          .write(
              "Problem getting InputStream: "
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage()));
    } finally {
      if (is != null) {
        try {
          is.close();
          is = null;
        } catch (Exception e) {
          // we tried...
        }
      }
    }
  }
Ejemplo n.º 5
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String queryString = request.getQueryString();
    String paramval = "vector" + "=";
    int paramLoc = -1;
    if (queryString != null) paramLoc = queryString.indexOf(paramval);
    if (paramLoc == -1) {
      response
          .getWriter()
          .println(
              "getQueryString() couldn't find expected parameter '"
                  + "vector"
                  + "' in query string.");
      return;
    }

    String param =
        queryString.substring(
            paramLoc
                + paramval
                    .length()); // 1st assume "vector" param is last parameter in query string.
    // And then check to see if its in the middle of the query string and if so, trim off what comes
    // after.
    int ampersandLoc = queryString.indexOf("&", paramLoc);
    if (ampersandLoc != -1) {
      param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
    }
    param = java.net.URLDecoder.decode(param, "UTF-8");

    String bar = doSomething(param);

    String fileName = null;
    java.io.FileOutputStream fos = null;

    try {
      fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;

      fos = new java.io.FileOutputStream(fileName);
      response
          .getWriter()
          .write(
              "Now ready to write to file: "
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName));
    } catch (Exception e) {
      System.out.println("Couldn't open FileOutputStream on file: '" + fileName + "'");
      //			System.out.println("File exception caught and swallowed: " + e.getMessage());
    } finally {
      if (fos != null) {
        try {
          fos.close();
          fos = null;
        } catch (Exception e) {
          // we tried...
        }
      }
    }
  } // end doPost
Ejemplo n.º 6
0
 /**
  * Build xml for all public Line positions in a Manuscript. Useful for exporting known Line
  * positions for use in another tool.
  *
  * @return valid xml
  * @throws SQLException
  */
 public String getLinePositions() throws SQLException {
   String toret = "";
   String query = "select pageNumber, imageName from folios where msID=?";
   Connection j = null;
   PreparedStatement ps = null;
   try {
     j = DatabaseWrapper.getConnection();
     ps = j.prepareStatement(query);
     ps.setInt(1, this.id);
     ResultSet rs = ps.executeQuery();
     while (rs.next()) {
       Folio f = new Folio(rs.getInt(1));
       toret += "<image name=\"" + ESAPI.encoder().encodeForXML(rs.getString(2)) + "\">";
       Line[] allLines = f.getlines();
       for (int i = 0; i < allLines.length; i++) {
         toret +=
             "<line><x>"
                 + allLines[i].getLeft()
                 + "</x><y>"
                 + allLines[i].getTop()
                 + "</y><w>"
                 + allLines[i].getWidth()
                 + "</w><h>"
                 + allLines[i].getHeight()
                 + "</h></line>\n";
       }
       toret += "</image>";
     }
   } finally {
     DatabaseWrapper.closeDBConnection(j);
     DatabaseWrapper.closePreparedStatement(ps);
   }
   return toret;
 }
Ejemplo n.º 7
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    try {
      String sql =
          "SELECT TOP 1 USERNAME from USERS where USERNAME='******' and PASSWORD='******'";

      Object results =
          org.owasp.benchmark.helpers.DatabaseHelper.JDBCtemplate.queryForObject(
              sql, new Object[] {}, String.class);
      java.io.PrintWriter out = response.getWriter();
      out.write("Your results are: ");
      //		System.out.println("Your results are");
      out.write(org.owasp.esapi.ESAPI.encoder().encodeForHTML(results.toString()));
      //		System.out.println(results.toString());
    } catch (org.springframework.dao.DataAccessException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  } // end doPost
 public static String[][] getSqlInjectionResult(String ApplicationRoot, String username) {
   Encoder encoder = ESAPI.encoder();
   String[][] result = new String[10][3];
   try {
     Connection conn = Database.getSqlInjLessonConnection(ApplicationRoot);
     Statement stmt;
     stmt = conn.createStatement();
     ResultSet resultSet =
         stmt.executeQuery("SELECT * FROM tb_users WHERE username = '******'");
     log.debug("Opening Result Set from query");
     for (int i = 0; resultSet.next(); i++) {
       log.debug("Row " + i + ": User ID = " + resultSet.getString(1));
       result[i][0] = encoder.encodeForHTML(resultSet.getString(1));
       result[i][1] = encoder.encodeForHTML(resultSet.getString(2));
       result[i][2] = encoder.encodeForHTML(resultSet.getString(3));
     }
     log.debug("That's All");
   } catch (SQLException e) {
     log.debug("SQL Error caught - " + e.toString());
     result[0][0] = "error";
     result[0][1] = encoder.encodeForHTML(e.toString());
   } catch (Exception e) {
     log.fatal("Error: " + e.toString());
   }
   return result;
 }
Ejemplo n.º 9
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    byte[] bytes = new byte[10];
    new java.util.Random().nextBytes(bytes);
    String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(bytes, true);

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (int i = 0; !foundUser && i < cookies.length; i++) {
        javax.servlet.http.Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
          if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
            foundUser = true;
          }
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextBytes() executed");
  } // end doPost
Ejemplo n.º 10
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheValue("vector");

    String bar = doSomething(param);

    String fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;
    java.io.InputStream is = null;

    try {
      java.nio.file.Path path = java.nio.file.Paths.get(fileName);
      is = java.nio.file.Files.newInputStream(path, java.nio.file.StandardOpenOption.READ);
      byte[] b = new byte[1000];
      int size = is.read(b);
      response
          .getWriter()
          .write(
              "The beginning of file: '"
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName)
                  + "' is:\n\n");
      response
          .getWriter()
          .write(org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(b, 0, size)));
      is.close();
    } catch (Exception e) {
      System.out.println("Couldn't open InputStream on file: '" + fileName + "'");
      response.getWriter().write("Problem getting InputStream: " + e.getMessage());
    } finally {
      if (is != null) {
        try {
          is.close();
          is = null;
        } catch (Exception e) {
          // we tried...
        }
      }
    }
  } // end doPost
Ejemplo n.º 11
0
 /**
  * This method validates input and then attempts to update the cheat sheet for the specified
  * module
  *
  * @param newSolution The new solution to store as a cheat sheet
  * @param moduleId[] The identifier of the module to update.
  * @param csrfToken
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // Setting IpAddress To Log and taking header for original IP if forwarded from proxy
   ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
   log.debug("*** servlets.Admin.CreateCheat ***");
   Encoder encoder = ESAPI.encoder();
   PrintWriter out = response.getWriter();
   out.print(getServletInfo());
   HttpSession ses = request.getSession(true);
   Cookie tokenCookie = Validate.getToken(request.getCookies());
   Object tokenParmeter = request.getParameter("csrfToken");
   if (Validate.validateAdminSession(ses, tokenCookie, tokenParmeter)) {
     ShepherdLogManager.setRequestIp(
         request.getRemoteAddr(),
         request.getHeader("X-Forwarded-For"),
         ses.getAttribute("userName").toString());
     log.debug("Current User: "******"userName").toString());
     if (Validate.validateTokens(tokenCookie, tokenParmeter)) {
       String errorMessage = null;
       String newSolution = request.getParameter("newSolution");
       log.debug("User submitted new solution - " + newSolution);
       String moduleId = request.getParameter("moduleId[]");
       log.debug("User submitted moduleId: " + moduleId);
       if (newSolution != null && !newSolution.isEmpty()) {
         String ApplicationRoot = getServletContext().getRealPath("");
         String moduleCheck = Getter.getModuleResult(ApplicationRoot, moduleId);
         if (moduleCheck != null) {
           if (!Setter.updateCheatSheet(
               ApplicationRoot, moduleId, encoder.encodeForHTML(newSolution)))
             errorMessage = "A database level error occurred. Please contact your administrator";
         } else {
           errorMessage = "Invalid Module submitted";
         }
       } else {
         errorMessage = "Invalid Module submitted";
       }
       String output = new String();
       if (errorMessage != null) {
         output =
             "<h2 class='title'>Create Cheat Sheet Failure</h2>"
                 + "<p>"
                 + encoder.encodeForHTML(errorMessage)
                 + "</p>";
       } else {
         output =
             "<h2 class='title'>Create Cheat Sheet Success</h2>"
                 + "<p>Cheat Sheet successfully created</p>";
       }
       out.write(output);
     }
   } else {
     out.write("<img src='css/images/loggedOutSheep.jpg'/>");
   }
   log.debug("*** END servlets.Admin.CreateCheat ***");
 }
Ejemplo n.º 12
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getParameter("foo");

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    // javax.servlet.http.HttpSession.putValue(java.lang.String,java.lang.Object^)
    request.getSession().putValue("foo", bar);
  }
  /**
   * This method sets the given text into Site Content Configure text editor.
   *
   * @param text
   * @param encoder Encode the text before adding it to the text editor.
   */
  public void setText(String text, Encoder encoder) {
    String encodedComment = text;
    if (encoder == null) {
      // Assume no encoding
      encoder = Encoder.ENCODER_NOENCODER;
    }

    switch (encoder) {
      case ENCODER_HTML:
        encodedComment = ESAPI.encoder().encodeForHTML(text);
        logger.info("Text encoded as HTML");
        break;
      case ENCODER_JAVASCRIPT:
        encodedComment = ESAPI.encoder().encodeForJavaScript(text);
        logger.info("Text encoded as JavaScript");
        break;
      default:
        logger.info("Text is not encoded");
    }
    setText(encodedComment);
  }
Ejemplo n.º 14
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("foo");

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    response.getWriter().write(bar);
  }
Ejemplo n.º 15
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String queryString = request.getQueryString();
    String paramval = "vector" + "=";
    int paramLoc = -1;
    if (queryString != null) paramLoc = queryString.indexOf(paramval);
    if (paramLoc == -1) {
      response
          .getWriter()
          .println(
              "getQueryString() couldn't find expected parameter '"
                  + "vector"
                  + "' in query string.");
      return;
    }

    String param =
        queryString.substring(
            paramLoc
                + paramval
                    .length()); // 1st assume "vector" param is last parameter in query string.
    // And then check to see if its in the middle of the query string and if so, trim off what comes
    // after.
    int ampersandLoc = queryString.indexOf("&", paramLoc);
    if (ampersandLoc != -1) {
      param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
    }
    param = java.net.URLDecoder.decode(param, "UTF-8");

    String bar = new Test().doSomething(param);

    try {
      String sql = "SELECT * from USERS where USERNAME='******' and PASSWORD='******'";

      org.owasp.benchmark.helpers.DatabaseHelper.JDBCtemplate.batchUpdate(sql);
      java.io.PrintWriter out = response.getWriter();
      //		System.out.println("no results for query: " + sql + " because the Spring batchUpdate
      // method doesn't return results.");
      out.write(
          "No results can be displayed for query: "
              + org.owasp.esapi.ESAPI.encoder().encodeForHTML(sql)
              + "<br>");
      out.write(" because the Spring batchUpdate method doesn't return results.");
    } catch (org.springframework.dao.DataAccessException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  } // end doPost
Ejemplo n.º 16
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getParameter("foo");

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    Object[] obj = {bar, "b"};

    response.getWriter().printf("notfoo", obj);
  }
Ejemplo n.º 17
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    java.io.File file = new java.io.File(bar);
  }
Ejemplo n.º 18
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    Object[] obj = {"a", bar};
    response.getWriter().println(obj);
  }
  /**
   * Strips any potential XSS threats out of the value
   *
   * @param value
   * @return
   */
  public static String stripXSS(String value) {
    LOG.debug("Value before stripping: " + value);
    if (value != null) {
      // Use the ESAPI library to avoid encoded attacks.
      value = ESAPI.encoder().canonicalize(value);

      // Avoid null characters
      value = value.replaceAll("\0", "");

      // Clean out HTML
      value = Jsoup.clean(value, Whitelist.none());
    }
    LOG.debug("Value after stripping: " + value);
    return value;
  }
Ejemplo n.º 20
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      param = map.get("foo")[0];
    }

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    java.lang.Math.random();

    response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
  }
 /**
  * Load the preferred JCE provider for ESAPI based on the <b>ESAPI.properties</b> property {@code
  * Encryptor.PreferredJCEProvider}. If this property is null (i.e., unset) or set to an empty
  * string, then no JCE provider is inserted at the "preferred" position and thus the Java VM
  * continues to use whatever the default it was using for this (generally specified in the file
  * {@code $JAVA_HOME/jre/security/java.security}).
  *
  * @return The actual preference position at which the provider was added, (which is expected to
  *     be 1) or -1 if the provider was not added because it is already installed at some other
  *     position. -1 is also returned if the {@code Encryptor.PreferredJCEProvider} was not set or
  *     set to an empty string, i.e., if the application <i>has</i> no preferred JCE provider.
  * @exception NoSuchProviderException - thrown if the provider class could not be loaded or added
  *     to the {@code SecurityManager} or any other reason for failure.
  * @see <a
  *     href="http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.htm">
  *     ESAPI 2.0 Symmetric Encryption User Guide</a>
  */
 public static int loadESAPIPreferredJCEProvider() throws NoSuchProviderException {
   String prefJCEProvider = ESAPI.securityConfiguration().getPreferredJCEProvider();
   try {
     // If unset or set to empty string, then don't try to change it.
     if (prefJCEProvider == null || prefJCEProvider.trim().length() == 0) {
       // Always log, per NSA suggestion.
       logger.always(Logger.SECURITY_AUDIT, "No Encryptor.PreferredJCEProvider specified.");
       return -1; // Unchanged; it is, whatever it is.
     } else {
       return insertProviderAt(prefJCEProvider, 1);
     }
   } catch (NoSuchProviderException ex) {
     // Will already have logged with exception msg.
     String msg = "failed to load *preferred* " + "JCE crypto provider, " + prefJCEProvider;
     logger.always(Logger.SECURITY_AUDIT, msg); // Per NSA suggestion.
     logger.error(Logger.SECURITY_FAILURE, msg);
     throw ex;
   }
 }
 /**
  * Allows users to retrieve their CSRF token for the CSRF Challenge 6 module
  *
  * @param myMessage To Be stored as the users message for this module
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // Setting IpAddress To Log and taking header for original IP if forwarded from proxy
   ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
   log.debug("Cross-SiteForegery Challenge Get Token Six Servlet");
   PrintWriter out = response.getWriter();
   out.print(getServletInfo());
   try {
     HttpSession ses = request.getSession(true);
     if (Validate.validateSession(ses)) {
       log.debug(levelName + " servlet accessed by: " + ses.getAttribute("userName").toString());
       String htmlOutput = new String("Your csrf Token for this Challenge is: ");
       String userId = request.getParameter("userId").toString();
       Encoder encoder = ESAPI.encoder();
       Connection conn =
           Database.getChallengeConnection(
               getServletContext().getRealPath(""), "csrfChallengeSix");
       try {
         log.debug("Preparing setCsrfChallengeSixToken call");
         PreparedStatement callstmnt =
             conn.prepareStatement(
                 "SELECT csrfTokenscol FROM csrfchallengesix.csrfTokens WHERE userId LIKE ?");
         callstmnt.setString(1, userId);
         log.debug("Executing setCsrfChallengeSixTokenQuery");
         ResultSet rs = callstmnt.executeQuery();
         int i = 0;
         while (rs.next()) {
           i++;
           htmlOutput += encoder.encodeForHTML("\"" + rs.getString(1) + "\"") + " <br/>";
         }
         log.debug("Returned " + i + " CSRF Tokens for ID: " + userId);
         conn.close();
       } catch (Exception e) {
         log.debug("Could not retrieve Challenge CSRF Tokens");
         htmlOutput = "Was unable to retrieve CSRF Token. Funky";
       }
       out.write(htmlOutput);
     }
   } catch (Exception e) {
     out.write("An Error Occurred! You must be getting funky!");
   }
 }
Ejemplo n.º 23
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    String sql = "SELECT * from USERS where USERNAME='******' and PASSWORD='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      statement.execute(sql, new int[] {1, 2});
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
Ejemplo n.º 24
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("vector");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    byte[] input = new byte[1000];
    String str = "?";
    Object inputParam = param;
    if (inputParam instanceof String) str = ((String) inputParam);
    if (inputParam instanceof java.io.InputStream) {
      int i = ((java.io.InputStream) inputParam).read(input);
      if (i == -1) {
        response
            .getWriter()
            .println(
                "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
        return;
      }
      str = new String(input, 0, i);
    }
    javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str);

    cookie.setSecure(false);

    response.addCookie(cookie);

    response
        .getWriter()
        .println(
            "Created cookie: 'SomeCookie': with value: '"
                + org.owasp.esapi.ESAPI.encoder().encodeForHTML(str)
                + "' and secure flag set to: false");
  } // end doPost
Ejemplo n.º 25
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheValue("vector");

    String bar = doSomething(param);

    byte[] input = new byte[1000];
    String str = "?";
    Object inputParam = param;
    if (inputParam instanceof String) str = ((String) inputParam);
    if (inputParam instanceof java.io.InputStream) {
      int i = ((java.io.InputStream) inputParam).read(input);
      if (i == -1) {
        response
            .getWriter()
            .println(
                "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
        return;
      }
      str = new String(input, 0, i);
    }
    javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str);

    cookie.setSecure(true);
    cookie.setPath("/benchmark/" + this.getClass().getSimpleName());

    response.addCookie(cookie);

    response
        .getWriter()
        .println(
            "Created cookie: SomeCookie: with value: '"
                + org.owasp.esapi.ESAPI.encoder().encodeForHTML(str)
                + "' and secure flag set to: true");
  } // end doPost
Ejemplo n.º 26
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheValue("vector");

    String bar = "alsosafe";
    if (param != null) {
      java.util.List<String> valuesList = new java.util.ArrayList<String>();
      valuesList.add("safe");
      valuesList.add(param);
      valuesList.add("moresafe");

      valuesList.remove(0); // remove the 1st safe value

      bar = valuesList.get(1); // get the last 'safe' value
    }

    try {
      String sql = "SELECT * from USERS where USERNAME='******' and PASSWORD='******'";

      org.owasp.benchmark.helpers.DatabaseHelper.JDBCtemplate.execute(sql);
      java.io.PrintWriter out = response.getWriter();
      //		System.out.println("no results for query: " + sql + " because the Spring execute method
      // doesn't return results.");
      out.write(
          "No results can be displayed for query: "
              + org.owasp.esapi.ESAPI.encoder().encodeForHTML(sql)
              + "<br>");
      out.write(" because the Spring execute method doesn't return results.");
    } catch (org.springframework.dao.DataAccessException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  }
Ejemplo n.º 27
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    javax.servlet.http.Cookie[] theCookies = request.getCookies();

    String param = "";
    if (theCookies != null) {
      for (javax.servlet.http.Cookie theCookie : theCookies) {
        if (theCookie.getName().equals("vector")) {
          param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
          break;
        }
      }
    }

    org.owasp.benchmark.helpers.ThingInterface thing =
        org.owasp.benchmark.helpers.ThingFactory.createThing();
    String bar = thing.doSomething(param);

    try {
      String sql = "SELECT TOP 1 userid from USERS where USERNAME='******' and PASSWORD='******'";

      java.util.Map results =
          org.owasp.benchmark.helpers.DatabaseHelper.JDBCtemplate.queryForMap(sql);
      java.io.PrintWriter out = response.getWriter();
      out.write("Your results are: ");
      //		System.out.println("Your results are");
      out.write(org.owasp.esapi.ESAPI.encoder().encodeForHTML(results.toString()));
      //		System.out.println(results.toString());
    } catch (org.springframework.dao.DataAccessException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  }
Ejemplo n.º 28
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("vector");
    if (param == null) param = "";

    String bar = new Test().doSomething(param);

    String fileName = null;
    java.io.FileOutputStream fos = null;

    try {
      fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;

      fos = new java.io.FileOutputStream(fileName, false);
      response
          .getWriter()
          .write(
              "Now ready to write to file: "
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName));
    } catch (Exception e) {
      System.out.println("Couldn't open FileOutputStream on file: '" + fileName + "'");
      //			System.out.println("File exception caught and swallowed: " + e.getMessage());
    } finally {
      if (fos != null) {
        try {
          fos.close();
          fos = null;
        } catch (Exception e) {
          // we tried...
        }
      }
    }
  } // end doPost
Ejemplo n.º 29
0
 public String login() throws AmadorProException {
   LoginTO to = new LoginTO();
   try {
     BeanUtils.copyProperties(to, this);
   } catch (IllegalAccessException e) {
     throw new AmadorProException(e);
   } catch (InvocationTargetException e) {
     throw new AmadorProException(e);
   }
   boolean isLogged = LoginHelper.login(to);
   if (!isLogged) {
     addMessagePagePanel("Username e/ou Senha Invalidos");
   } else {
     try {
       // troca o identificador de sessao
       // Logger log = ESAPI.getLogger(this.getClass());
       ESAPI.httpUtilities().changeSessionIdentifier(FacesUtil.getRequest());
       System.out.println("depois " + FacesUtil.getRequest().getSession(false).getId());
     } catch (AuthenticationException e) {
       throw new AmadorProException(e);
     }
   }
   return isLogged ? Constants.SUCCESS : Constants.ERROR;
 }
  /**
   * A user with the submitted email address is set a new random password, the password is also
   * returned from the database procedure and is forwards through to the HTTP response. This
   * response is not consumed by the client interface by default, and the user will have to discover
   * it.
   *
   * @param subEmail Sub schema user email address
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    HttpSession ses = request.getSession(true);

    // Translation Stuff
    Locale locale = new Locale(Validate.validateLanguage(request.getSession()));
    ResourceBundle errors = ResourceBundle.getBundle("i18n.servlets.errors", locale);
    ResourceBundle bundle =
        ResourceBundle.getBundle(
            "i18n.servlets.challenges.sessionManagement.sessionManagement2", locale);

    if (Validate.validateSession(ses)) {
      ShepherdLogManager.setRequestIp(
          request.getRemoteAddr(),
          request.getHeader("X-Forwarded-For"),
          ses.getAttribute("userName").toString());
      log.debug(levelName + " servlet accessed by: " + ses.getAttribute("userName").toString());
      PrintWriter out = response.getWriter();
      out.print(getServletInfo());
      Encoder encoder = ESAPI.encoder();
      String htmlOutput = new String();
      log.debug(levelName + " Servlet accessed");
      try {
        log.debug("Getting Challenge Parameter");
        Object emailObj = request.getParameter("subEmail");
        String subEmail = new String();
        if (emailObj != null) subEmail = (String) emailObj;
        log.debug("subEmail = " + subEmail);

        log.debug("Getting ApplicationRoot");
        String ApplicationRoot = getServletContext().getRealPath("");

        String newPassword = Hash.randomString();
        try {
          Connection conn =
              Database.getChallengeConnection(ApplicationRoot, "BrokenAuthAndSessMangChalTwo");
          log.debug("Checking credentials");
          PreparedStatement callstmt =
              conn.prepareStatement("UPDATE users SET userPassword = SHA(?) WHERE userAddress = ?");
          callstmt.setString(1, newPassword);
          callstmt.setString(2, subEmail);
          log.debug("Executing resetPassword");
          callstmt.execute();
          log.debug("Statement executed");

          log.debug("Committing changes made to database");
          callstmt = conn.prepareStatement("COMMIT");
          callstmt.execute();
          log.debug("Changes committed.");

          htmlOutput = encoder.encodeForHTML(newPassword);
          Database.closeConnection(conn);
        } catch (SQLException e) {
          log.error(levelName + " SQL Error: " + e.toString());
        }
        log.debug("Outputting HTML");
        out.write(bundle.getString("response.changedTo") + " " + htmlOutput);
      } catch (Exception e) {
        out.write(errors.getString("error.funky"));
        log.fatal(levelName + " - " + e.toString());
      }
    } else {
      log.error(levelName + " servlet accessed with no session");
    }
  }