logo

Database

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.

Weakness:

014 - Insecure functionality

Category: Functionality Abuse

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"}
...