{"title":"Disabled JWT Signature Verification","language":"Python","severity":"Critical","cwe":"CWE-347","source_lines":[6],"flow_lines":[6,7],"sink_lines":[7],"vulnerable_code":"import jwt\nimport json\nfrom flask import request, jsonify\n\ndef verify_iot_device_token(auth_header):\n    try:\n        token = auth_header.split(' ')[1]\n        device_payload = jwt.decode(token, options={\"verify_signature\": False})\n        if device_payload.get('device_id') and device_payload.get('role') == 'admin':\n            return jsonify({\"status\": \"authorized\", \"device_id\": device_payload['device_id'], \"access_level\": \"full\"})\n        return jsonify({\"status\": \"authorized\", \"device_id\": device_payload['device_id'], \"access_level\": \"limited\"})\n    except Exception as e:\n        return jsonify({\"error\": \"invalid_token\"}), 401","explanation":"The code disables JWT signature verification entirely using `options={\"verify_signature\": False}`, allowing attackers to forge arbitrary tokens with any claims. This enables complete authentication bypass and privilege escalation to admin access without knowing the secret key.","remediation":"The fix enforces cryptographic signature verification by providing a secret key and explicitly restricting the allowed algorithms to HS256, preventing algorithm confusion attacks including `alg=none`. Additionally, required claims (`device_id`, `role`, `exp`) are enforced and specific exception handling provides better error diagnostics while rejecting tampered or forged tokens.","secure_code":"import jwt\nimport json\nimport os\nfrom flask import request, jsonify\n\nIOT_SECRET_KEY = os.environ.get('IOT_JWT_SECRET_KEY')\nALLOWED_ALGORITHMS = ['HS256']\n\ndef verify_iot_device_token(auth_header):\n    try:\n        token = auth_header.split(' ')[1]\n        device_payload = jwt.decode(\n            token,\n            key=IOT_SECRET_KEY,\n            algorithms=ALLOWED_ALGORITHMS,\n            options={\"verify_signature\": True, \"require\": [\"device_id\", \"role\", \"exp\"]}\n        )\n        if device_payload.get('device_id') and device_payload.get('role') == 'admin':\n            return jsonify({\"status\": \"authorized\", \"device_id\": device_payload['device_id'], \"access_level\": \"full\"})\n        return jsonify({\"status\": \"authorized\", \"device_id\": device_payload['device_id'], \"access_level\": \"limited\"})\n    except jwt.ExpiredSignatureError:\n        return jsonify({\"error\": \"token_expired\"}), 401\n    except jwt.InvalidAlgorithmError:\n        return jsonify({\"error\": \"invalid_algorithm\"}), 401\n    except jwt.InvalidSignatureError:\n        return jsonify({\"error\": \"invalid_signature\"}), 401\n    except Exception as e:\n        return jsonify({\"error\": \"invalid_token\"}), 401"}