コード例 #1
0
  public void updateTokens(HttpServletRequest request) {
    /** cannot create sessions if response already committed * */
    HttpSession session = request.getSession(false);

    if (session != null) {
      /** create master token if it does not exist * */
      updateToken(session);

      /** create page specific token * */
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        /** first time initialization * */
        if (pageTokens == null) {
          pageTokens = new HashMap<String, String>();
          session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens);
        }

        /** create token if it does not exist * */
        if (isProtectedPageAndMethod(request)) {
          createPageToken(pageTokens, request.getRequestURI());
        }
      }
    }
  }
コード例 #2
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
コード例 #3
0
  private void verifySessionToken(HttpServletRequest request) throws CsrfGuardException {
    HttpSession session = request.getSession(true);
    String tokenFromSession = (String) session.getAttribute(getSessionKey());
    String tokenFromRequest = request.getParameter(getTokenName());

    if (tokenFromRequest == null) {
      /** FAIL: token is missing from the request * */
      throw new CsrfGuardException("required token is missing from the request");
    } else if (!tokenFromSession.equals(tokenFromRequest)) {
      /** FAIL: the request token does not match the session token * */
      throw new CsrfGuardException("request token does not match session token");
    }
  }
コード例 #4
0
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
コード例 #5
0
  protected static String getString(
      HttpServletRequest request, String propertyName, String propertyValueDefault) {
    String res = null;

    {
      try {
        Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal != null) {
          PreferenceAccessorFactory f = DefaultPreferenceAccessorFactory.getInstance();
          PreferenceAccessor a = f.getUserPreferenceAccessor();

          res = a.getPreferenceProperty(userPrincipal, propertyName);

          if (res == null || res.length() == 0) {
            if (propertyValueDefault != null) {
              res = propertyValueDefault;
            }
          }
        }
      } catch (Throwable ex) {
        ex.printStackTrace(); // TODO: Log!
      }
    }

    return res;
  }
コード例 #6
0
  private void verifyPageToken(HttpServletRequest request) throws CsrfGuardException {
    HttpSession session = request.getSession(true);
    @SuppressWarnings("unchecked")
    Map<String, String> pageTokens =
        (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

    String tokenFromPages = (pageTokens != null ? pageTokens.get(request.getRequestURI()) : null);
    String tokenFromSession = (String) session.getAttribute(getSessionKey());
    String tokenFromRequest = request.getParameter(getTokenName());

    if (tokenFromRequest == null) {
      /** FAIL: token is missing from the request * */
      throw new CsrfGuardException("required token is missing from the request");
    } else if (tokenFromPages != null) {
      if (!tokenFromPages.equals(tokenFromRequest)) {
        /** FAIL: request does not match page token * */
        throw new CsrfGuardException("request token does not match page token");
      }
    } else if (!tokenFromSession.equals(tokenFromRequest)) {
      /** FAIL: the request token does not match the session token * */
      throw new CsrfGuardException("request token does not match session token");
    }
  }
コード例 #7
0
  protected static void setString(
      HttpServletRequest request, String propertyName, String propertyValue) {
    try {
      Principal userPrincipal = request.getUserPrincipal();
      if (userPrincipal != null) {
        PreferenceAccessorFactory f = DefaultPreferenceAccessorFactory.getInstance();
        PreferenceAccessor a = f.getUserPreferenceAccessor();

        a.setPreferenceProperty(userPrincipal, propertyName, propertyValue);
      }
    } catch (Throwable ex) {
      ex.printStackTrace(); // TODO: Log!
    }
  }
コード例 #8
0
  public static void setMenuPropertyValue(HttpServletRequest request, Integer v) {
    try {
      Principal userPrincipal = request.getUserPrincipal();
      if (userPrincipal != null) {
        PreferenceAccessorFactory f = DefaultPreferenceAccessorFactory.getInstance();
        PreferenceAccessor a = f.getUserPreferenceAccessor();

        if (v == null) {
          a.setPreferenceProperty(userPrincipal, MENU_PROPERTY_NAME, null);
        } else {
          String value = v.toString();
          a.setPreferenceProperty(userPrincipal, MENU_PROPERTY_NAME, value);
        }
      }
    } catch (Throwable ex) {
      ex.printStackTrace(); // TODO: Log!
    }
  }
コード例 #9
0
  public boolean isValidRequest(HttpServletRequest request, HttpServletResponse response) {
    boolean valid = !isProtectedPageAndMethod(request);
    HttpSession session = request.getSession(true);
    String tokenFromSession = (String) session.getAttribute(getSessionKey());

    /** sending request to protected resource - verify token * */
    if (tokenFromSession != null && !valid) {
      try {
        if (isAjaxEnabled() && isAjaxRequest(request)) {
          verifyAjaxToken(request);
        } else if (isTokenPerPageEnabled()) {
          verifyPageToken(request);
        } else {
          verifySessionToken(request);
        }
        valid = true;
      } catch (CsrfGuardException csrfe) {
        for (IAction action : getActions()) {
          try {
            action.execute(request, response, csrfe, this);
          } catch (CsrfGuardException exception) {
            getLogger().log(LogLevel.Error, exception);
          }
        }
      }

      /** rotate session and page tokens * */
      if (!isAjaxRequest(request) && isRotateEnabled()) {
        rotateTokens(request);
      }
      /** expected token in session - bad state * */
    } else if ((tokenFromSession == null) && !valid) {
      throw new IllegalStateException(
          "CsrfGuard expects the token to exist in session at this point");
    } else {
      /** unprotected page - nothing to do * */
    }

    return valid;
  }
コード例 #10
0
  private static Integer getMenuPropertyValue(HttpServletRequest request) {
    Integer res = null;

    {
      try {
        Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal != null) {
          PreferenceAccessorFactory f = DefaultPreferenceAccessorFactory.getInstance();
          PreferenceAccessor a = f.getUserPreferenceAccessor();

          String name = a.getPreferenceProperty(userPrincipal, MENU_PROPERTY_NAME);
          if (name != null) {
            res = Integer.parseInt(name);
          }
        }
      } catch (Throwable ex) {
        ex.printStackTrace(); // TODO: Log!
      }
    }

    return res;
  }
コード例 #11
0
 public boolean isProtectedPageAndMethod(HttpServletRequest request) {
   return isProtectedPageAndMethod(request.getRequestURI(), request.getMethod());
 }
コード例 #12
0
 private boolean isAjaxRequest(HttpServletRequest request) {
   return request.getHeader("X-Requested-With") != null;
 }
コード例 #13
0
  public void writeLandingPage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String landingPage = getNewTokenLandingPage();

    /** default to current page * */
    if (landingPage == null) {
      StringBuilder sb = new StringBuilder();

      sb.append(request.getContextPath());
      sb.append(request.getServletPath());

      landingPage = sb.toString();
    }

    /** create auto posting form * */
    StringBuilder sb = new StringBuilder();

    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>OWASP CSRFGuard Project - New Token Landing Page</title>\r\n");
    sb.append("</head>\r\n");
    sb.append("<body>\r\n");
    sb.append("<script type=\"text/javascript\">\r\n");
    sb.append("var form = document.createElement(\"form\");\r\n");
    sb.append("form.setAttribute(\"method\", \"post\");\r\n");
    sb.append("form.setAttribute(\"action\", \"");
    sb.append(landingPage);
    sb.append("\");\r\n");

    /** only include token if needed * */
    if (isProtectedPage(landingPage)) {
      sb.append("var hiddenField = document.createElement(\"input\");\r\n");
      sb.append("hiddenField.setAttribute(\"type\", \"hidden\");\r\n");
      sb.append("hiddenField.setAttribute(\"name\", \"");
      sb.append(getTokenName());
      sb.append("\");\r\n");
      sb.append("hiddenField.setAttribute(\"value\", \"");
      sb.append(getTokenValue(request, landingPage));
      sb.append("\");\r\n");
      sb.append("form.appendChild(hiddenField);\r\n");
    }

    sb.append("document.body.appendChild(form);\r\n");
    sb.append("form.submit();\r\n");
    sb.append("</script>\r\n");
    sb.append("</body>\r\n");
    sb.append("</html>\r\n");

    String code = sb.toString();

    /** setup headers * */
    response.setContentType("text/html");
    response.setContentLength(code.length());

    /** write auto posting form * */
    OutputStream output = null;
    PrintWriter writer = null;

    try {
      output = response.getOutputStream();
      writer = new PrintWriter(output);

      writer.write(code);
      writer.flush();
    } finally {
      Writers.close(writer);
      Streams.close(output);
    }
  }
コード例 #14
0
 public String getTokenValue(HttpServletRequest request) {
   return getTokenValue(request, request.getRequestURI());
 }