/
DoSFilter.java
1554 lines (1395 loc) · 50 KB
/
DoSFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.servlets;
import java.io.IOException;
import java.io.Serializable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
/**
* Denial of Service filter
* <p>
* This filter is useful for limiting
* exposure to abuse from request flooding, whether malicious, or as a result of
* a misconfigured client.
* <p>
* The filter keeps track of the number of requests from a connection per
* second. If a limit is exceeded, the request is either rejected, delayed, or
* throttled.
* <p>
* When a request is throttled, it is placed in a priority queue. Priority is
* given first to authenticated users and users with an HttpSession, then
* connections which can be identified by their IP addresses. Connections with
* no way to identify them are given lowest priority.
* <p>
* The {@link #extractUserId(ServletRequest request)} function should be
* implemented, in order to uniquely identify authenticated users.
* <p>
* The following init parameters control the behavior of the filter:
* <dl>
* <dt>maxRequestsPerSec</dt>
* <dd>the maximum number of requests from a connection per
* second. Requests in excess of this are first delayed,
* then throttled.</dd>
* <dt>delayMs</dt>
* <dd>is the delay given to all requests over the rate limit,
* before they are considered at all. -1 means just reject request,
* 0 means no delay, otherwise it is the delay.</dd>
* <dt>maxWaitMs</dt>
* <dd>how long to blocking wait for the throttle semaphore.</dd>
* <dt>throttledRequests</dt>
* <dd>is the number of requests over the rate limit able to be
* considered at once.</dd>
* <dt>throttleMs</dt>
* <dd>how long to async wait for semaphore.</dd>
* <dt>maxRequestMs</dt>
* <dd>how long to allow this request to run.</dd>
* <dt>maxIdleTrackerMs</dt>
* <dd>how long to keep track of request rates for a connection,
* before deciding that the user has gone away, and discarding it</dd>
* <dt>insertHeaders</dt>
* <dd>if true , insert the DoSFilter headers into the response. Defaults to true.</dd>
* <dt>trackSessions</dt>
* <dd>if true, usage rate is tracked by session if a session exists. Defaults to true.</dd>
* <dt>remotePort</dt>
* <dd>if true and session tracking is not used, then rate is tracked by IP+port (effectively connection). Defaults to false.</dd>
* <dt>ipWhitelist</dt>
* <dd>a comma-separated list of IP addresses that will not be rate limited</dd>
* <dt>managedAttr</dt>
* <dd>if set to true, then this servlet is set as a {@link ServletContext} attribute with the
* filter name as the attribute name. This allows context external mechanism (eg JMX via {@link ContextHandler#MANAGED_ATTRIBUTES}) to
* manage the configuration of the filter.</dd>
* <dt>tooManyCode</dt>
* <dd>The status code to send if there are too many requests. By default is 429 (too many requests), but 503 (Unavailable) is
* another option</dd>
* </dl>
* <p>
* This filter should be configured for {@link DispatcherType#REQUEST} and {@link DispatcherType#ASYNC} and with
* {@code <async-supported>true</async-supported>}.
* </p>
*/
@ManagedObject("limits exposure to abuse from request flooding, whether malicious, or as a result of a misconfigured client")
public class DoSFilter implements Filter
{
private static final Logger LOG = Log.getLogger(DoSFilter.class);
private static final String IPv4_GROUP = "(\\d{1,3})";
private static final Pattern IPv4_PATTERN = Pattern.compile(IPv4_GROUP + "\\." + IPv4_GROUP + "\\." + IPv4_GROUP + "\\." + IPv4_GROUP);
private static final String IPv6_GROUP = "(\\p{XDigit}{1,4})";
private static final Pattern IPv6_PATTERN = Pattern.compile(IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP + ":" + IPv6_GROUP);
private static final Pattern CIDR_PATTERN = Pattern.compile("([^/]+)/(\\d+)");
private static final String __TRACKER = "DoSFilter.Tracker";
private static final String __THROTTLED = "DoSFilter.Throttled";
private static final int __DEFAULT_MAX_REQUESTS_PER_SEC = 25;
private static final int __DEFAULT_DELAY_MS = 100;
private static final int __DEFAULT_THROTTLE = 5;
private static final int __DEFAULT_MAX_WAIT_MS = 50;
private static final long __DEFAULT_THROTTLE_MS = 30000L;
private static final long __DEFAULT_MAX_REQUEST_MS_INIT_PARAM = 30000L;
private static final long __DEFAULT_MAX_IDLE_TRACKER_MS_INIT_PARAM = 30000L;
static final String MANAGED_ATTR_INIT_PARAM = "managedAttr";
static final String MAX_REQUESTS_PER_S_INIT_PARAM = "maxRequestsPerSec";
static final String DELAY_MS_INIT_PARAM = "delayMs";
static final String THROTTLED_REQUESTS_INIT_PARAM = "throttledRequests";
static final String MAX_WAIT_INIT_PARAM = "maxWaitMs";
static final String THROTTLE_MS_INIT_PARAM = "throttleMs";
static final String MAX_REQUEST_MS_INIT_PARAM = "maxRequestMs";
static final String MAX_IDLE_TRACKER_MS_INIT_PARAM = "maxIdleTrackerMs";
static final String INSERT_HEADERS_INIT_PARAM = "insertHeaders";
static final String TRACK_SESSIONS_INIT_PARAM = "trackSessions";
static final String REMOTE_PORT_INIT_PARAM = "remotePort";
static final String IP_WHITELIST_INIT_PARAM = "ipWhitelist";
static final String ENABLED_INIT_PARAM = "enabled";
static final String TOO_MANY_CODE = "tooManyCode";
public enum RateType
{
AUTH,
SESSION,
IP,
UNKNOWN
}
private final String _suspended = "DoSFilter@" + Integer.toHexString(hashCode()) + ".SUSPENDED";
private final String _resumed = "DoSFilter@" + Integer.toHexString(hashCode()) + ".RESUMED";
private final ConcurrentHashMap<String, RateTracker> _rateTrackers = new ConcurrentHashMap<>();
private final List<String> _whitelist = new CopyOnWriteArrayList<>();
private int _tooManyCode;
private volatile long _delayMs;
private volatile long _throttleMs;
private volatile long _maxWaitMs;
private volatile long _maxRequestMs;
private volatile long _maxIdleTrackerMs;
private volatile boolean _insertHeaders;
private volatile boolean _trackSessions;
private volatile boolean _remotePort;
private volatile boolean _enabled;
private volatile String _name;
private DoSFilter.Listener _listener = new Listener();
private Semaphore _passes;
private volatile int _throttledRequests;
private volatile int _maxRequestsPerSec;
private Map<RateType, Queue<AsyncContext>> _queues = new HashMap<>();
private Map<RateType, AsyncListener> _listeners = new HashMap<>();
private Scheduler _scheduler;
private ServletContext _context;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
for (RateType rateType : RateType.values())
{
_queues.put(rateType, new ConcurrentLinkedQueue<>());
_listeners.put(rateType, new DoSAsyncListener(rateType));
}
_rateTrackers.clear();
int maxRequests = __DEFAULT_MAX_REQUESTS_PER_SEC;
String parameter = filterConfig.getInitParameter(MAX_REQUESTS_PER_S_INIT_PARAM);
if (parameter != null)
maxRequests = Integer.parseInt(parameter);
setMaxRequestsPerSec(maxRequests);
long delay = __DEFAULT_DELAY_MS;
parameter = filterConfig.getInitParameter(DELAY_MS_INIT_PARAM);
if (parameter != null)
delay = Long.parseLong(parameter);
setDelayMs(delay);
int throttledRequests = __DEFAULT_THROTTLE;
parameter = filterConfig.getInitParameter(THROTTLED_REQUESTS_INIT_PARAM);
if (parameter != null)
throttledRequests = Integer.parseInt(parameter);
setThrottledRequests(throttledRequests);
long maxWait = __DEFAULT_MAX_WAIT_MS;
parameter = filterConfig.getInitParameter(MAX_WAIT_INIT_PARAM);
if (parameter != null)
maxWait = Long.parseLong(parameter);
setMaxWaitMs(maxWait);
long throttle = __DEFAULT_THROTTLE_MS;
parameter = filterConfig.getInitParameter(THROTTLE_MS_INIT_PARAM);
if (parameter != null)
throttle = Long.parseLong(parameter);
setThrottleMs(throttle);
long maxRequestMs = __DEFAULT_MAX_REQUEST_MS_INIT_PARAM;
parameter = filterConfig.getInitParameter(MAX_REQUEST_MS_INIT_PARAM);
if (parameter != null)
maxRequestMs = Long.parseLong(parameter);
setMaxRequestMs(maxRequestMs);
long maxIdleTrackerMs = __DEFAULT_MAX_IDLE_TRACKER_MS_INIT_PARAM;
parameter = filterConfig.getInitParameter(MAX_IDLE_TRACKER_MS_INIT_PARAM);
if (parameter != null)
maxIdleTrackerMs = Long.parseLong(parameter);
setMaxIdleTrackerMs(maxIdleTrackerMs);
String whiteList = "";
parameter = filterConfig.getInitParameter(IP_WHITELIST_INIT_PARAM);
if (parameter != null)
whiteList = parameter;
setWhitelist(whiteList);
parameter = filterConfig.getInitParameter(INSERT_HEADERS_INIT_PARAM);
setInsertHeaders(parameter == null || Boolean.parseBoolean(parameter));
parameter = filterConfig.getInitParameter(TRACK_SESSIONS_INIT_PARAM);
setTrackSessions(parameter == null || Boolean.parseBoolean(parameter));
parameter = filterConfig.getInitParameter(REMOTE_PORT_INIT_PARAM);
setRemotePort(parameter != null && Boolean.parseBoolean(parameter));
parameter = filterConfig.getInitParameter(ENABLED_INIT_PARAM);
setEnabled(parameter == null || Boolean.parseBoolean(parameter));
parameter = filterConfig.getInitParameter(TOO_MANY_CODE);
setTooManyCode(parameter == null ? 429 : Integer.parseInt(parameter));
setName(filterConfig.getFilterName());
_context = filterConfig.getServletContext();
if (_context != null)
{
_context.setAttribute(filterConfig.getFilterName(), this);
}
_scheduler = startScheduler();
}
protected Scheduler startScheduler() throws ServletException
{
try
{
Scheduler result = new ScheduledExecutorScheduler(String.format("DoS-Scheduler-%x", hashCode()), false);
result.start();
return result;
}
catch (Exception x)
{
throw new ServletException(x);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
doFilter((HttpServletRequest)request, (HttpServletResponse)response, filterChain);
}
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
if (!isEnabled())
{
filterChain.doFilter(request, response);
return;
}
// Look for the rate tracker for this request.
RateTracker tracker = (RateTracker)request.getAttribute(__TRACKER);
if (tracker != null)
{
// Redispatched, RateTracker present in request attributes.
throttleRequest(request, response, filterChain, tracker);
return;
}
// This is the first time we have seen this request.
if (LOG.isDebugEnabled())
LOG.debug("Filtering {}", request);
// Get a rate tracker associated with this request, and record one hit.
tracker = getRateTracker(request);
// Calculate the rate and check if it is over the allowed limit
final OverLimit overLimit = tracker.isRateExceeded(System.nanoTime());
// Pass it through if we are not currently over the rate limit.
if (overLimit == null)
{
if (LOG.isDebugEnabled())
LOG.debug("Allowing {}", request);
doFilterChain(filterChain, request, response);
return;
}
// We are over the limit.
// Ask listener what to perform.
Action action = _listener.onRequestOverLimit(request, overLimit, this);
// Perform action
long delayMs = getDelayMs();
boolean insertHeaders = isInsertHeaders();
switch (action)
{
case NO_ACTION:
if (LOG.isDebugEnabled())
LOG.debug("Allowing over-limit request {}", request);
doFilterChain(filterChain, request, response);
break;
case ABORT:
if (LOG.isDebugEnabled())
LOG.debug("Aborting over-limit request {}", request);
response.sendError(-1);
return;
case REJECT:
if (insertHeaders)
response.addHeader("DoSFilter", "unavailable");
response.sendError(getTooManyCode());
return;
case DELAY:
// Insert a delay before throttling the request,
// using the suspend+timeout mechanism of AsyncContext.
if (insertHeaders)
response.addHeader("DoSFilter", "delayed");
request.setAttribute(__TRACKER, tracker);
AsyncContext asyncContext = request.startAsync();
if (delayMs > 0)
asyncContext.setTimeout(delayMs);
asyncContext.addListener(new DoSTimeoutAsyncListener());
break;
case THROTTLE:
throttleRequest(request, response, filterChain, tracker);
break;
}
}
private void throttleRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, RateTracker tracker) throws IOException, ServletException
{
if (LOG.isDebugEnabled())
LOG.debug("Throttling {}", request);
// Throttle the request.
boolean accepted = false;
try
{
// Check if we can afford to accept another request at this time.
accepted = _passes.tryAcquire(getMaxWaitMs(), TimeUnit.MILLISECONDS);
if (!accepted)
{
// We were not accepted, so either we suspend to wait,
// or if we were woken up we insist or we fail.
Boolean throttled = (Boolean)request.getAttribute(__THROTTLED);
long throttleMs = getThrottleMs();
if (!Boolean.TRUE.equals(throttled) && throttleMs > 0)
{
RateType priority = getPriority(request, tracker);
request.setAttribute(__THROTTLED, Boolean.TRUE);
if (isInsertHeaders())
response.addHeader("DoSFilter", "throttled");
AsyncContext asyncContext = request.startAsync();
request.setAttribute(_suspended, Boolean.TRUE);
asyncContext.setTimeout(throttleMs);
asyncContext.addListener(_listeners.get(priority));
_queues.get(priority).add(asyncContext);
if (LOG.isDebugEnabled())
LOG.debug("Throttled {}, {}ms", request, throttleMs);
return;
}
Boolean resumed = (Boolean)request.getAttribute(_resumed);
if (Boolean.TRUE.equals(resumed))
{
// We were resumed, we wait for the next pass.
_passes.acquire();
accepted = true;
}
}
// If we were accepted (either immediately or after throttle)...
if (accepted)
{
// ...call the chain.
if (LOG.isDebugEnabled())
LOG.debug("Allowing {}", request);
doFilterChain(filterChain, request, response);
}
else
{
// ...otherwise fail the request.
if (LOG.isDebugEnabled())
LOG.debug("Rejecting {}", request);
if (isInsertHeaders())
response.addHeader("DoSFilter", "unavailable");
response.sendError(getTooManyCode());
}
}
catch (InterruptedException e)
{
LOG.ignore(e);
response.sendError(getTooManyCode());
}
finally
{
if (accepted)
{
try
{
// Wake up the next highest priority request.
for (RateType rateType : RateType.values())
{
AsyncContext asyncContext = _queues.get(rateType).poll();
if (asyncContext != null)
{
ServletRequest candidate = asyncContext.getRequest();
Boolean suspended = (Boolean)candidate.getAttribute(_suspended);
if (Boolean.TRUE.equals(suspended))
{
if (LOG.isDebugEnabled())
LOG.debug("Resuming {}", request);
candidate.setAttribute(_resumed, Boolean.TRUE);
asyncContext.dispatch();
break;
}
}
}
}
finally
{
_passes.release();
}
}
}
}
protected void doFilterChain(FilterChain chain, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
final Thread thread = Thread.currentThread();
Runnable requestTimeout = () -> closeConnection(request, response, thread);
Scheduler.Task task = _scheduler.schedule(requestTimeout, getMaxRequestMs(), TimeUnit.MILLISECONDS);
try
{
chain.doFilter(request, response);
}
finally
{
task.cancel();
}
}
/**
* Invoked when the request handling exceeds {@link #getMaxRequestMs()}.
* <p>
* By default, an HTTP 503 response is returned and the handling thread is interrupted.
*
* @param request the current request
* @param response the current response
* @param handlingThread the handling thread
*/
protected void onRequestTimeout(HttpServletRequest request, HttpServletResponse response, Thread handlingThread)
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("Timing out {}", request);
try
{
response.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
}
catch (IllegalStateException ise)
{
LOG.ignore(ise);
// abort instead
response.sendError(-1);
}
}
catch (Throwable x)
{
LOG.info(x);
}
handlingThread.interrupt();
}
/**
* @param request the current request
* @param response the current response
* @param thread the handling thread
* @deprecated use {@link #onRequestTimeout(HttpServletRequest, HttpServletResponse, Thread)} instead
*/
@Deprecated
protected void closeConnection(HttpServletRequest request, HttpServletResponse response, Thread thread)
{
onRequestTimeout(request, response, thread);
}
/**
* Get priority for this request, based on user type
*
* @param request the current request
* @param tracker the rate tracker for this request
* @return the priority for this request
*/
private RateType getPriority(HttpServletRequest request, RateTracker tracker)
{
if (extractUserId(request) != null)
return RateType.AUTH;
if (tracker != null)
return tracker.getType();
return RateType.UNKNOWN;
}
/**
* @return the maximum priority that we can assign to a request
*/
protected RateType getMaxPriority()
{
return RateType.AUTH;
}
public void setListener(DoSFilter.Listener listener)
{
_listener = Objects.requireNonNull(listener, "Listener may not be null");
}
public DoSFilter.Listener getListener()
{
return _listener;
}
private void schedule(RateTracker tracker)
{
_scheduler.schedule(tracker, getMaxIdleTrackerMs(), TimeUnit.MILLISECONDS);
}
/**
* Return a request rate tracker associated with this connection; keeps
* track of this connection's request rate. If this is not the first request
* from this connection, return the existing object with the stored stats.
* If it is the first request, then create a new request tracker.
* <p>
* Assumes that each connection has an identifying characteristic, and goes
* through them in order, taking the first that matches: user id (logged
* in), session id, client IP address. Unidentifiable connections are lumped
* into one.
* <p>
* When a session expires, its rate tracker is automatically deleted.
*
* @param request the current request
* @return the request rate tracker for the current connection
*/
RateTracker getRateTracker(ServletRequest request)
{
HttpSession session = ((HttpServletRequest)request).getSession(false);
String loadId = extractUserId(request);
final RateType type;
if (loadId != null)
{
type = RateType.AUTH;
}
else
{
if (isTrackSessions() && session != null && !session.isNew())
{
loadId = session.getId();
type = RateType.SESSION;
}
else
{
loadId = isRemotePort() ? createRemotePortId(request) : request.getRemoteAddr();
type = RateType.IP;
}
}
RateTracker tracker = _rateTrackers.get(loadId);
if (tracker == null)
{
boolean allowed = checkWhitelist(request.getRemoteAddr());
int maxRequestsPerSec = getMaxRequestsPerSec();
tracker = allowed ? new FixedRateTracker(_context, _name, loadId, type, maxRequestsPerSec)
: new RateTracker(_context, _name, loadId, type, maxRequestsPerSec);
tracker.setContext(_context);
RateTracker existing = _rateTrackers.putIfAbsent(loadId, tracker);
if (existing != null)
tracker = existing;
if (type == RateType.IP)
{
// USER_IP expiration from _rateTrackers is handled by the _scheduler
_scheduler.schedule(tracker, getMaxIdleTrackerMs(), TimeUnit.MILLISECONDS);
}
else if (session != null)
{
// USER_SESSION expiration from _rateTrackers are handled by the HttpSessionBindingListener
session.setAttribute(__TRACKER, tracker);
}
}
return tracker;
}
private void addToRateTracker(RateTracker tracker)
{
_rateTrackers.put(tracker.getId(), tracker);
}
public void removeFromRateTracker(String id)
{
_rateTrackers.remove(id);
}
protected boolean checkWhitelist(String candidate)
{
for (String address : _whitelist)
{
if (address.contains("/"))
{
if (subnetMatch(address, candidate))
return true;
}
else
{
if (address.equals(candidate))
return true;
}
}
return false;
}
@Deprecated
protected boolean checkWhitelist(List<String> whitelist, String candidate)
{
for (String address : whitelist)
{
if (address.contains("/"))
{
if (subnetMatch(address, candidate))
return true;
}
else
{
if (address.equals(candidate))
return true;
}
}
return false;
}
protected boolean subnetMatch(String subnetAddress, String address)
{
Matcher cidrMatcher = CIDR_PATTERN.matcher(subnetAddress);
if (!cidrMatcher.matches())
return false;
String subnet = cidrMatcher.group(1);
int prefix;
try
{
prefix = Integer.parseInt(cidrMatcher.group(2));
}
catch (NumberFormatException x)
{
LOG.info("Ignoring malformed CIDR address {}", subnetAddress);
return false;
}
byte[] subnetBytes = addressToBytes(subnet);
if (subnetBytes == null)
{
LOG.info("Ignoring malformed CIDR address {}", subnetAddress);
return false;
}
byte[] addressBytes = addressToBytes(address);
if (addressBytes == null)
{
LOG.info("Ignoring malformed remote address {}", address);
return false;
}
// Comparing IPv4 with IPv6 ?
int length = subnetBytes.length;
if (length != addressBytes.length)
return false;
byte[] mask = prefixToBytes(prefix, length);
for (int i = 0; i < length; ++i)
{
if ((subnetBytes[i] & mask[i]) != (addressBytes[i] & mask[i]))
return false;
}
return true;
}
private byte[] addressToBytes(String address)
{
Matcher ipv4Matcher = IPv4_PATTERN.matcher(address);
if (ipv4Matcher.matches())
{
byte[] result = new byte[4];
for (int i = 0; i < result.length; ++i)
{
result[i] = Integer.valueOf(ipv4Matcher.group(i + 1)).byteValue();
}
return result;
}
else
{
Matcher ipv6Matcher = IPv6_PATTERN.matcher(address);
if (ipv6Matcher.matches())
{
byte[] result = new byte[16];
for (int i = 0; i < result.length; i += 2)
{
int word = Integer.parseInt(ipv6Matcher.group(i / 2 + 1), 16);
result[i] = (byte)((word & 0xFF00) >>> 8);
result[i + 1] = (byte)(word & 0xFF);
}
return result;
}
}
return null;
}
private byte[] prefixToBytes(int prefix, int length)
{
byte[] result = new byte[length];
int index = 0;
while (prefix / 8 > 0)
{
result[index] = -1;
prefix -= 8;
++index;
}
if (index == result.length)
return result;
// Sets the _prefix_ most significant bits to 1
result[index] = (byte)~((1 << (8 - prefix)) - 1);
return result;
}
@Override
public void destroy()
{
LOG.debug("Destroy {}", this);
stopScheduler();
_rateTrackers.clear();
_whitelist.clear();
}
protected void stopScheduler()
{
try
{
_scheduler.stop();
}
catch (Exception x)
{
LOG.ignore(x);
}
}
/**
* Returns the user id, used to track this connection.
* This SHOULD be overridden by subclasses.
*
* @param request the current request
* @return a unique user id, if logged in; otherwise null.
*/
protected String extractUserId(ServletRequest request)
{
return null;
}
/**
* Get maximum number of requests from a connection per
* second. Requests in excess of this are first delayed,
* then throttled.
*
* @return maximum number of requests
*/
@ManagedAttribute("maximum number of requests allowed from a connection per second")
public int getMaxRequestsPerSec()
{
return _maxRequestsPerSec;
}
/**
* Get maximum number of requests from a connection per
* second. Requests in excess of this are first delayed,
* then throttled.
*
* @param value maximum number of requests
*/
public void setMaxRequestsPerSec(int value)
{
_maxRequestsPerSec = value;
}
/**
* Get delay (in milliseconds) that is applied to all requests
* over the rate limit, before they are considered at all.
*
* @return the delay in milliseconds
*/
@ManagedAttribute("delay applied to all requests over the rate limit (in ms)")
public long getDelayMs()
{
return _delayMs;
}
/**
* Set delay (in milliseconds) that is applied to all requests
* over the rate limit, before they are considered at all.
*
* @param value delay (in milliseconds), 0 - no delay, -1 - reject request
*/
public void setDelayMs(long value)
{
_delayMs = value;
}
/**
* Get maximum amount of time (in milliseconds) the filter will
* blocking wait for the throttle semaphore.
*
* @return maximum wait time
*/
@ManagedAttribute("maximum time the filter will block waiting throttled connections, (0 for no delay, -1 to reject requests)")
public long getMaxWaitMs()
{
return _maxWaitMs;
}
/**
* Set maximum amount of time (in milliseconds) the filter will
* blocking wait for the throttle semaphore.
*
* @param value maximum wait time
*/
public void setMaxWaitMs(long value)
{
_maxWaitMs = value;
}
/**
* Get number of requests over the rate limit able to be
* considered at once.
*
* @return number of requests
*/
@ManagedAttribute("number of requests over rate limit")
public int getThrottledRequests()
{
return _throttledRequests;
}
/**
* Set number of requests over the rate limit able to be
* considered at once.
*
* @param value number of requests
*/
public void setThrottledRequests(int value)
{
int permits = _passes == null ? 0 : _passes.availablePermits();
_passes = new Semaphore((value - _throttledRequests + permits), true);
_throttledRequests = value;
}
/**
* Get amount of time (in milliseconds) to async wait for semaphore.
*
* @return wait time
*/
@ManagedAttribute("amount of time to async wait for semaphore")
public long getThrottleMs()
{
return _throttleMs;
}
/**
* Set amount of time (in milliseconds) to async wait for semaphore.
*
* @param value wait time
*/
public void setThrottleMs(long value)
{
_throttleMs = value;
}
/**
* Get maximum amount of time (in milliseconds) to allow
* the request to process.
*
* @return maximum processing time
*/
@ManagedAttribute("maximum time to allow requests to process (in ms)")
public long getMaxRequestMs()
{
return _maxRequestMs;
}
/**
* Set maximum amount of time (in milliseconds) to allow
* the request to process.
*
* @param value maximum processing time
*/
public void setMaxRequestMs(long value)
{
_maxRequestMs = value;
}
/**
* Get maximum amount of time (in milliseconds) to keep track
* of request rates for a connection, before deciding that
* the user has gone away, and discarding it.
*
* @return maximum tracking time
*/
@ManagedAttribute("maximum time to track of request rates for connection before discarding")
public long getMaxIdleTrackerMs()
{
return _maxIdleTrackerMs;
}
/**
* Set maximum amount of time (in milliseconds) to keep track
* of request rates for a connection, before deciding that
* the user has gone away, and discarding it.
*
* @param value maximum tracking time
*/
public void setMaxIdleTrackerMs(long value)
{
_maxIdleTrackerMs = value;
}
/**
* The unique name of the filter when there is more than
* one DosFilter instance.
*
* @return the name
*/
public String getName()
{
return _name;
}
/**