# Disabled JWT Signature Verification

Language: Python
Severity: Critical
CWE: CWE-347

## Source
6

## Flow
6-7

## Sink
7

## Vulnerable Code
```python
import jwt
import json
from flask import request, jsonify

def verify_iot_device_token(auth_header):
    try:
        token = auth_header.split(' ')[1]
        device_payload = jwt.decode(token, options={"verify_signature": False})
        if device_payload.get('device_id') and device_payload.get('role') == 'admin':
            return jsonify({"status": "authorized", "device_id": device_payload['device_id'], "access_level": "full"})
        return jsonify({"status": "authorized", "device_id": device_payload['device_id'], "access_level": "limited"})
    except Exception as e:
        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
```python
import jwt
import json
import os
from flask import request, jsonify

IOT_SECRET_KEY = os.environ.get('IOT_JWT_SECRET_KEY')
ALLOWED_ALGORITHMS = ['HS256']

def verify_iot_device_token(auth_header):
    try:
        token = auth_header.split(' ')[1]
        device_payload = jwt.decode(
            token,
            key=IOT_SECRET_KEY,
            algorithms=ALLOWED_ALGORITHMS,
            options={"verify_signature": True, "require": ["device_id", "role", "exp"]}
        )
        if device_payload.get('device_id') and device_payload.get('role') == 'admin':
            return jsonify({"status": "authorized", "device_id": device_payload['device_id'], "access_level": "full"})
        return jsonify({"status": "authorized", "device_id": device_payload['device_id'], "access_level": "limited"})
    except jwt.ExpiredSignatureError:
        return jsonify({"error": "token_expired"}), 401
    except jwt.InvalidAlgorithmError:
        return jsonify({"error": "invalid_algorithm"}), 401
    except jwt.InvalidSignatureError:
        return jsonify({"error": "invalid_signature"}), 401
    except Exception as e:
        return jsonify({"error": "invalid_token"}), 401
```
