예제 #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());
 }