wireguard_peer_manager/kiss/toml-manager/auth/token_auth.py

37 lines
1.3 KiB
Python
Raw Permalink Normal View History

import json
import base64
from utils.crypto_utils import decrypt_symmetric_key, decrypt_data, encrypt_data, CLIENT_PUBLIC_KEY
from cryptography.exceptions import InvalidSignature
import logging
def validate_token(auth_header, encrypted_data):
if not auth_header or not auth_header.startswith("Bearer "):
raise ValueError("Invalid Authorization header")
# Extract JWE token
jwe_token = auth_header.split(" ")[1]
payload = json.loads(base64.b64decode(jwe_token.split('.')[1]))
# Extract the encrypted symmetric key from the token payload
encrypted_symmetric_key = base64.b64decode(payload['enc_sym_key'])
# Decrypt the symmetric key
symmetric_key = decrypt_symmetric_key(encrypted_symmetric_key)
# Decrypt the data using the symmetric key
decrypted_data = decrypt_data(encrypted_data, symmetric_key)
# Verify client's signature
signature = base64.b64decode(payload['signature'])
try:
CLIENT_PUBLIC_KEY.verify(
signature,
decrypted_data.encode(),
ec.ECDSA(hashes.SHA256())
)
except InvalidSignature:
raise ValueError("Invalid client signature")
# Return both decrypted data and the symmetric key for response encryption
return json.loads(decrypted_data), symmetric_key