# SQL Injection via f-string Formatted WHERE Clause

Language: Python
Severity: Critical
CWE: CWE-89

## Source
11-12

## Flow
11-12-13-4-6-7

## Sink
7

## Vulnerable Code
```python
import sqlite3

def fetch_iot_device_telemetry(device_mac, metric_type):
    conn = sqlite3.connect('iot_hub.db')
    cursor = conn.cursor()
    query = f"SELECT timestamp, value, unit FROM sensor_data WHERE device_id = '{device_mac}' AND metric = '{metric_type}' ORDER BY timestamp DESC LIMIT 50"
    cursor.execute(query)
    telemetry = cursor.fetchall()
    conn.close()
    return telemetry

user_device = request.args.get('mac_address')
metric = request.args.get('sensor_type')
results = fetch_iot_device_telemetry(user_device, metric)
```

## Explanation

User-controlled input from request.args.get() is directly interpolated into an SQL query using f-strings without any sanitization or parameterization. An attacker can inject malicious SQL code through the mac_address or sensor_type parameters to manipulate the query logic, extract unauthorized data, or perform other database operations.

## Remediation

The fix replaces the f-string interpolation in the SQL query with parameterized query placeholders (?). The user-supplied values are passed as a tuple to cursor.execute(), which ensures the database driver properly escapes and binds the parameters, preventing any injected SQL from being interpreted as executable code.

## Secure Code
```python
import sqlite3

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

user_device = request.args.get('mac_address')
metric = request.args.get('sensor_type')
results = fetch_iot_device_telemetry(user_device, metric)
```
