Constructing operating system or shell commands with unsanitized user input can lead to inadvertently running malicious code.
1public void createProcessNoncompliant(HttpServletRequest request) {
2 String favoriteColor = request.getParameter("favoriteColor");
3 // Noncompliant: user-supplied parameter is passed to an OS command and could be malicious.
4 ProcessBuilder pb = new ProcessBuilder("/usr/local/bin/program", "--color", favoriteColor);
5 try {
6 pb.start();
7 } catch (IOException e) {
8 System.out.println(e);
9 }
10}
1public void createProcessCompliant(HttpServletRequest request) {
2 String favoriteColor = request.getParameter("favoriteColor");
3 // Compliant: user-supplied parameter is sanitized before passing it to an OS command.
4 if (!favoriteColor.matches("[a-z]+")) {
5 throw new IllegalArgumentException();
6 }
7 ProcessBuilder pb = new ProcessBuilder("/usr/local/bin/program", "--color", favoriteColor);
8 try {
9 pb.start();
10 } catch (IOException e) {
11 System.out.println(e);
12 }
13}