# Regex Denial of Service via Catastrophic Backtracking

Language: Python
Severity: High
CWE: CWE-1333

## Source
8

## Flow
8-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-Z0-9]+)*-)*([A-Z0-9]+)+$'
    if re.match(pattern, device_id):
        return jsonify({'status': 'valid', 'device': device_id})
    return jsonify({'status': 'invalid'}), 400
```

## Explanation

The regex pattern contains nested quantifiers `(([A-Z0-9]+)*-)*` and `([A-Z0-9]+)+` which cause catastrophic backtracking. When a malformed device_id like 'AAAAAAAAAAAAAAAAAAAAAA-' is provided, the regex engine explores exponentially many matching paths, causing CPU exhaustion and denial of service.

## Remediation

The fix replaces the vulnerable regex pattern that had nested quantifiers `(([A-Z0-9]+)*-)*([A-Z0-9]+)+` with a safe equivalent `^[A-Z0-9]+(-[A-Z0-9]+)*$` that matches the same valid input (alphanumeric segments separated by hyphens) without any nested or overlapping quantifiers. Additionally, an input length check is added as a defense-in-depth measure to prevent excessively long inputs from being processed.

## 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', '')
    if len(device_id) > 256:
        return jsonify({'status': 'invalid', 'error': 'device_id too long'}), 400
    pattern = r'^[A-Z0-9]+(-[A-Z0-9]+)*$'
    if re.match(pattern, device_id):
        return jsonify({'status': 'valid', 'device': device_id})
    return jsonify({'status': 'invalid'}), 400
```
