001/**
002 * Copyright 2005-2018 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.krad.web.filter;
017
018import java.io.IOException;
019import java.util.regex.Pattern;
020
021import javax.servlet.Filter;
022import javax.servlet.FilterChain;
023import javax.servlet.FilterConfig;
024import javax.servlet.ServletException;
025import javax.servlet.ServletRequest;
026import javax.servlet.ServletResponse;
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029
030/**
031 * A simple filter that 404s any urls to embedded module WEB-INF directories.
032 * Another solution would be for the container to disable directory browsing, however
033 * files may still be accessed directly.  This filter will pre-emptively catch the URL
034 * which means that application code cannot actually handle those URLs (for instance,
035 * to do its own error handling).
036 *
037 * There is probably a better way to do this, e.g. a filter to bean proxy in some spring context,
038 * but the sample app doesn't really have a web context of its own to put this in.
039 *
040 * @author Kuali Rice Team (rice.collab@kuali.org)
041 */
042public class HideWebInfFilter implements Filter {
043
044        private static final Pattern WEB_INF_PATTERN = Pattern.compile(".*WEB-INF.*");
045        
046    /**
047     * @see javax.servlet.Filter#destroy()
048     */
049    public void destroy() {
050        // nothing
051    }
052
053    /**
054     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
055     */
056    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
057        if ((req instanceof HttpServletRequest)) { 
058
059            HttpServletRequest hsr = (HttpServletRequest) req;
060    
061            if (WEB_INF_PATTERN.matcher(hsr.getRequestURI()).matches()) {
062                HttpServletResponse hsresp = (HttpServletResponse) res;
063                hsresp.sendError(HttpServletResponse.SC_NOT_FOUND);
064                return;
065            }
066        }
067
068        fc.doFilter(req, res);
069    }
070
071    /**
072     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
073     */
074    public void init(FilterConfig arg0) throws ServletException {
075        // nada
076    }
077}