# Regex Denial of Service via Catastrophic Backtracking in `re.search`

Language: Python
Severity: High
CWE: CWE-1333

## Source
8

## Flow
8-9-10

## Sink
10

## Vulnerable Code
```python
import re
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/iot/validate_device_id', methods=['POST'])
def validate_iot_device_identifier():
    device_id = request.json.get('device_identifier', '')
    pattern = r'^(([a-zA-Z0-9]+)+)+@iot\.device$'
    if re.search(pattern, device_id):
        return jsonify({'status': 'valid', 'device': device_id})
    return jsonify({'status': 'invalid'}), 400
```

## Explanation

The regex pattern `r'^(([a-zA-Z0-9]+)+)+@iot\.device$'` contains nested quantifiers that cause catastrophic backtracking. When an attacker sends a malformed device_id with many repeating characters followed by a non-matching suffix, the regex engine explores exponentially many backtracking paths, causing CPU exhaustion and denial of service.

## Remediation

The fix replaces the vulnerable regex pattern `r'^(([a-zA-Z0-9]+)+)+@iot\.device$'` with `r'^[a-zA-Z0-9]+@iot\.device$'`, which removes the nested quantifiers that caused catastrophic backtracking. The simplified pattern still correctly validates that the device ID consists of one or more alphanumeric characters followed by the literal `@iot.device` suffix, but executes in linear time.

## Secure Code
```python
import re
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/iot/validate_device_id', methods=['POST'])
def validate_iot_device_identifier():
    device_id = request.json.get('device_identifier', '')
    pattern = r'^[a-zA-Z0-9]+@iot\.device$'
    if re.search(pattern, device_id):
        return jsonify({'status': 'valid', 'device': device_id})
    return jsonify({'status': 'invalid'}), 400
```
