View Javadoc
1   /**
2    * This file Copyright (c) 2003-2016 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      private boolean validateContentType = false;
83  
84      private ServerConfiguration serverConfiguration;
85  
86      /**
87       * @deprecated since 5.4.2, use {@link #ContentTypeFilter(ServerConfiguration)} instead.
88       */
89      @Deprecated
90      public ContentTypeFilter() {
91      }
92  
93      @Inject
94      public ContentTypeFilter(ServerConfiguration serverConfiguration) {
95          this.serverConfiguration = serverConfiguration;
96      }
97  
98  
99      @Override
100     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
101 
102         // we will set the original uri, to avoid conflicts we have to reset the aggregation state
103         // this will mainly reset the original uri and keep all other information
104         if (request.getAttribute(AGGREGATION_STATE_INITIALIZED) != null) {
105             MgnlContext.resetAggregationState();
106         } else {
107             request.setAttribute(AGGREGATION_STATE_INITIALIZED, Boolean.TRUE);
108         }
109 
110         final String originalUri = ServletUtil.getOriginalRequestURI(request);
111         final String originalUrl = ServletUtil.getOriginalRequestURLIncludingQueryString(request);
112         final String extension = getUriExtension(originalUri);
113         final String mimeType = getMimeType(extension, response);
114         if (isRegisteredExtensionsOnly() && mimeType == null && !response.isCommitted()) {
115             response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unsupported extension=%1$s.", extension));
116             return;
117         }
118         final String characterEncoding = setupCharacterEncoding(mimeType, request, response);
119         final AggregationState aggregationState = MgnlContext.getAggregationState();
120         aggregationState.setCharacterEncoding(characterEncoding);
121 
122         final String decodedOriginalUri = decodeUri(originalUri, characterEncoding);
123         aggregationState.setOriginalURI(decodedOriginalUri);
124 
125         try {
126             final String decodedOriginalUrl = decodeUri(originalUrl, characterEncoding);
127             aggregationState.setOriginalURL(decodedOriginalUrl);
128         } catch (IllegalArgumentException e) {
129             // URL is malformed and cannot be decoded - send back error 400
130             if (!response.isCommitted()) {
131                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL is malformed (not encoded properly).");
132             }
133             // stop filter chain
134             return;
135         }
136         aggregationState.setOriginalBrowserURI(originalUri);
137         aggregationState.setOriginalBrowserURL(originalUrl);
138         final String requestURI = URI.create(ServletUtil.getRequestUri(request)).normalize().getRawPath();
139         final String currentURI = decodeUri(requestURI, characterEncoding);
140         aggregationState.setCurrentURI(currentURI);
141         aggregationState.setExtension(extension);
142         aggregationState.setQueryString(request.getQueryString());
143 
144         if (isValidateContentType()) {
145             ContentTypeCheckingResponseWrapper resWrapper = new ContentTypeCheckingResponseWrapper(response, extension);
146             chain.doFilter(request, resWrapper);
147         } else {
148             chain.doFilter(request, response);
149         }
150         if (response.getContentType() == null) { //if the content type was not set (e.g. in renderer), set it so we don't produce a response without the content type
151             response.setContentType(mimeType);
152         }
153     }
154 
155     protected String getUriExtension(String uri) {
156         final String fileName = StringUtils.substringAfterLast(uri, "/");
157         return StringUtils.substringAfterLast(fileName, ".");
158     }
159 
160     protected String getMimeType(String extension, HttpServletResponse response) {
161         final String mimeType;
162 
163         if (isRegisteredExtensionsOnly()) {
164             if (StringUtils.isBlank(extension)) {
165                 extension = serverConfiguration.getDefaultExtension();
166                 if (StringUtils.isBlank(extension)) {
167                     extension = MIMEMapping.DEFAULT_EXTENSION;
168                 }
169             }
170             mimeType = MIMEMapping.getMIMEType(extension);
171             if (mimeType == null) {
172                 return null;
173             }
174         } else {
175             mimeType = MIMEMapping.getMIMETypeOrDefault(extension);
176         }
177 
178         return mimeType;
179     }
180 
181     protected String setupCharacterEncoding(String mimeType, HttpServletRequest request, HttpServletResponse response) {
182         final String characterEncoding = MIMEMapping.getContentEncodingOrDefault(mimeType);
183 
184         try {
185             // let's not override the request encoding if set by the servlet container or the requesting browser
186             if (request.getCharacterEncoding() == null) {
187                 request.setCharacterEncoding(characterEncoding);
188             }
189         } catch (UnsupportedEncodingException e) {
190             log.error("Can't set character encoding for the request (mimetype={})", mimeType, e);
191         }
192 
193         response.setCharacterEncoding(characterEncoding);
194 
195         return characterEncoding;
196     }
197 
198     /**
199      * XSS escaping of a substring after last dot in uri for preventing XSS attack.
200      * If uri doesn't contain dot, the same uri will be returned.
201      * @param uri the uri whose substring after last dot will be XSS escaped.
202      */
203     private String sanitizeXss(String uri) {
204         final String afterLastDot = StringUtils.substringAfterLast(uri, ".");
205         if (StringUtils.isNotEmpty(afterLastDot)) {
206             final String xssEscapedAfterLastDot = EscapeUtil.escapeXss(afterLastDot);
207             final String sanitizedXssUri = StringUtils.removeEnd(uri, afterLastDot).concat(xssEscapedAfterLastDot);
208             return sanitizedXssUri;
209         }
210 
211         return uri;
212     }
213 
214     /**
215      * Decodes an URI using given character encoding and sanitizes the URI against XSS if configured.
216      */
217     private String decodeUri(String uri, String characterEncoding) throws UnsupportedEncodingException {
218         final String decodedUri = URLDecoder.decode(uri, characterEncoding);
219         return isSanitizeXssUri() ? sanitizeXss(decodedUri) : decodedUri;
220     }
221 
222     public boolean isSanitizeXssUri() {
223         return sanitizeXssUri;
224     }
225 
226     public void setSanitizeXssUri(boolean sanitizeXssUri) {
227         this.sanitizeXssUri = sanitizeXssUri;
228     }
229 
230     public boolean isRegisteredExtensionsOnly() {
231         return registeredExtensionsOnly;
232     }
233 
234     public void setRegisteredExtensionsOnly(boolean registeredExtensionsOnly) {
235         this.registeredExtensionsOnly = registeredExtensionsOnly;
236     }
237 
238     public boolean isValidateContentType() {
239         return validateContentType;
240     }
241 
242     public void setValidateContentType(boolean validateContentType) {
243         this.validateContentType = validateContentType;
244     }
245 
246     /**
247      * @deprecated since 5.4.2, use {@link #getMimeType(String, HttpServletResponse)} and {@link #setupCharacterEncoding(String, HttpServletRequest, HttpServletResponse)} instead.
248      */
249     @Deprecated
250     protected String setupContentTypeAndCharacterEncoding(String extension, HttpServletRequest request, HttpServletResponse response) {
251         final String mimeType = setupContentType(extension, response);
252         return setupCharacterEncoding(mimeType, request, response);
253     }
254 
255     /**
256      * @deprecated since 5.3.13 & 5.4.2, use {@link #getMimeType(String, HttpServletResponse)} instead.
257      */
258     @Deprecated
259     protected String setupContentType(String extension, HttpServletResponse response) {
260         return getMimeType(extension, response);
261     }
262 }