Skip to content

Commit

Permalink
Fix #8067 Use nanotime for DosFilter rate tracker
Browse files Browse the repository at this point in the history
Use nano time to avoid false positives when wall clock changes.
  • Loading branch information
gregw committed May 31, 2022
1 parent ee404b6 commit 437b45c
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ protected void doFilter(HttpServletRequest request, HttpServletResponse response
tracker = getRateTracker(request);

// Calculate the rate and check if it is over the allowed limit
final OverLimit overLimit = tracker.isRateExceeded(System.currentTimeMillis());
final OverLimit overLimit = tracker.isRateExceeded(System.nanoTime());

// Pass it through if we are not currently over the rate limit.
if (overLimit == null)
Expand Down Expand Up @@ -1235,7 +1235,7 @@ public OverLimit isRateExceeded(long now)
}

long rate = (now - last);
if (rate < 1000L)
if (TimeUnit.NANOSECONDS.toSeconds(rate) < 1L)
{
return new Overage(Duration.ofMillis(rate), _maxRequestsPerSecond);
}
Expand Down Expand Up @@ -1326,7 +1326,7 @@ public void run()

int latestIndex = _next == 0 ? (_timestamps.length - 1) : (_next - 1);
long last = _timestamps[latestIndex];
boolean hasRecentRequest = last != 0 && (System.currentTimeMillis() - last) < 1000L;
boolean hasRecentRequest = last != 0 && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - last) < 1L;

DoSFilter filter = (DoSFilter)_context.getAttribute(_filterName);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
Expand Down Expand Up @@ -179,7 +178,7 @@ private boolean hitRateTracker(DoSFilter doSFilter, int sleep) throws Interrupte
for (int i = 0; i < 5; i++)
{
Thread.sleep(sleep);
if (rateTracker.isRateExceeded(TimeUnit.NANOSECONDS.toMillis(System.nanoTime())) != null)
if (rateTracker.isRateExceeded(System.nanoTime()) != null)
exceeded = true;
}
return exceeded;
Expand Down

0 comments on commit 437b45c

Please sign in to comment.