View Javadoc
1   /**
2    * This file Copyright (c) 2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.security;
35  
36  import info.magnolia.audit.AuditLoggingUtil;
37  import info.magnolia.cms.filters.AbstractMgnlFilter;
38  import info.magnolia.context.Context;
39  
40  import java.io.IOException;
41  import java.security.SecureRandom;
42  import java.util.Base64;
43  import java.util.Random;
44  
45  import javax.inject.Inject;
46  import javax.inject.Provider;
47  import javax.servlet.FilterChain;
48  import javax.servlet.ServletException;
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  import javax.servlet.http.HttpSession;
52  
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  /**
58   * Filter that handles setup and validation of tokens to prevent CSRF attacks.
59   *
60   * This provides additional layer of security in addition to Referrer-checking {@link CsrfSecurityFilter}.
61   *
62   * <p>This filter passes if:</p>
63   * <ul>
64   * <li>the method is not POST</li>
65   * <li>CSRF token passed as request parameter matches the value of CSRF token saved in session.</li>
66   * </ul>
67   *
68   * <p>To provide flexibility, check is performed with voter in the filters bypasses node.
69   * The default bypass configured is:</p>
70   * <ul>
71   * <li>Bypass any request url that starts with '/.'.</li>
72   * </ul>
73   *
74   * <p>To add more bypasses (i.e. to 'white-list' specific referrer domains or uris) use for example:</p>
75   * <ul>
76   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternSimpleVoter} or</li>
77   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternRegexVoter}.</li>
78   * </ul>
79   *
80   * @see <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">Cross-Site
81   *      Request Forgery (CSRF) Prevention Cheat Sheet</a>
82   */
83  public class CsrfTokenSecurityFilter extends AbstractMgnlFilter {
84  
85      private static final Logger log = LoggerFactory.getLogger(CsrfTokenSecurityFilter.class);
86  
87      static final String CSRF_ATTRIBUTE_NAME = "csrf";
88      private static final String EVENT_TYPE = "Possible CSRF Attack";
89  
90      private Random random = new SecureRandom();
91  
92      private final Provider<Context> contextProvider;
93  
94      @Inject
95      public CsrfTokenSecurityFilter(final Provider<Context> contextProvider) {
96          this.contextProvider = contextProvider;
97      }
98  
99      @Override
100     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
101         HttpSession session = request.getSession(false);
102         if (request.getMethod().equals("POST")
103                 && session != null && !session.isNew()) {
104             String token = request.getParameter(CSRF_ATTRIBUTE_NAME);
105             if (StringUtils.isBlank(token)) {
106                 csrfTokenMissing(request, response, request.getServletPath());
107                 return;
108             }
109             if (!token.equals(session.getAttribute(CSRF_ATTRIBUTE_NAME))) {
110                 csrfTokenMismatch(request, response, request.getServletPath());
111                 return;
112             }
113         } else if (session != null && session.getAttribute(CSRF_ATTRIBUTE_NAME) == null) {
114             session.setAttribute(CSRF_ATTRIBUTE_NAME, generateSafeToken());
115         }
116         chain.doFilter(request, response);
117     }
118 
119     private void csrfTokenMissing(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
120         final String auditDetails = String.format("CSRF token not set while user '%s' attempted to access url '%s'.", contextProvider.get().getUser().getName(), url);
121         handleError(request, response, auditDetails);
122     }
123 
124     private void csrfTokenMismatch(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
125         final String auditDetails = String.format("CSRF token mismatched while user '%s' attempted to access url '%s'.", contextProvider.get().getUser().getName(), url);
126         handleError(request, response, auditDetails);
127     }
128 
129     /**
130      * Actions to take when a CSRF attack is detected.
131      * Log a message and send {@link HttpServletResponse#SC_FORBIDDEN} error response.
132      */
133     protected void handleError(HttpServletRequest request, HttpServletResponse response, String message) throws IOException {
134         auditLogging(request, response, message);
135         response.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF token mismatch possibly caused by expired session. Please re-open the page and submit the form again.");
136     }
137 
138     private void auditLogging(HttpServletRequest request, HttpServletResponse response, String auditDetails) throws IOException {
139         log.warn("{}. {}", new Object[]{EVENT_TYPE, auditDetails});
140         AuditLoggingUtil.logSecurity(request.getRemoteAddr(), EVENT_TYPE, auditDetails);
141     }
142 
143     private String generateSafeToken() {
144         byte bytes[] = new byte[20];
145         random.nextBytes(bytes);
146         Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
147         String token = encoder.encodeToString(bytes);
148         return token;
149     }
150 
151 }