It occurs when an application executes untrusted code from an attacker. User input gets concatenated with code. The input is executed without validation or sanitization.
1import javax.servlet.http.HttpServletRequest
2import scala.tools.nsc.interpreter.IMain
3
4class CodeInjectionNoncompliant {
5 def executeUserCode(request: HttpServletRequest): Any = {
6 val codeId = request.getParameter("codeId")
7 val interpreter = new IMain()
8
9 // Noncompliant: User input is executed as Scala code, allowing arbitrary code execution on the server.
10 interpreter.interpret(codeId)
11 }
12}
1import javax.servlet.http.HttpServletRequest
2import scala.tools.nsc.interpreter.IMain
3
4class CodeInjectionCompliant {
5 def executeUserCode(request: HttpServletRequest): Any = {
6 val codeId = request.getParameter("codeId")
7
8 if (codeId != null && codeId.matches("^[A-Z0-9]{1,10}$")) {
9 val allowedCodes = Set("CALC001", "PRINT001", "TIME001")
10
11 if (allowedCodes.contains(codeId)) {
12 val codeMap = Map(
13 "CALC001" -> "println(math.sqrt(16))",
14 "PRINT001" -> "println(\"Safe execution\")",
15 "TIME001" -> "println(java.time.LocalDateTime.now())"
16 )
17 val interpreter = new IMain()
18
19 // Compliant: User input is validated and mapped to predefined code, preventing arbitrary code execution.
20 interpreter.interpret(codeMap(codeId))
21 } else {
22 throw new SecurityException("Code ID not allowed")
23 }
24 } else {
25 throw new SecurityException("Invalid code ID format")
26 }
27 }
28}