Python User Controlled Dynamic Import
Description
Identifies unsafe dynamic imports in Python code where the module name being imported could be controlled by user input. When attackers can influence what modules are dynamically imported using importlib.import_module(), they may be able to load malicious code and achieve arbitrary code execution.
Detection Strategy
• Checks if the importlib library is imported in the code
• Locates calls to import_module function from importlib
• Examines the arguments passed to import_module to determine if they can be influenced by external input
• Reports a vulnerability when import_module is called with parameters that could be controlled by users
Vulnerable code example
from flask import Flask, request
import importlib
app = Flask(__name__)
@app.route("/import")
def dynamic_import():
# VULNERABLE: Unsanitized user input directly used in dynamic import...✅ Secure code example
from flask import Flask, request, jsonify
import importlib
app = Flask(__name__)
# Define whitelist of allowed modules
ALLOWED_MODULES = {"math", "json", "datetime"}
...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.