# SQL Injection via sqlite3 f-string Query Construction

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):
    conn = sqlite3.connect('iot_telemetry.db')
    cursor = conn.cursor()
    query = f"SELECT timestamp, value, unit FROM sensor_data WHERE mac_address = '{device_mac}' AND metric = '{metric_type}' ORDER BY timestamp DESC LIMIT 50"
    cursor.execute(query)
    results = cursor.fetchall()
    conn.close()
    return results
```

## Explanation

The function parameters device_mac and metric_type are directly embedded into an SQL query using f-string formatting without any sanitization or parameterization. This allows attackers to inject arbitrary SQL commands through these parameters, potentially extracting, modifying, or deleting database contents.

## Remediation

The fix replaces the f-string query construction with parameterized queries using placeholder symbols (?). The user-supplied values device_mac and metric_type are passed as a tuple to cursor.execute(), allowing the database driver to safely handle escaping and prevent SQL injection.

## 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 mac_address = ? AND metric = ? ORDER BY timestamp DESC LIMIT 50"
    cursor.execute(query, (device_mac, metric_type))
    results = cursor.fetchall()
    conn.close()
    return results
```
