{"title":"SQL Injection via sqlite3.execute() String Concatenation","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    db_conn = sqlite3.connect('/var/iot/telemetry.db')\n    cursor = db_conn.cursor()\n    query = \"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    telemetry_records = cursor.fetchall()\n    db_conn.close()\n    return telemetry_records","explanation":"The function accepts untrusted input parameters device_mac and metric_type which are directly concatenated into an SQL query string without sanitization or parameterization. This allows attackers to inject malicious SQL code that will be executed by cursor.execute(), leading to unauthorized data access, modification, or deletion.","remediation":"The fix replaces string concatenation with parameterized queries using placeholder syntax (?). The user-supplied 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    db_conn = sqlite3.connect('/var/iot/telemetry.db')\n    cursor = db_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    telemetry_records = cursor.fetchall()\n    db_conn.close()\n    return telemetry_records"}