{"title":"SQL Injection via f-string formatted sqlite3 query","language":"Python","severity":"Critical","cwe":"CWE-89","source_lines":[1],"flow_lines":[1,4,5],"sink_lines":[5],"vulnerable_code":"import sqlite3\n\ndef fetch_iot_device_telemetry(device_mac, metric_type):\n    conn = sqlite3.connect('iot_hub.db')\n    cursor = conn.cursor()\n    query = f\"SELECT timestamp, value, unit FROM telemetry WHERE device_id = '{device_mac}' AND metric = '{metric_type}' ORDER BY timestamp DESC LIMIT 50\"\n    cursor.execute(query)\n    results = cursor.fetchall()\n    conn.close()\n    return results","explanation":"The function accepts user-controlled parameters 'device_mac' and 'metric_type' which are directly interpolated into an SQL query using f-strings without sanitization or parameterization. This allows attackers to inject arbitrary SQL commands through either parameter, potentially exposing sensitive telemetry data, modifying database contents, or executing unauthorized operations.","remediation":"The fix replaces the f-string interpolation with parameterized query placeholders (?) and passes the user-supplied values as a tuple to cursor.execute(). This ensures the database driver properly escapes and binds the parameters, preventing any injected SQL from being interpreted as executable code.","secure_code":"import sqlite3\n\ndef fetch_iot_device_telemetry(device_mac, metric_type):\n    conn = sqlite3.connect('iot_hub.db')\n    cursor = conn.cursor()\n    query = \"SELECT timestamp, value, unit FROM telemetry WHERE device_id = ? AND metric = ? ORDER BY timestamp DESC LIMIT 50\"\n    cursor.execute(query, (device_mac, metric_type))\n    results = cursor.fetchall()\n    conn.close()\n    return results"}