2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in Java SE
|
|
|
|
|
|
|
|
=== Code examples
|
2023-01-31 10:26:37 +01:00
|
|
|
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
|
|
----
|
|
|
|
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
|
|
|
Long time = Long.parseLong(req.getParameter("time"));
|
|
|
|
try {
|
|
|
|
Thread.sleep(time); // Noncompliant
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
resp.sendError(500);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
|
|
----
|
|
|
|
protected void compliant(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
|
|
|
Long time = Long.parseLong(req.getParameter("time"));
|
|
|
|
try {
|
|
|
|
Thread.sleep(Math.min(time, 1000));
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
resp.sendError(500);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
=== How does this work?
|
|
|
|
|
|
|
|
In most cases, it is discouraged to define a thread suspension time from
|
|
|
|
user-input.
|
|
|
|
|
|
|
|
If really necessary, the application should ensure that the provided suspension
|
|
|
|
time is below a safe limit. Such a limit should be evaluated and set to the lowest
|
|
|
|
possible time that ensures the application's operation and restricts denial of service
|
|
|
|
attacks.
|
|
|
|
|
|
|
|
The example compliant code uses the `Math.min` function to ensure the suspension
|
|
|
|
duration is below the limit of one second.
|
|
|
|
|
|
|
|
Note that even when the suspension time is limited, an attacker who submits
|
|
|
|
numerous requests at high speed can still manage always to consume all available
|
2023-05-25 14:18:12 +02:00
|
|
|
threads.
|