
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
51 lines
1.5 KiB
Plaintext
51 lines
1.5 KiB
Plaintext
== How to fix it in Java SE
|
|
|
|
=== Code examples
|
|
|
|
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
|
|
threads.
|