View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.server.handler;
20  
21  import java.io.IOException;
22  import java.net.InetSocketAddress;
23  import java.util.Map;
24  
25  import javax.servlet.ServletException;
26  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;
28  
29  import org.eclipse.jetty.http.HttpStatus;
30  import org.eclipse.jetty.http.PathMap;
31  import org.eclipse.jetty.io.EndPoint;
32  import org.eclipse.jetty.server.HttpChannel;
33  import org.eclipse.jetty.server.Request;
34  import org.eclipse.jetty.util.IPAddressMap;
35  import org.eclipse.jetty.util.log.Log;
36  import org.eclipse.jetty.util.log.Logger;
37  
38  
39  /**
40   * IP Access Handler
41   * <p>
42   * Controls access to the wrapped handler by the real remote IP. Control is provided
43   * by white/black lists that include both internet addresses and URIs. This handler
44   * uses the real internet address of the connection, not one reported in the forwarded
45   * for headers, as this cannot be as easily forged.
46   * <p>
47   * Typically, the black/white lists will be used in one of three modes:
48   * <ul>
49   * <li>Blocking a few specific IPs/URLs by specifying several black list entries.
50   * <li>Allowing only some specific IPs/URLs by specifying several white lists entries.
51   * <li>Allowing a general range of IPs/URLs by specifying several general white list
52   * entries, that are then further refined by several specific black list exceptions
53   * </ul>
54   * <p>
55   * By default an empty white list is treated as match all. If there is at least one entry in
56   * the white list, then a request must match a white list entry. Black list entries
57   * are always applied, so that even if an entry matches the white list, a black list
58   * entry will override it.
59   * <p>
60   * You can change white list policy setting whiteListByPath to true. In this mode a request will be white listed
61   * IF it has a matching URL in the white list, otherwise the black list applies, e.g. in default mode when
62   * whiteListByPath = false and wl = "127.0.0.1|/foo", /bar request from 127.0.0.1 will be blacklisted,
63   * if whiteListByPath=true then not.
64   * <p>
65   * Internet addresses may be specified as absolute address or as a combination of
66   * four octet wildcard specifications (a.b.c.d) that are defined as follows.
67   * </p>
68   * <pre>
69   * nnn - an absolute value (0-255)
70   * mmm-nnn - an inclusive range of absolute values,
71   *           with following shorthand notations:
72   *           nnn- =&gt; nnn-255
73   *           -nnn =&gt; 0-nnn
74   *           -    =&gt; 0-255
75   * a,b,... - a list of wildcard specifications
76   * </pre>
77   * <p>
78   * Internet address specification is separated from the URI pattern using the "|" (pipe)
79   * character. URI patterns follow the servlet specification for simple * prefix and
80   * suffix wild cards (e.g. /, /foo, /foo/bar, /foo/bar/*, *.baz).
81   * <p>
82   * Earlier versions of the handler used internet address prefix wildcard specification
83   * to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
84   * They also used the first "/" character of the URI pattern to separate it from the
85   * internet address. Both of these features have been deprecated in the current version.
86   * <p>
87   * Examples of the entry specifications are:
88   * <ul>
89   * <li>10.10.1.2 - all requests from IP 10.10.1.2
90   * <li>10.10.1.2|/foo/bar - all requests from IP 10.10.1.2 to URI /foo/bar
91   * <li>10.10.1.2|/foo/* - all requests from IP 10.10.1.2 to URIs starting with /foo/
92   * <li>10.10.1.2|*.html - all requests from IP 10.10.1.2 to URIs ending with .html
93   * <li>10.10.0-255.0-255 - all requests from IPs within 10.10.0.0/16 subnet
94   * <li>10.10.0-.-255|/foo/bar - all requests from IPs within 10.10.0.0/16 subnet to URI /foo/bar
95   * <li>10.10.0-3,1,3,7,15|/foo/* - all requests from IPs addresses with last octet equal
96   *                                  to 1,3,7,15 in subnet 10.10.0.0/22 to URIs starting with /foo/
97   * </ul>
98   * <p>
99   * Earlier versions of the handler used internet address prefix wildcard specification
100  * to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
101  * They also used the first "/" character of the URI pattern to separate it from the
102  * internet address. Both of these features have been deprecated in the current version.
103  */
104 public class IPAccessHandler extends HandlerWrapper
105 {
106     private static final Logger LOG = Log.getLogger(IPAccessHandler.class);
107     // true means nodefault match
108     PathMap<IPAddressMap<Boolean>> _white = new PathMap<IPAddressMap<Boolean>>(true);
109     PathMap<IPAddressMap<Boolean>> _black = new PathMap<IPAddressMap<Boolean>>(true);
110     boolean _whiteListByPath = false;
111 
112     /* ------------------------------------------------------------ */
113     /**
114      * Creates new handler object
115      */
116     public IPAccessHandler()
117     {
118         super();
119     }
120 
121     /* ------------------------------------------------------------ */
122     /**
123      * Creates new handler object and initializes white- and black-list
124      *
125      * @param white array of whitelist entries
126      * @param black array of blacklist entries
127      */
128     public IPAccessHandler(String[] white, String []black)
129     {
130         super();
131 
132         if (white != null && white.length > 0)
133             setWhite(white);
134         if (black != null && black.length > 0)
135             setBlack(black);
136     }
137 
138     /* ------------------------------------------------------------ */
139     /**
140      * Add a whitelist entry to an existing handler configuration
141      *
142      * @param entry new whitelist entry
143      */
144     public void addWhite(String entry)
145     {
146         add(entry, _white);
147     }
148 
149     /* ------------------------------------------------------------ */
150     /**
151      * Add a blacklist entry to an existing handler configuration
152      *
153      * @param entry new blacklist entry
154      */
155     public void addBlack(String entry)
156     {
157         add(entry, _black);
158     }
159 
160     /* ------------------------------------------------------------ */
161     /**
162      * Re-initialize the whitelist of existing handler object
163      *
164      * @param entries array of whitelist entries
165      */
166     public void setWhite(String[] entries)
167     {
168         set(entries, _white);
169     }
170 
171     /* ------------------------------------------------------------ */
172     /**
173      * Re-initialize the blacklist of existing handler object
174      *
175      * @param entries array of blacklist entries
176      */
177     public void setBlack(String[] entries)
178     {
179         set(entries, _black);
180     }
181 
182     /* ------------------------------------------------------------ */
183     /**
184      * Re-initialize the mode of path matching
185      *
186      * @param whiteListByPath matching mode
187      */
188     public void setWhiteListByPath(boolean whiteListByPath)
189     {
190         this._whiteListByPath = whiteListByPath;
191     }
192 
193     /* ------------------------------------------------------------ */
194     /**
195      * Checks the incoming request against the whitelist and blacklist
196      *
197      * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
198      */
199     @Override
200     public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
201     {
202         // Get the real remote IP (not the one set by the forwarded headers (which may be forged))
203         HttpChannel channel = baseRequest.getHttpChannel();
204         if (channel!=null)
205         {
206             EndPoint endp=channel.getEndPoint();
207             if (endp!=null)
208             {
209                 InetSocketAddress address = endp.getRemoteAddress();
210                 if (address!=null && !isAddrUriAllowed(address.getHostString(),baseRequest.getPathInfo()))
211                 {
212                     response.sendError(HttpStatus.FORBIDDEN_403);
213                     baseRequest.setHandled(true);
214                     return;
215                 }
216             }
217         }
218 
219         getHandler().handle(target,baseRequest, request, response);
220     }
221 
222 
223     /* ------------------------------------------------------------ */
224     /**
225      * Helper method to parse the new entry and add it to
226      * the specified address pattern map.
227      *
228      * @param entry new entry
229      * @param patternMap target address pattern map
230      */
231     protected void add(String entry, PathMap<IPAddressMap<Boolean>> patternMap)
232     {
233         if (entry != null && entry.length() > 0)
234         {
235             boolean deprecated = false;
236             int idx;
237             if (entry.indexOf('|') > 0 )
238             {
239                 idx = entry.indexOf('|');
240             }
241             else
242             {
243                 idx = entry.indexOf('/');
244                 deprecated = (idx >= 0);
245             }
246 
247             String addr = idx > 0 ? entry.substring(0,idx) : entry;
248             String path = idx > 0 ? entry.substring(idx) : "/*";
249 
250             if (addr.endsWith("."))
251                 deprecated = true;
252             if (path!=null && (path.startsWith("|") || path.startsWith("/*.")))
253                 path=path.substring(1);
254 
255             IPAddressMap<Boolean> addrMap = patternMap.get(path);
256             if (addrMap == null)
257             {
258                 addrMap = new IPAddressMap<Boolean>();
259                 patternMap.put(path,addrMap);
260             }
261             if (addr != null && !"".equals(addr))
262                 // MUST NOT BE null
263                 addrMap.put(addr, true);
264 
265             if (deprecated)
266                 LOG.debug(toString() +" - deprecated specification syntax: "+entry);
267         }
268     }
269 
270     /* ------------------------------------------------------------ */
271     /**
272      * Helper method to process a list of new entries and replace
273      * the content of the specified address pattern map
274      *
275      * @param entries new entries
276      * @param patternMap target address pattern map
277      */
278     protected void set(String[] entries,  PathMap<IPAddressMap<Boolean>> patternMap)
279     {
280         patternMap.clear();
281 
282         if (entries != null && entries.length > 0)
283         {
284             for (String addrPath:entries)
285             {
286                 add(addrPath, patternMap);
287             }
288         }
289     }
290 
291     /* ------------------------------------------------------------ */
292     /**
293      * Check if specified request is allowed by current IPAccess rules.
294      *
295      * @param addr internet address
296      * @param path context path
297      * @return true if request is allowed
298      *
299      */
300     protected boolean isAddrUriAllowed(String addr, String path)
301     {
302         if (_white.size()>0)
303         {
304             boolean match = false;
305             boolean matchedByPath = false;
306 
307             for (Map.Entry<String,IPAddressMap<Boolean>> entry : _white.getMatches(path))
308             {
309                 matchedByPath=true;
310                 IPAddressMap<Boolean> addrMap = entry.getValue();
311                 if ((addrMap!=null && (addrMap.size()==0 || addrMap.match(addr)!=null)))
312                 {
313                     match=true;
314                     break;
315                 }
316             }
317             
318             if (_whiteListByPath)
319             {
320                 if (matchedByPath && !match)
321                     return false;
322             }
323             else
324             {
325                 if (!match)
326                     return false;
327             }
328         }
329 
330         if (_black.size() > 0)
331         {
332             for (Map.Entry<String,IPAddressMap<Boolean>> entry : _black.getMatches(path))
333             {
334                 IPAddressMap<Boolean> addrMap = entry.getValue();
335                 if (addrMap!=null && (addrMap.size()==0 || addrMap.match(addr)!=null))
336                     return false;
337             }
338             
339         }
340 
341         return true;
342     }
343 
344     /* ------------------------------------------------------------ */
345     /**
346      * Dump the handler configuration
347      */
348     @Override
349     public String dump()
350     {
351         StringBuilder buf = new StringBuilder();
352 
353         buf.append(toString());
354         buf.append(" WHITELIST:\n");
355         dump(buf, _white);
356         buf.append(toString());
357         buf.append(" BLACKLIST:\n");
358         dump(buf, _black);
359 
360         return buf.toString();
361     }
362 
363     /* ------------------------------------------------------------ */
364     /**
365      * Dump a pattern map into a StringBuilder buffer
366      *
367      * @param buf buffer
368      * @param patternMap pattern map to dump
369      */
370     protected void dump(StringBuilder buf, PathMap<IPAddressMap<Boolean>> patternMap)
371     {
372         for (String path: patternMap.keySet())
373         {
374             for (String addr: patternMap.get(path).keySet())
375             {
376                 buf.append("# ");
377                 buf.append(addr);
378                 buf.append("|");
379                 buf.append(path);
380                 buf.append("\n");
381             }
382         }
383     }
384  }