{"title":"SQLite Injection via f-string in sqlite3 execute()","language":"Python","severity":"Critical","cwe":"CWE-89","source_lines":[3],"flow_lines":[3,5,6],"sink_lines":[6],"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 device_mac='{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 uses f-strings to directly interpolate user-controlled parameters (device_mac and metric_type) into an SQL query without any sanitization or parameterization. This allows an attacker to inject arbitrary SQL code through these parameters, potentially extracting unauthorized data, modifying the database, or executing administrative commands.","remediation":"The fix replaces the f-string interpolation with parameterized query placeholders (?). The user-controlled values (device_mac and metric_type) are passed as a tuple to cursor.execute(), which ensures they are properly escaped and treated as literal values rather than executable SQL code.","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 device_mac=? 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"}