{"title":"SQL Injection via sqlite3 f-string Query Construction","language":"Python","severity":"Critical","cwe":"CWE-89","source_lines":[9],"flow_lines":[9,11],"sink_lines":[11],"vulnerable_code":"import sqlite3\n\ndef fetch_iot_device_telemetry(device_mac, metric_type):\n    conn = sqlite3.connect('iot_telemetry.db')\n    cursor = conn.cursor()\n    query = f\"SELECT timestamp, value, unit FROM sensor_data WHERE mac_address = '{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 parameters device_mac and metric_type are directly embedded into an SQL query using f-string formatting without any sanitization or parameterization. This allows attackers to inject arbitrary SQL commands through these parameters, potentially extracting, modifying, or deleting database contents.","remediation":"The fix replaces the f-string query construction with parameterized queries using placeholder symbols (?). The user-supplied values device_mac and metric_type are passed as a tuple to cursor.execute(), allowing the database driver to safely handle escaping and prevent SQL injection.","secure_code":"import sqlite3\n\ndef fetch_iot_device_telemetry(device_mac, metric_type):\n    conn = sqlite3.connect('iot_telemetry.db')\n    cursor = conn.cursor()\n    query = \"SELECT timestamp, value, unit FROM sensor_data WHERE mac_address = ? 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"}