{"title":"Hardcoded Cryptographic Key in Fernet Encryption","language":"Python","severity":"Critical","cwe":"CWE-798","source_lines":[5],"flow_lines":[5,6,7,8],"sink_lines":[6],"vulnerable_code":"from cryptography.fernet import Fernet\nimport boto3\n\ndef encrypt_iot_telemetry(device_id, sensor_data):\n    MASTER_KEY = b'zK8vQ2mP9xR4wN7jL3hF6tY1sC5bV0aE8dG2nM4pU6q='\n    cipher = Fernet(MASTER_KEY)\n    payload = f\"{device_id}|{sensor_data['temp']}|{sensor_data['humidity']}\"\n    encrypted_payload = cipher.encrypt(payload.encode())\n    s3_client = boto3.client('s3')\n    s3_client.put_object(Bucket='iot-telemetry-vault', Key=f'device_{device_id}.enc', Body=encrypted_payload)\n    return encrypted_payload.decode()","explanation":"The code contains a hardcoded Fernet encryption key directly embedded in the source code (line 5), which is then used to initialize the cipher (line 6). This compromises the confidentiality of all encrypted telemetry data since anyone with access to the source code or binary can extract the key and decrypt all stored IoT sensor data in the S3 bucket.","remediation":"The fix removes the hardcoded cryptographic key and replaces it with a secure retrieval mechanism using AWS Secrets Manager. The encryption key is now fetched at runtime from a managed secrets store, ensuring it never appears in source code and can be rotated without code changes.","secure_code":"from cryptography.fernet import Fernet\nimport boto3\nimport os\n\n\ndef get_encryption_key():\n    \"\"\"Retrieve encryption key from AWS Secrets Manager.\"\"\"\n    secret_name = os.environ.get('IOT_ENCRYPTION_KEY_SECRET', 'iot-telemetry-encryption-key')\n    region = os.environ.get('AWS_REGION', 'us-east-1')\n    \n    client = boto3.client('secretsmanager', region_name=region)\n    response = client.get_secret_value(SecretId=secret_name)\n    return response['SecretString'].encode()\n\n\ndef encrypt_iot_telemetry(device_id, sensor_data):\n    encryption_key = get_encryption_key()\n    cipher = Fernet(encryption_key)\n    payload = f\"{device_id}|{sensor_data['temp']}|{sensor_data['humidity']}\"\n    encrypted_payload = cipher.encrypt(payload.encode())\n    s3_client = boto3.client('s3')\n    s3_client.put_object(Bucket='iot-telemetry-vault', Key=f'device_{device_id}.enc', Body=encrypted_payload)\n    return encrypted_payload.decode()"}