{"title":"Regex Denial of Service via Catastrophic Backtracking","language":"Python","severity":"High","cwe":"CWE-1333","source_lines":[8],"flow_lines":[8,10],"sink_lines":[10],"vulnerable_code":"import re\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n@app.route('/api/iot/validate_device_id', methods=['POST'])\ndef validate_iot_device_identifier():\n    device_id = request.json.get('device_identifier', '')\n    pattern = r'^(([A-Z0-9]+)*-)*([A-Z0-9]+)+$'\n    if re.match(pattern, device_id):\n        return jsonify({'status': 'valid', 'device': device_id})\n    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":"import re\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n@app.route('/api/iot/validate_device_id', methods=['POST'])\ndef validate_iot_device_identifier():\n    device_id = request.json.get('device_identifier', '')\n    if len(device_id) > 256:\n        return jsonify({'status': 'invalid', 'error': 'device_id too long'}), 400\n    pattern = r'^[A-Z0-9]+(-[A-Z0-9]+)*$'\n    if re.match(pattern, device_id):\n        return jsonify({'status': 'valid', 'device': device_id})\n    return jsonify({'status': 'invalid'}), 400"}