# SQL Injection via String Concatenation in sqlite3 Query

Language: Python
Severity: Critical
CWE: CWE-89

## Source
1

## Flow
1-5

## Sink
5

## Vulnerable Code
```python
import sqlite3

def fetch_iot_device_telemetry(device_mac, metric_type):
    conn = sqlite3.connect('iot_telemetry.db')
    cursor = 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()
    conn.close()
    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
```python
import sqlite3

def fetch_iot_device_telemetry(device_mac, metric_type):
    conn = sqlite3.connect('iot_telemetry.db')
    cursor = 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()
    conn.close()
    return telemetry_records
```
