View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 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.filters;
35  
36  import info.magnolia.cms.beans.config.MIMEMapping;
37  import info.magnolia.cms.beans.config.ServerConfiguration;
38  import info.magnolia.cms.core.AggregationState;
39  import info.magnolia.cms.util.ServletUtil;
40  import info.magnolia.context.MgnlContext;
41  import info.magnolia.util.EscapeUtil;
42  
43  import java.io.IOException;
44  import java.io.UnsupportedEncodingException;
45  import java.net.URI;
46  import java.net.URLDecoder;
47  
48  import javax.inject.Inject;
49  import javax.servlet.FilterChain;
50  import javax.servlet.ServletException;
51  import javax.servlet.http.HttpServletRequest;
52  import javax.servlet.http.HttpServletResponse;
53  
54  import org.apache.commons.lang3.StringUtils;
55  
56  
57  /**
58   * Sets content type and encoding for requests based on the uri extension and prepares uri path information in the
59   * aggregation state.
60   *
61   * TODO : rename this filter. What it really does is initialize and setup the basic,
62   * non-content related attributes of the AggregationState. ContentType could become an
63   * attribute of the AggregationState too and could be set later.
64   *
65   * FIXME: the original uri should not be reset, MAGNOLIA-3204
66   *
67   * @see MIMEMapping
68   * @see AggregationState
69   */
70  public class ContentTypeFilter extends AbstractMgnlFilter {
71  
72      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ContentTypeFilter.class);
73  
74      private boolean sanitizeXssUri = true;
75  
76      /**
77       * If set we have to reset the aggregation state before setting the original URI/URL with new values.
78       */
79      private static final String AGGREGATION_STATE_INITIALIZED = ContentTypeFilter.class.getName() + ".aggregationStateInitialized";
80  
81      private boolean registeredExtensionsOnly = false;
82  
83      private ServerConfiguration serverConfiguration;
84  
85      /**
86       * @deprecated since 5.4.2, use {@link #ContentTypeFilter(ServerConfiguration)} instead.
87       */
88      @Deprecated
89      public ContentTypeFilter() {
90      }
91  
92      @Inject
93      public ContentTypeFilter(ServerConfiguration serverConfiguration) {
94          this.serverConfiguration = serverConfiguration;
95      }
96  
97  
98      @Override
99      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
100 
101         // we will set the original uri, to avoid conflicts we have to reset the aggregation state
102         // this will mainly reset the original uri and keep all other information
103         if (request.getAttribute(AGGREGATION_STATE_INITIALIZED) != null) {
104             MgnlContext.resetAggregationState();
105         } else {
106             request.setAttribute(AGGREGATION_STATE_INITIALIZED, Boolean.TRUE);
107         }
108 
109         final String originalUri = ServletUtil.getOriginalRequestURI(request);
110         final String originalUrl = ServletUtil.getOriginalRequestURLIncludingQueryString(request);
111         final String extension = getUriExtension(originalUri);
112         final String mimeType = setupContentType(extension, response);
113         if (isRegisteredExtensionsOnly() && mimeType == null && !response.isCommitted()) {
114             response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unsupported extension=%1$s.", extension));
115             return;
116         }
117         final String characterEncoding = setupCharacterEncoding(mimeType, request, response);
118         final AggregationState aggregationState = MgnlContext.getAggregationState();
119         aggregationState.setCharacterEncoding(characterEncoding);
120 
121         final String decodedOriginalUri = decodeUri(originalUri, characterEncoding);
122         aggregationState.setOriginalURI(decodedOriginalUri);
123 
124         try {
125             final String decodedOriginalUrl = decodeUri(originalUrl, characterEncoding);
126             aggregationState.setOriginalURL(decodedOriginalUrl);
127         } catch (IllegalArgumentException e) {
128             // URL is malformed and cannot be decoded - send back error 400
129             if (!response.isCommitted()) {
130                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL is malformed (not encoded properly).");
131             }
132             // stop filter chain
133             return;
134         }
135         aggregationState.setOriginalBrowserURI(originalUri);
136         aggregationState.setOriginalBrowserURL(originalUrl);
137         final String requestURI = URI.create(ServletUtil.getRequestUri(request)).normalize().getRawPath();
138         final String currentURI = decodeUri(requestURI, characterEncoding);
139         aggregationState.setCurrentURI(currentURI);
140         aggregationState.setExtension(extension);
141         aggregationState.setQueryString(request.getQueryString());
142 
143         chain.doFilter(request, response);
144     }
145 
146     protected String getUriExtension(String uri) {
147         final String fileName = StringUtils.substringAfterLast(uri, "/");
148         return StringUtils.substringAfterLast(fileName, ".");
149     }
150 
151     protected String setupContentType(String extension, HttpServletResponse response) {
152         final String mimeType;
153 
154         if (isRegisteredExtensionsOnly()) {
155             if (StringUtils.isBlank(extension)) {
156                 extension = serverConfiguration.getDefaultExtension();
157                 if (StringUtils.isBlank(extension)) {
158                     extension = MIMEMapping.DEFAULT_EXTENSION;
159                 }
160             }
161             mimeType = MIMEMapping.getMIMEType(extension);
162             if (mimeType == null) {
163                 return null;
164             }
165         } else {
166             mimeType = MIMEMapping.getMIMETypeOrDefault(extension);
167         }
168 
169         response.setContentType(mimeType);
170 
171         return mimeType;
172     }
173 
174     protected String setupCharacterEncoding(String mimeType, HttpServletRequest request, HttpServletResponse response) {
175         final String characterEncoding = MIMEMapping.getContentEncodingOrDefault(mimeType);
176 
177         try {
178             // let's not override the request encoding if set by the servlet container or the requesting browser
179             if (request.getCharacterEncoding() == null) {
180                 request.setCharacterEncoding(characterEncoding);
181             }
182         } catch (UnsupportedEncodingException e) {
183             log.error("Can't set character encoding for the request (mimetype={})", mimeType, e);
184         }
185 
186         response.setCharacterEncoding(characterEncoding);
187 
188         return characterEncoding;
189     }
190 
191     /**
192      * XSS escaping of a substring after last dot in uri for preventing XSS attack.
193      * If uri doesn't contain dot, the same uri will be returned.
194      * @param uri the uri whose substring after last dot will be XSS escaped.
195      */
196     private String sanitizeXss(String uri) {
197         final String afterLastDot = StringUtils.substringAfterLast(uri, ".");
198         if (StringUtils.isNotEmpty(afterLastDot)) {
199             final String xssEscapedAfterLastDot = EscapeUtil.escapeXss(afterLastDot);
200             final String sanitizedXssUri = StringUtils.removeEnd(uri, afterLastDot).concat(xssEscapedAfterLastDot);
201             return sanitizedXssUri;
202         }
203 
204         return uri;
205     }
206 
207     /**
208      * Decodes an URI using given character encoding and sanitizes the URI against XSS if configured.
209      */
210     private String decodeUri(String uri, String characterEncoding) throws UnsupportedEncodingException {
211         final String decodedUri = URLDecoder.decode(uri, characterEncoding);
212         return isSanitizeXssUri() ? sanitizeXss(decodedUri) : decodedUri;
213     }
214 
215     public boolean isSanitizeXssUri() {
216         return sanitizeXssUri;
217     }
218 
219     public void setSanitizeXssUri(boolean sanitizeXssUri) {
220         this.sanitizeXssUri = sanitizeXssUri;
221     }
222 
223     public boolean isRegisteredExtensionsOnly() {
224         return registeredExtensionsOnly;
225     }
226 
227     public void setRegisteredExtensionsOnly(boolean registeredExtensionsOnly) {
228         this.registeredExtensionsOnly = registeredExtensionsOnly;
229     }
230 
231     /**
232      * @deprecated since 5.4.2, use {@link #setupContentType(String, HttpServletResponse)} and {@link #setupCharacterEncoding(String, HttpServletRequest, HttpServletResponse)} instead.
233      */
234     @Deprecated
235     protected String setupContentTypeAndCharacterEncoding(String extension, HttpServletRequest request, HttpServletResponse response) {
236         final String mimeType = setupContentType(extension, response);
237         return setupCharacterEncoding(mimeType, request, response);
238     }
239 }