{"title":"SQL Injection via f-string in sqlite3.execute()","language":"Python","severity":"Critical","cwe":"CWE-89","source_lines":[3],"flow_lines":[3,6,7],"sink_lines":[7],"vulnerable_code":"import sqlite3\n\ndef fetch_iot_device_logs(device_mac, start_ts):\n    conn = sqlite3.connect('/var/iot/telemetry.db')\n    cur = conn.cursor()\n    query = f\"SELECT timestamp, sensor_data, alert_level FROM device_logs WHERE mac_address = '{device_mac}' AND timestamp >= {start_ts} ORDER BY timestamp DESC\"\n    cur.execute(query)\n    logs = cur.fetchall()\n    conn.close()\n    return logs","explanation":"The function parameters device_mac and start_ts are directly embedded into an SQL query using an f-string without any sanitization or parameterization. This allows an attacker to inject arbitrary SQL commands through either the MAC address or timestamp parameters, potentially leading to data exfiltration, modification, or deletion.","remediation":"The fix replaces the vulnerable f-string interpolation with parameterized query placeholders (?). The user-supplied values device_mac and start_ts are passed as a tuple to cur.execute(), which ensures the database driver properly escapes and binds them, preventing SQL injection regardless of input content.","secure_code":"import sqlite3\n\ndef fetch_iot_device_logs(device_mac, start_ts):\n    conn = sqlite3.connect('/var/iot/telemetry.db')\n    cur = conn.cursor()\n    query = \"SELECT timestamp, sensor_data, alert_level FROM device_logs WHERE mac_address = ? AND timestamp >= ? ORDER BY timestamp DESC\"\n    cur.execute(query, (device_mac, start_ts))\n    logs = cur.fetchall()\n    conn.close()\n    return logs"}