rspec/rules/S2076/java/rule.adoc

70 lines
1.6 KiB
Plaintext
Raw Normal View History

2020-06-30 12:48:07 +02:00
include::../description.adoc[]
== Noncompliant Code Example
----
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
public void runUnsafe(HttpServletRequest request) throws IOException {
String cmd = request.getParameter("command");
String arg = request.getParameter("arg");
2020-06-30 12:48:07 +02:00
Runtime.getRuntime().exec(cmd+" "+arg); // Noncompliant
2020-06-30 12:48:07 +02:00
}
----
== Compliant Solution
Implement an allow-list of authorized commands to execute:
* each time the command to execute is user-controlled:
2020-06-30 12:48:07 +02:00
----
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
public void runUnsafe(HttpServletRequest request) throws IOException {
String cmd = request.getParameter("command");
String arg = request.getParameter("arg");
if(cmd.equals("/usr/bin/ls") || cmd.equals("/usr/bin/cat"))
{
// only ls or cat command are authorized
String cmdarray[] = new String[] { cmd, arg };
Runtime.getRuntime().exec(cmdarray); // Compliant
}
}
----
2020-06-30 12:48:07 +02:00
* or globally with the creation of a SecurityManager overriding checkExec() method:
2020-06-30 12:48:07 +02:00
----
class MySecurityManager extends SecurityManager {
MySecurityManager() {
super();
}
public void checkExec(String cmd) {
if(!(cmd.equals("/usr/bin/ls") || cmd.equals("/usr/bin/cat"))) {
throw new SecurityException("Unauthorized command: "+cmd);
}
}
}
----
2020-06-30 12:48:07 +02:00
----
MySecurityManager sm = new MySecurityManager();
System.setSecurityManager(sm);
2020-06-30 12:48:07 +02:00
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]