{"title":"SQL Injection via String Concatenation in sqlite3 Query","language":"Python","severity":"Critical","cwe":"CWE-89","source_lines":[1],"flow_lines":[1,5],"sink_lines":[5],"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 = \"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    conn.close()\n    return telemetry_records","explanation":"The function accepts user-controlled input parameters (device_mac and metric_type) and directly concatenates them into an SQL query string without sanitization or parameterization. This allows attackers to inject malicious SQL code that will be executed by cursor.execute(), enabling 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 data 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    telemetry_records = cursor.fetchall()\n    conn.close()\n    return telemetry_records"}