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  
52  import org.apache.commons.lang3.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * Filter that handles setup and validation of tokens to prevent CSRF attacks.
58   *
59   * This provides additional layer of security in addition to Referrer-checking {@link CsrfSecurityFilter}.
60   *
61   * <p>This filter passes if:</p>
62   * <ul>
63   * <li>the method is not POST</li>
64   * <li>CSRF token passed as request parameter matches the value of CSRF token saved in session.</li>
65   * </ul>
66   *
67   * <p>To provide flexibility, check is performed with voter in the filters bypasses node.
68   * The default bypass configured is:</p>
69   * <ul>
70   * <li>Bypass any request url that starts with '/.'.</li>
71   * </ul>
72   *
73   * <p>To add more bypasses (i.e. to 'white-list' specific referrer domains or uris) use for example:</p>
74   * <ul>
75   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternSimpleVoter} or</li>
76   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternRegexVoter}.</li>
77   * </ul>
78   *
79   * @see <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">Cross-Site
80   *      Request Forgery (CSRF) Prevention Cheat Sheet</a>
81   */
82  public class CsrfTokenSecurityFilter extends AbstractMgnlFilter {
83  
84      private static final Logger log = LoggerFactory.getLogger(CsrfTokenSecurityFilter.class);
85  
86      static final String CSRF_ATTRIBUTE_NAME = "csrf";
87      private static final String EVENT_TYPE = "Possible CSRF Attack";
88  
89      private Random random = new SecureRandom();
90  
91      private final Provider<Context> contextProvider;
92  
93      @Inject
94      public CsrfTokenSecurityFilter(final Provider<Context> contextProvider) {
95          this.contextProvider = contextProvider;
96      }
97  
98      @Override
99      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
100         if (request.getMethod().equals("POST")) {
101             final String token = request.getParameter(CSRF_ATTRIBUTE_NAME);
102             if (StringUtils.isBlank(token)) {
103                 csrfTokenMissing(request, response, request.getServletPath());
104                 return;
105             }
106             if (!token.equals(request.getSession().getAttribute(CSRF_ATTRIBUTE_NAME))) {
107                 csrfTokenMismatch(request, response, request.getServletPath());
108                 return;
109             }
110         } else {
111             if (request.getSession().getAttribute(CSRF_ATTRIBUTE_NAME) == null) {
112                 request.getSession().setAttribute(CSRF_ATTRIBUTE_NAME, generateSafeToken());
113             }
114         }
115         chain.doFilter(request, response);
116     }
117 
118     private void csrfTokenMissing(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
119         final String auditDetails = String.format("CSRF token not set while user '%s' attempted to access url '%s'.", contextProvider.get().getUser().getName(), url);
120         handleError(request, response, auditDetails);
121     }
122 
123     private void csrfTokenMismatch(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
124         final String auditDetails = String.format("CSRF token mismatched while user '%s' attempted to access url '%s'.", contextProvider.get().getUser().getName(), url);
125         handleError(request, response, auditDetails);
126     }
127 
128     /**
129      * Actions to take when a CSRF attack is detected.
130      * Log a message and send {@link HttpServletResponse#SC_FORBIDDEN} error response.
131      */
132     protected void handleError(HttpServletRequest request, HttpServletResponse response, String message) throws IOException {
133         auditLogging(request, response, message);
134         response.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF token mismatch possibly caused by expired session. Please re-open the page and submit the form again.");
135     }
136 
137     private void auditLogging(HttpServletRequest request, HttpServletResponse response, String auditDetails) throws IOException {
138         log.warn("{}. {}", new Object[]{EVENT_TYPE, auditDetails});
139         AuditLoggingUtil.logSecurity(request.getRemoteAddr(), EVENT_TYPE, auditDetails);
140     }
141 
142     private String generateSafeToken() {
143         byte bytes[] = new byte[20];
144         random.nextBytes(bytes);
145         Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
146         String token = encoder.encodeToString(bytes);
147         return token;
148     }
149 
150 }