I am getting below warning while running my python code through Semgrep(Static Code validater). Please suggest any practical example how to use a whitelist to prevent running untrusted code or any other solution to avoid this warning.I searched on net but could not found any example..
I am getting warning at below particuklar line with import_module
Warning: Untrusted user input in importlib.import_module() function allows an attacker to load arbitrary code.Avoid dynamic values in importlib.import_module() or use a whitelist to prevent running untrusted code.
channel_module = import_module("src.main.core_prj.prj_" + config['subscription'].lower())
The triggered rule can be found at https://semgrep.dev/r?q=Untrusted+user+input+in+importlib.import_module . Clicking on the rule will expand to show the definition, which shows it allows
importlib.import_module("..")
and triggers a warning if a variable is used.The rule mentions it is intending to prevent CWE-706: Use of Incorrectly-Resolved Name or Reference, which is quite broad.
This is not relevant in the sample code, which has a string prefix before the user defined config string, so there is no opportunity that
import_module("src.main.core_prj.prj_" + config['subscription'].lower())
will load a module (resource) that is outside of the intended control sphere (src.main.core_prj...
).To instruct semgrep to ignore the line, append an inline comment
nosem
, like the following for PythonTest the above in the semgrep rule playground at https://semgrep.dev/s/KXZL
After adding these inline comments disabling lines, or specific rules on lines, they can be shown again by using the
--strict
command-line argument.