# SQL Injection via sqlite3.execute() String Concatenation

Language: Python
Severity: Critical
CWE: CWE-89

## Source
9

## Flow
9-11

## Sink
11

## Vulnerable Code
```python
import sqlite3

def fetch_iot_device_telemetry(device_mac, metric_type):
    db_conn = sqlite3.connect('/var/iot/telemetry.db')
    cursor = db_conn.cursor()
    query = "SELECT timestamp, value, unit FROM sensor_data WHERE device_mac='" + device_mac + "' AND metric='" + metric_type + "' ORDER BY timestamp DESC LIMIT 50"
    cursor.execute(query)
    telemetry_records = cursor.fetchall()
    db_conn.close()
    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
```python
import sqlite3

def fetch_iot_device_telemetry(device_mac, metric_type):
    db_conn = sqlite3.connect('/var/iot/telemetry.db')
    cursor = db_conn.cursor()
    query = "SELECT timestamp, value, unit FROM sensor_data WHERE device_mac=? AND metric=? ORDER BY timestamp DESC LIMIT 50"
    cursor.execute(query, (device_mac, metric_type))
    telemetry_records = cursor.fetchall()
    db_conn.close()
    return telemetry_records
```
