# SQL Injection via f-string in sqlite3.execute()

Language: Python
Severity: Critical
CWE: CWE-89

## Source
3

## Flow
3-6-7

## Sink
7

## Vulnerable Code
```python
import sqlite3

def fetch_iot_device_logs(device_mac, start_ts):
    conn = sqlite3.connect('/var/iot/telemetry.db')
    cur = conn.cursor()
    query = f"SELECT timestamp, sensor_data, alert_level FROM device_logs WHERE mac_address = '{device_mac}' AND timestamp >= {start_ts} ORDER BY timestamp DESC"
    cur.execute(query)
    logs = cur.fetchall()
    conn.close()
    return logs
```

## Explanation

The function parameters device_mac and start_ts are directly embedded into an SQL query using an f-string without any sanitization or parameterization. This allows an attacker to inject arbitrary SQL commands through either the MAC address or timestamp parameters, potentially leading to data exfiltration, modification, or deletion.

## Remediation

The fix replaces the vulnerable f-string interpolation with parameterized query placeholders (?). The user-supplied values device_mac and start_ts are passed as a tuple to cur.execute(), which ensures the database driver properly escapes and binds them, preventing SQL injection regardless of input content.

## Secure Code
```python
import sqlite3

def fetch_iot_device_logs(device_mac, start_ts):
    conn = sqlite3.connect('/var/iot/telemetry.db')
    cur = conn.cursor()
    query = "SELECT timestamp, sensor_data, alert_level FROM device_logs WHERE mac_address = ? AND timestamp >= ? ORDER BY timestamp DESC"
    cur.execute(query, (device_mac, start_ts))
    logs = cur.fetchall()
    conn.close()
    return logs
```
