File size: 3,767 Bytes
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Seal Login credentials with a context-bound AES-256-GCM data key."""
import base64
import json
import os
import secrets

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

VERSION = 1


class LoginLocked(RuntimeError):
    """The configured Login encryption backend is unavailable."""


class LoginEnvelopeError(ValueError):
    """A Login envelope or its encryption context is invalid."""


def context(tenant, entry_id, origin):
    values = (tenant, entry_id, origin)
    if any(not isinstance(value, str) or not value or len(value) > 2048 for value in values):
        raise LoginEnvelopeError("The Login encryption context is invalid.")
    return dict(zip(("tenant", "entry_id", "origin"), values))


def aad(ctx):
    if not isinstance(ctx, dict) or set(ctx) != {"tenant", "entry_id", "origin"}:
        raise LoginEnvelopeError("The Login encryption context is invalid.")
    clean = context(ctx["tenant"], ctx["entry_id"], ctx["origin"])
    return json.dumps(clean, sort_keys=True, separators=(",", ":")).encode("utf-8")


def encode(value):
    return base64.b64encode(value).decode("ascii")


def _local_key():
    raw = os.environ.get("AIOS_LOGIN_LOCAL_KEY", "")
    if len(raw) < 32:
        raise LoginLocked("The Login vault is locked.")
    try:
        return HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
                    info=b"aios/logins/local/v1").derive(raw.encode("utf-8"))
    except Exception:
        raise LoginLocked("The Login vault is locked.") from None


def _kms_client():
    try:
        import boto3
        return boto3.client("kms")
    except Exception:
        raise LoginLocked("The Login vault is locked.") from None


def seal(payload, ctx):
    """Return ciphertext and a wrapped data key without a decryption API."""
    associated = aad(ctx)
    if (not isinstance(payload, dict) or set(payload) != {"password", "totp_seed"}
            or any(not isinstance(value, str) for value in payload.values())):
        raise LoginEnvelopeError("The Login credential payload is invalid.")
    backend = os.environ.get("AIOS_LOGIN_ENVELOPE", "local").strip().lower()
    nonce = secrets.token_bytes(12)
    envelope = {"version": VERSION, "backend": backend, "nonce": encode(nonce)}
    try:
        if backend == "local":
            wrapping_key = _local_key()
            data_key = secrets.token_bytes(32)
            wrap_nonce = secrets.token_bytes(12)
            wrapped = wrap_nonce + AESGCM(wrapping_key).encrypt(
                wrap_nonce, data_key, b"wrap\x00" + associated)
        elif backend == "kms":
            key_id = os.environ.get("AIOS_LOGIN_KMS_KEY_ID", "").strip()
            if not key_id:
                raise LoginLocked("The Login vault is locked.")
            result = _kms_client().generate_data_key(
                KeyId=key_id, KeySpec="AES_256", EncryptionContext=ctx)
            data_key, wrapped = result["Plaintext"], result["CiphertextBlob"]
            if (not isinstance(data_key, bytes) or len(data_key) != 32
                    or not isinstance(wrapped, bytes) or not wrapped):
                raise LoginLocked("The Login vault is locked.")
            envelope["kms_key_id"] = key_id
        else:
            raise LoginLocked("The Login vault is locked.")
        raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        envelope["ciphertext"] = encode(AESGCM(data_key).encrypt(nonce, raw, associated))
        envelope["wrapped_key"] = encode(wrapped)
        return envelope
    except LoginLocked:
        raise
    except Exception:
        raise LoginLocked("The Login vault is locked.") from None