View Javadoc
1   /*
2    * Copyright (c) 2002-2024, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.web.upload;
35  
36  import fr.paris.lutece.portal.service.util.AppLogService;
37  import fr.paris.lutece.portal.service.util.AppPropertiesService;
38  
39  import java.io.IOException;
40  
41  import java.util.HashMap;
42  import java.util.LinkedList;
43  import java.util.Map;
44  
45  import javax.servlet.Filter;
46  import javax.servlet.FilterChain;
47  import javax.servlet.FilterConfig;
48  import javax.servlet.ServletException;
49  import javax.servlet.ServletRequest;
50  import javax.servlet.ServletResponse;
51  
52  import org.apache.commons.collections4.CollectionUtils;
53  
54  /**
55   * A rewrite of the multipart filter from the com.oreilly.servlet package. The rewrite allows us to use initialization parameters specified in the Lutece
56   * configuration files.
57   */
58  public class DosGuardFilter implements Filter
59  {
60      // properties
61      private static String PROPERTY_DOSGUARDFILTER_MINCONTENTLENGTH = "lutece.upload.dosguard.minContentLength";
62      private static String PROPERTY_DOSGUARDFILTER_MININTERVAL    = "lutece.upload.dosguard.minInterval";
63  
64      // constants
65      private static int CONSTANT_DEFAULT_DOSGUARDFILTER_MINCONTENTLENGTH = 10240 ;
66      private static int CONSTANT_DEFAULT_DOSGUARDFILTER_MININTERVAL = 2000 ;
67  
68      // Initial capacity of the HashMap
69      private static final int INITIAL_CAPACITY = 100;
70      private FilterConfig _filterConfig;
71  
72      // The size under which requests are allowed systematically
73      private int _nMinContentLength;
74  
75      // The minimum interval allowed between two requests from the same client
76      private int _nMinInterval;
77  
78      // The HashMap used to store IP/time entries
79      private Map<String, Long> _mapLastRequestTimes;
80  
81      // The LinkedList used to store entries in their order of arrival (to speed
82      // up cleaning the HashMap)
83      private LinkedList<Entry> _listOrderedRequests;
84  
85      /**
86       * {@inheritDoc}
87       */
88      @Override
89      public void init( FilterConfig config ) throws ServletException
90      {
91          _filterConfig = config;
92          _mapLastRequestTimes = new HashMap<String, Long>( INITIAL_CAPACITY );
93          _listOrderedRequests = new LinkedList<Entry>( );
94  
95          _nMinContentLength = AppPropertiesService.getPropertyInt( PROPERTY_DOSGUARDFILTER_MINCONTENTLENGTH, CONSTANT_DEFAULT_DOSGUARDFILTER_MINCONTENTLENGTH ) ;
96          _nMinInterval = AppPropertiesService.getPropertyInt( PROPERTY_DOSGUARDFILTER_MININTERVAL, CONSTANT_DEFAULT_DOSGUARDFILTER_MININTERVAL ) ;
97  
98      }
99  
100     /**
101      * {@inheritDoc}
102      */
103     @Override
104     public void destroy( )
105     {
106         // Do nothing
107     }
108 
109     /**
110      * {@inheritDoc}
111      */
112     @Override
113     public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException
114     {
115         // DOS check
116         if ( this.isAllowed( request.getRemoteAddr( ), request.getContentLength( ) ) )
117         {
118             chain.doFilter( request, response );
119         }
120         else
121         {
122             throw new ServletException( "DOS Guard : Too many upload from the same IP !" );
123         }
124     }
125 
126     /**
127      * Checks if a client is allowed to make a request at the present time.
128      *
129      * @param strRemoteAddr
130      *            the IP address of the client
131      * @param iContentLength
132      *            the size of the request
133      * @return true if allowed, false otherwize
134      */
135     public synchronized boolean isAllowed( String strRemoteAddr, int iContentLength )
136     {
137         AppLogService.debug( "DosGuard : isAllowed({}, {})", strRemoteAddr, iContentLength );
138 
139         // Ignore requests if minInterval is negative (e.g. -1)
140         if ( _nMinInterval < 0 )
141         {
142             AppLogService.debug( "minInterval is below minimum, ignored" );
143 
144             return true;
145         }
146 
147         // Ignore the requests under the minimum size
148         if ( iContentLength < _nMinContentLength )
149         {
150             AppLogService.debug( "ContentLength is below minimum, ignored" );
151 
152             return true;
153         }
154 
155         // Record the time of this request
156         long lRequestTime = System.currentTimeMillis( );
157         AppLogService.debug( "Request time : {}", lRequestTime );
158 
159         // Test if IP was previously recorded
160         Long previousRequestTime = _mapLastRequestTimes.get( strRemoteAddr );
161         AppLogService.debug( "Previous request time : {}", previousRequestTime );
162 
163         if ( previousRequestTime != null )
164         {
165             AppLogService.debug( "IP is in the map" );
166 
167             // Test if IP is allowed to make a new request
168             if ( lRequestTime > ( previousRequestTime.longValue( ) + _nMinInterval ) )
169             {
170                 AppLogService.debug( "IP is allowed to make a new request" );
171 
172                 // Clean up
173                 this.cleanExpiredEntries( );
174 
175                 // Update the map with the new time
176                 _mapLastRequestTimes.put( strRemoteAddr, Long.valueOf( lRequestTime ) );
177 
178                 // Add a new entry in the list
179                 _listOrderedRequests.addFirst( new Entry( strRemoteAddr, lRequestTime ) );
180 
181                 return true;
182             }
183 
184             AppLogService.debug( "IP is not allowed to make a new request" );
185 
186             return false;
187         }
188 
189         AppLogService.debug( "IP is not in the map" );
190 
191         // Clean up
192         this.cleanExpiredEntries( );
193 
194         // Add the IP and the time to the map
195         _mapLastRequestTimes.put( strRemoteAddr, Long.valueOf( lRequestTime ) );
196 
197         // Add a new entry in the list
198         _listOrderedRequests.addFirst( new Entry( strRemoteAddr, lRequestTime ) );
199 
200         return true;
201     }
202 
203     /**
204      * Cleans the internal map from expired entries.
205      */
206     private void cleanExpiredEntries( )
207     {
208         AppLogService.debug( "DosGuard.class : cleanExpiredEntries()" );
209 
210         if ( CollectionUtils.isNotEmpty( _listOrderedRequests ) )
211         {
212             // Expired entries are those where the IP can't be blocked anymore
213             long lMinTime = System.currentTimeMillis( ) - _nMinInterval;
214 
215             AppLogService.debug( "Min time : {}", lMinTime );
216 
217             // Read entries from the list, remove them as long as they are expired
218             boolean bDone = false;
219 
220             while ( !bDone && CollectionUtils.isNotEmpty( _listOrderedRequests ) )
221             {
222                 // The list is ordered by arrival time, so the last one is the
223                 // oldest
224                 Entry lastEntry = _listOrderedRequests.getLast( );
225 
226                 if ( lastEntry.getRequestTime( ) < lMinTime )
227                 {
228                     // The entry is expired, remove it from the map and the list
229                     _mapLastRequestTimes.remove( lastEntry.getRemoteAddr( ) );
230                     _listOrderedRequests.removeLast( );
231 
232                     AppLogService.debug( "Removing [{}, {}]", lastEntry.getRemoteAddr( ), lastEntry.getRequestTime( ) );
233                 }
234                 else
235                 {
236                     bDone = true;
237                 }
238             }
239         }
240     }
241 
242     /**
243      * Utility class used to store entries in the list.
244      */
245     private static class Entry
246     {
247         private String _strRemoteAddr;
248         private long _lRequestTime;
249 
250         /**
251          * Constructor
252          * 
253          * @param strRemoteAddr
254          *            The remote address
255          * @param lRequestTime
256          *            The request time
257          */
258         public Entry( String strRemoteAddr, long lRequestTime )
259         {
260             this._strRemoteAddr = strRemoteAddr;
261             this._lRequestTime = lRequestTime;
262         }
263 
264         /**
265          * Gets the remote address
266          * 
267          * @return The remote address
268          */
269         public String getRemoteAddr( )
270         {
271             return _strRemoteAddr;
272         }
273 
274         /**
275          * Gets the request time
276          * 
277          * @return The request time
278          */
279         public long getRequestTime( )
280         {
281             return _lRequestTime;
282         }
283     }
284 }