1 22 package org.jboss.web.tomcat.filters; 23 24 import java.io.IOException ; 25 import javax.servlet.Filter ; 26 import javax.servlet.FilterChain ; 27 import javax.servlet.FilterConfig ; 28 import javax.servlet.ServletException ; 29 import javax.servlet.ServletRequest ; 30 import javax.servlet.ServletResponse ; 31 import javax.servlet.http.HttpServletRequest ; 32 import javax.servlet.http.HttpServletResponse ; 33 34 import org.jboss.logging.Logger; 35 36 70 public class RemoteHostFilter implements Filter 71 { 72 private static final Logger log = Logger.getLogger(RemoteHostFilter.class); 73 74 private String [] allow; 75 76 private String [] deny; 77 78 private boolean trace; 79 80 private FilterConfig filterConfig = null; 81 82 public RemoteHostFilter() 83 { 84 trace = log.isTraceEnabled(); 85 } 86 87 94 public void doFilter(ServletRequest request, 95 ServletResponse response, 96 FilterChain chain) 97 throws IOException , ServletException 98 { 99 String clientAddr = request.getRemoteAddr(); 100 if( trace ) 101 log.trace("Client addres is: " + clientAddr); 102 103 if (hasMatch(clientAddr, deny)) 104 { 105 handleInvalidAccess(request, response, clientAddr); 106 return; 107 } 108 109 if ((allow.length > 0) && !hasMatch(clientAddr, allow)) 110 { 111 handleInvalidAccess(request, response, clientAddr); 112 return; 113 } 114 115 chain.doFilter(request, response); 116 } 117 118 private void handleInvalidAccess(ServletRequest request, 119 ServletResponse response, 120 String clientAddr) throws IOException 121 { 122 HttpServletRequest httpRequest = (HttpServletRequest ) request; 123 HttpServletResponse httpResponse = (HttpServletResponse ) response; 124 String url = httpRequest.getRequestURL().toString(); 125 if( trace ) 126 log.trace("Invalid access attempt to " + url + " from " + clientAddr); 127 httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); 128 } 129 130 private boolean hasMatch(String clientAddr, String [] regExps) 131 { 132 for (int i = 0; i < regExps.length; i++) 133 { 134 if (clientAddr.matches(regExps[i])) 135 return true; 136 } 137 138 return false; 139 } 140 141 144 public void destroy() 145 { 146 this.filterConfig = null; 147 this.allow = null; 148 this.deny = null; 149 } 150 151 152 155 public void init(FilterConfig filterConfig) 156 { 157 this.filterConfig = filterConfig; 158 this.allow = extractRegExps(filterConfig.getInitParameter("allow")); 159 this.deny = extractRegExps(filterConfig.getInitParameter("deny")); 160 } 161 162 private String [] extractRegExps(String initParam) 163 { 164 if (initParam == null) 165 { 166 return new String [0]; 167 } 168 else 169 { 170 return initParam.split(","); 171 } 172 } 173 174 177 public String toString() 178 { 179 if (filterConfig == null) return ("ClientAddrFilter()"); 180 StringBuffer sb = new StringBuffer ("ClientAddrFilter("); 181 sb.append(filterConfig); 182 sb.append(")"); 183 return sb.toString(); 184 } 185 186 } 187 | Popular Tags |