mitm.djigzo.web.utils.IPFilter.java Source code

Java tutorial

Introduction

Here is the source code for mitm.djigzo.web.utils.IPFilter.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Common Development and 
 * Distribution License (CDDL), Common Public License (CPL) the 
 * licensors of this Program grant you additional permission to 
 * convey the resulting work.
 */

package mitm.djigzo.web.utils;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mitm.common.util.InetNetworkFilter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A HTTP Servlet filter that can filter out IP addresses. The filter specification is read from the system property 'djigzo.ipfilter.network'.
 * If this system property does not exist the filter parameter (from web.xml) 'network' is read.
 * 
 * Example filters:
 * 
 * - 192.168.*
 * - 192.168.*, 127.*, 222.0.0.0/8
 * 
 * @author martijn
 *
 */
public class IPFilter implements Filter {
    private static final String IP_FILTER_NETWORK_PARAMETER = "djigzo.ipfilter.network";

    private final static Logger logger = LoggerFactory.getLogger(IPFilter.class);

    /*
     * Used for checking access based on IP address
     */
    private InetNetworkFilter filter;

    /*
     * Reg expr pattern used to check which servlet paths to exclude from the IP filter
     */
    private Pattern excludePattern;

    public IPFilter() {
    }

    private void initInetNetwork(FilterConfig filterConfig) throws UnknownHostException {
        /*
         * The IP filter network will be loaded from the system properties (if available)
         */
        String networkSpec = System.getProperty(IP_FILTER_NETWORK_PARAMETER);

        /*
         * If not set try to load it from the web.xml filter settings
         */
        if (StringUtils.isBlank(networkSpec)) {
            networkSpec = filterConfig.getInitParameter("network");
        }

        if (StringUtils.isBlank(networkSpec)) {
            networkSpec = "*";
        }

        filter = new InetNetworkFilter(networkSpec);

        logger.info("IPFilter initialized with network " + networkSpec);
    }

    private void initExcludePattern(FilterConfig filterConfig) {
        String regExp = filterConfig.getInitParameter("exclude-servlet-path");

        if (StringUtils.isNotBlank(regExp)) {
            excludePattern = Pattern.compile(regExp);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            initInetNetwork(filterConfig);
            initExcludePattern(filterConfig);
        } catch (UnknownHostException e) {
            throw new ServletException(e);
        }
    }

    private boolean isServletPathExcluded(String servletPath) {
        if (excludePattern == null) {
            return false;
        }

        return excludePattern.matcher(servletPath).matches();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("HttpServletResponse expected.");
        }

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String servletPath = null;

        if (request instanceof HttpServletRequest) {
            servletPath = ((HttpServletRequest) request).getServletPath();
        }

        String remoteAddress = request.getRemoteAddr();

        if (filter.isAccepted(remoteAddress) || isServletPathExcluded(servletPath)) {
            chain.doFilter(request, response);
        } else {
            logger.warn("Request from " + remoteAddress + " to " + request.toString() + " is blocked.");

            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Access denied (" + remoteAddress + " is not allowed to connect)");
        }
    }

    @Override
    public void destroy() {
    }
}