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.context.Context;
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.http.HttpServletRequest;
45  import javax.servlet.http.HttpServletResponse;
46  
47  import org.apache.commons.lang.StringUtils;
48  import org.slf4j.Logger;
49  import org.slf4j.LoggerFactory;
50  
51  /**
52   * Ensure that the request is not a CSRF attack.
53   * See: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
54   *
55   * isAllowed should fail if:
56   * - The referrer header is blank.
57   * - The host of header referrer request domain does not match actual requested host.
58   *
59   * To provide flexibility, two of the key checks are performed with voters in the filters bypasess node, rather than explicitly here in code.
60   * The default bypasses configuration includes:
61   * - Excludes any request url that doesn't start with '/.magnolia' with a URIStartsWithVoter.
62   * - Excludes all non-authenticated requests with an AuthenticatedVoter.
63   *
64   * To 'white-list' specific referrer domains or uris, setup bypasses in the configuration for the filter
65   * using, for example, the {@link info.magnolia.voting.voters.RequestHeaderPatternSimpleVoter RequestHeaderPatternVoter} or {@link info.magnolia.voting.voters.RequestHeaderPatternRegexVoter RequestHeaderRegexVoter}.
66   */
67  public class CsrfSecurityFilter extends BaseSecurityFilter {
68  
69      private static final Logger log = LoggerFactory.getLogger(CsrfSecurityFilter.class);
70  
71      protected final String ADMINCENTRAL_LOGIN_PATH = ".magnolia/pages/adminCentral.html";
72  
73      @Override
74      public boolean isAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException {
75  
76          final String refererURL = request.getHeader("referer");
77          final String actualURL = request.getRequestURL().toString();
78  
79          try {
80              // Only perform check if not on the login page.
81              final String actualPath = new URI(actualURL).getPath();
82              if (!isLoginPage(actualPath)){
83  
84                  if (StringUtils.isEmpty(refererURL)){
85                      handlePossibleCsrf(request, response, refererURL, actualURL);
86                      return false;
87                  }
88  
89                  final String referrerHost = new URI(refererURL).getHost();
90                  final String actualHost = new URI(actualURL).getHost();
91                  if (!referrerHost.equalsIgnoreCase(actualHost)) {
92                      handlePossibleCsrf(request, response, refererURL, actualURL);
93                      return false;
94                  }
95              }
96          } catch (URISyntaxException ex) {
97              handlePossibleCsrf(request, response, refererURL, actualURL);
98              return false;
99          }
100 
101         return true;
102     }
103 
104     /**
105      * Actions to take when a CSRF attack is detected.
106      * Log, set response to forbidden, and set an attribute so the login page can display a message.
107      */
108     protected void handlePossibleCsrf(HttpServletRequest request, HttpServletResponse response, String referer, String url){
109         log.warn("Possible Csrf Attack. request.referer='{}' User {} attempts to access url '{}'.", new Object[] { referer, MgnlContext.getUser().getName(), url });
110         final String auditDetails = "request.referer='" + referer + "' attempting to access url '" + url + "'.";
111         AuditLoggingUtil.logSecurity(request.getRemoteAddr(), "Possible CSRF Attack", auditDetails);
112         MgnlContext.setAttribute(Context.ATTRIBUTE_POSSIBLE_CSRF, true);
113         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
114     }
115 
116     /**
117      * The login page will be exempted from the referrer check.
118      */
119     protected boolean isLoginPage(String actualPath){
120         final String adminCentralLoginPath = MgnlContext.getContextPath() + "/" + ADMINCENTRAL_LOGIN_PATH;
121         return adminCentralLoginPath.equals(actualPath);
122     }
123 
124 
125 }