View Javadoc

1   /**
2    * This file Copyright (c) 2014 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.MgnlContext;
39  
40  import java.io.IOException;
41  import java.net.URI;
42  import java.net.URISyntaxException;
43  
44  import javax.servlet.FilterChain;
45  import javax.servlet.ServletException;
46  import javax.servlet.http.HttpServletRequest;
47  import javax.servlet.http.HttpServletResponse;
48  
49  import org.apache.commons.lang.StringUtils;
50  import org.slf4j.Logger;
51  import org.slf4j.LoggerFactory;
52  
53  /**
54   * Ensure that the request is not a CSRF attack.
55   *
56   * <p>This filter passes if:</p>
57   * <ul>
58   * <li>The referrer header is not blank.</li>
59   * <li>The host of header referrer request domain matches the actual requested host.</li>
60   * </ul>
61   *
62   * <p>To provide flexibility, two of the key checks are performed with voters in the filters bypasses node.
63   * The default bypasses configured are:</p>
64   * <ul>
65   * <li>Bypass any request url that doesn't start with '/.magnolia'.</li>
66   * <li>Bypass all non-authenticated requests.</li>
67   * </ul>
68   *
69   * <p>To add more bypasses (i.e. to 'white-list' specific referrer domains or uris) use for example:</p>
70   * <ul>
71   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternSimpleVoter} or</li>
72   * <li>{@link info.magnolia.voting.voters.RequestHeaderPatternRegexVoter}.</li>
73   * </ul>
74   *
75   * @see <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">Cross-Site
76   * Request Forgery (CSRF) Prevention Cheat Sheet</a>
77   */
78  public class CsrfSecurityFilter extends AbstractMgnlFilter {
79  
80      private static final Logger log = LoggerFactory.getLogger(CsrfSecurityFilter.class);
81  
82      public static final String REFERRER = "referer"; // Referrer header key is badly spelled in rfc1945
83  
84      @Override
85      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
86          final String referrerURL = request.getHeader(REFERRER);
87          final String actualURL = request.getRequestURL().toString();
88  
89          try {
90              if (StringUtils.isEmpty(referrerURL)) {
91                  handlePossibleCsrf(request, response, actualURL);
92                  return;
93              }
94  
95              final String referrerHost = new URI(referrerURL).getHost();
96              final String actualHost = new URI(actualURL).getHost();
97              if (referrerHost == null || !referrerHost.equalsIgnoreCase(actualHost)) {
98                  handlePossibleCsrf(request, response, actualURL);
99                  return;
100             }
101         } catch (URISyntaxException ex) {
102             handlePossibleCsrf(request, response, actualURL);
103             return;
104         }
105 
106         chain.doFilter(request, response);
107     }
108 
109     /**
110      * Actions to take when a CSRF attack is detected.
111      * Log a message and set response to {@link HttpServletResponse#SC_BAD_REQUEST}.
112      */
113     protected void handlePossibleCsrf(HttpServletRequest request, HttpServletResponse response, String url) {
114         final String eventType = "Possible CSRF Attack";
115         final String auditDetails = String.format("Referrer was null or referrer- and request-host did not match. User '%s' attempted to access url '%s'.", MgnlContext.getUser().getName(), url);
116         log.warn("{}. {}", new Object[]{eventType, auditDetails});
117         AuditLoggingUtil.logSecurity(request.getRemoteAddr(), eventType, auditDetails);
118 
119         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
120     }
121 
122 }