This rule is designed to prevent the execution of unsafe functions that could potentially expose your application to security risks. It specifically targets functions such as Code.eval_string, Code.eval_file, Code.eval_quoted, and System.shell, which are known to be potentially dangerous when used improperly. These functions can execute code or shell commands from user inputs, which might introduce vulnerabilities if the input is not properly sanitized.
The importance of this rule lies in its ability to mitigate the risk of code injection attacks. Code injection attacks occur when an attacker is able to insert malicious code into your application, often through unsanitized user inputs. This can lead to a variety of negative outcomes, including data breaches and unauthorized access to system resources.
To adhere to this rule, avoid using these potentially unsafe functions, especially with user inputs. Instead, consider using safer alternatives that do not execute code dynamically. For instance, if you need to perform a set of operations, you can define a map of allowed functions and their corresponding implementations. This way, you can control what operations are allowed and avoid executing arbitrary code.
Non-Compliant Code Examples
# unsafe function eval_file on user_inputfile_result=Code.eval_file(user_input)# nested evals will each have their own error msg, depending on where# your mouse is hovered.single_nested=Code.eval_string(Code.eval_file(a))# unsafe function eval_quoted ran on user_inputquoted_result=Code.eval_quoted(user_input,"1","2")# Concatenated results should also raise errors. Here, two errors are raised because of two different variablesconcat=Code.eval_string("1 + 2 + #{variable} + 4","1 + 2 + #{test}")# We also want to look for shell commands.shellcmd=System.shell(command)
Compliant Code Examples
# Instead of letting the user eval commands/files, you can specify allowed functions using # a predefined set of functions with their own error handling.defmoduleSafeREPLdo@allowed_functions%{"add"=>fn[a,b]->a+bend,"subtract"=>fn[a,b]->a-bend,"multiply"=>fn[a,b]->a*bend,"divide"=>fn[a,b]->ifb==0,do:"Cannot divide by zero",else:a/bend}end# You can also opt to hard-code in your own values, as long as variables are not passed in.Code.eval_string("1 + 2")
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- elixir-security # Rules to enforce Elixir security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines