// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Package loginseal opens what the app seals to the enclave's login key (QA-289, // docs/e2ee/work-plan.md 4.11): the input of a messenger sign-in step (an app password, a code, // cookies) and the code proving an identity reset, which the API passes on without being able to // read them. It also signs the sign-in steps a bridge answers, so that the app shows only steps of // its own sign-in: what the server shows (a QR code, a pairing code, a PIN) cannot be sealed. // // The app seals with HPKE (RFC 9180) in base mode, DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 and // AES-256-GCM, with an info naming where the value goes (LoginInfo, IdentityInfo) and no AAD. The // envelope is {"v":1,"kid":…,"enc":…,"ct":…}, its strings unpadded base64url; kid is the first 8 // bytes of the public key's SHA-256. The enclave gives each bridge the 32-byte X25519 private key in // the file XESSENGER_LOGIN_KEY_FILE names, and the app gets the public key from the enclave's // attestation. // // Steps are signed with an Ed25519 key derived from the login key (HKDF-SHA256, info // "xessenger-login-signing-v1"), whose public half the attestation carries too (SignStep). package loginseal import ( "bytes" "crypto/ecdh" "crypto/ed25519" "crypto/hkdf" "crypto/hpke" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "os" "sync" ) const ( // KeyFileEnv names the file holding the login key: the 32-byte X25519 private key, as the enclave // writes it (/run/xessenger/login/.key). KeyFileEnv = "XESSENGER_LOGIN_KEY_FILE" // PublicKeyEnv holds the login key's public half in standard base64, as the enclave's attestation // carries it to the app. PublicKeyEnv = "XESSENGER_LOGIN_PUBLIC_KEY" // SigningPublicKeyEnv holds the public half of the signing key derived from the login key, in // standard base64, as the enclave's attestation carries it to the app. SigningPublicKeyEnv = "XESSENGER_LOGIN_SIGNING_PUBLIC_KEY" // SignedStepField is the field a bridge adds to the sign-in step it answers: the step signed for // the login's owner (SignedStep). SignedStepField = "com.xessenger.signed_step" // Version is the version of the envelopes this package opens and of the steps it signs. Version = 1 // KeySize is the size of the login key and of its public half. KeySize = 32 kidSize = 8 // bytes of the public key's SHA-256 encSize = 32 // DHKEM(X25519) encapsulated key tagSize = 16 // AES-256-GCM tag // signingInfo is the HKDF info deriving the signing key's seed from the login key. signingInfo = "xessenger-login-signing-v1" // stepContext comes before a signed step's payload in what the signature covers. stepContext = "xessenger-login-step-v1:" ) // The envelope's KDF and AEAD; its KEM is the key's, DHKEM(X25519, HKDF-SHA256). var ( kdf = hpke.HKDFSHA256() aead = hpke.AES256GCM() ) var ( // ErrNoKey is returned when the program runs without a login key. ErrNoKey = errors.New("loginseal: no login key") // ErrKeyChanged is returned for an envelope sealed to another login key, or a step signed with // another signing key: the app has to fetch the attestation again, and seal anew. ErrKeyChanged = errors.New("loginseal: sealed to another login key") // ErrMalformed is returned for an envelope this package does not open. ErrMalformed = errors.New("loginseal: malformed envelope") // ErrOpen is returned for an envelope that does not open with the key and info: it was sealed for // another bridge, login, step or identity, or changed on the way. ErrOpen = errors.New("loginseal: the envelope does not open") // ErrSignature is returned for a signed step whose signature does not verify. ErrSignature = errors.New("loginseal: the signature does not verify") ) // Key is the enclave's login key, with the signing key derived from it. type Key struct { private hpke.PrivateKey public []byte kid string signing ed25519.PrivateKey signingKid string } // NewKey takes the 32-byte X25519 private key. func NewKey(raw []byte) (*Key, error) { if len(raw) != KeySize { return nil, fmt.Errorf("loginseal: the login key has %d bytes, not %d", len(raw), KeySize) } private, err := ecdh.X25519().NewPrivateKey(raw) if err != nil { return nil, fmt.Errorf("loginseal: %w", err) } kem, err := hpke.NewDHKEMPrivateKey(private) if err != nil { return nil, fmt.Errorf("loginseal: %w", err) } seed, err := hkdf.Key(sha256.New, raw, nil, signingInfo, ed25519.SeedSize) if err != nil { return nil, fmt.Errorf("loginseal: %w", err) } signing := ed25519.NewKeyFromSeed(seed) public := private.PublicKey().Bytes() return &Key{ private: kem, public: public, kid: KeyID(public), signing: signing, signingKid: KeyID(signing.Public().(ed25519.PublicKey)), }, nil } // LoadKey reads the login key from a file. func LoadKey(path string) (*Key, error) { raw, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("loginseal: failed to read the login key: %w", err) } return NewKey(raw) } var defaultKey = sync.OnceValues(fromEnvironment) // Default is the program's login key, read once from the file XESSENGER_LOGIN_KEY_FILE names. Without // the variable it is nil, which opens nothing (ErrNoKey); a file that cannot be used is an error. func Default() (*Key, error) { return defaultKey() } func fromEnvironment() (*Key, error) { path := os.Getenv(KeyFileEnv) if path == "" { return nil, nil } return LoadKey(path) } // KeyID is the kid of a public key: the first 8 bytes of its SHA-256, unpadded base64url. func KeyID(public []byte) string { sum := sha256.Sum256(public) return base64.RawURLEncoding.EncodeToString(sum[:kidSize]) } // Kid is the key's kid, empty without a key. func (k *Key) Kid() string { if k == nil { return "" } return k.kid } // PublicKey is the key's public half in standard base64, as XESSENGER_LOGIN_PUBLIC_KEY and the // attestation carry it. func (k *Key) PublicKey() string { return base64.StdEncoding.EncodeToString(k.public) } // SigningPublicKey is the signing key's public half in standard base64, as // XESSENGER_LOGIN_SIGNING_PUBLIC_KEY and the attestation carry it. func (k *Key) SigningPublicKey() string { return base64.StdEncoding.EncodeToString(k.signing.Public().(ed25519.PublicKey)) } // SigningKid is the signing key's kid, empty without a key. func (k *Key) SigningKid() string { if k == nil { return "" } return k.signingKid } // LoginInfo is the info of a sign-in step's input: it opens only for that bridge (its appservice ID, // the API's channel), the Matrix user who started the login, the login process and the step. The // bridge, the login process ID (bridgev2's xid) and the step ID have no colon, so the user ID's own // colons leave a single reading. func LoginInfo(bridge, userID, loginID, stepID string) string { return "xessenger-login-v2:" + bridge + ":" + userID + ":" + loginID + ":" + stepID } // IdentityInfo is the info of the code proving an identity reset: it opens only for that bridge, Matrix // user and new master key (unpadded base64, as Matrix writes keys). func IdentityInfo(bridge, userID, masterKey string) string { return "xessenger-identity-v1:" + bridge + ":" + userID + ":" + masterKey } // Envelope is a sealed value as the app sends it. type Envelope struct { V int `json:"v"` Kid string `json:"kid"` Enc string `json:"enc"` Ct string `json:"ct"` } // Open opens a sealed value, the envelope's JSON, for info. func (k *Key) Open(info string, sealed []byte) ([]byte, error) { if k == nil { return nil, ErrNoKey } envelope, enc, ct, err := parse(sealed) if err != nil { return nil, err } if envelope.Kid != k.kid { return nil, ErrKeyChanged } plaintext, err := hpke.Open(k.private, kdf, aead, []byte(info), append(enc, ct...)) if err != nil { return nil, ErrOpen } return plaintext, nil } // parse reads an envelope strictly: its four fields and nothing else, each string in canonical // unpadded base64url. func parse(sealed []byte) (envelope Envelope, enc, ct []byte, err error) { decoder := json.NewDecoder(bytes.NewReader(sealed)) decoder.DisallowUnknownFields() if err = decoder.Decode(&envelope); err != nil { return envelope, nil, nil, fmt.Errorf("%w: %v", ErrMalformed, err) } if _, err = decoder.Token(); err != io.EOF { return envelope, nil, nil, fmt.Errorf("%w: data after the envelope", ErrMalformed) } if envelope.V != Version { return envelope, nil, nil, fmt.Errorf("%w: version %d", ErrMalformed, envelope.V) } if kid, err := decode(envelope.Kid); err != nil || len(kid) != kidSize { return envelope, nil, nil, fmt.Errorf("%w: kid is not %d bytes of unpadded base64url", ErrMalformed, kidSize) } if enc, err = decode(envelope.Enc); err != nil || len(enc) != encSize { return envelope, nil, nil, fmt.Errorf("%w: enc is not %d bytes of unpadded base64url", ErrMalformed, encSize) } if ct, err = decode(envelope.Ct); err != nil || len(ct) < tagSize { return envelope, nil, nil, fmt.Errorf("%w: ct is not at least %d bytes of unpadded base64url", ErrMalformed, tagSize) } return envelope, enc, ct, nil } // SignedStep is a sign-in step signed for the user its login is for. The bridge adds it to the step it // answers (SignedStepField), the API passes it on as it is, and the app shows only what the payload // holds once the signature verifies with the attested signing key. Payload is the JSON of a // StepPayload; Sig is the Ed25519 signature of "xessenger-login-step-v1:" followed by the payload's // bytes; both are unpadded base64url. Carrying the signed bytes spares both sides a canonical JSON. type SignedStep struct { V int `json:"v"` Kid string `json:"kid"` Payload string `json:"payload"` Sig string `json:"sig"` } // StepPayload is what a signed step vouches for: the step as bridgev2 answered it (login_id, type, // step_id, instructions and the step's parameters), for that bridge's login owned by that user. type StepPayload struct { Bridge string `json:"bridge"` UserID string `json:"user_id"` Step json.RawMessage `json:"step"` } // SignStep signs a sign-in step, bridgev2's answer, for the bridge's login owned by userID. func (k *Key) SignStep(bridge, userID string, step json.RawMessage) (*SignedStep, error) { if k == nil { return nil, ErrNoKey } var payload bytes.Buffer encoder := json.NewEncoder(&payload) encoder.SetEscapeHTML(false) if err := encoder.Encode(StepPayload{Bridge: bridge, UserID: userID, Step: bytes.TrimSpace(step)}); err != nil { return nil, fmt.Errorf("loginseal: %w", err) } signed := bytes.TrimSuffix(payload.Bytes(), []byte("\n")) return &SignedStep{ V: Version, Kid: k.signingKid, Payload: base64.RawURLEncoding.EncodeToString(signed), Sig: base64.RawURLEncoding.EncodeToString(ed25519.Sign(k.signing, append([]byte(stepContext), signed...))), }, nil } // VerifyStep checks a signed step with the signing key's 32-byte public half, as the app does, and // returns what it vouches for. func VerifyStep(public []byte, signed SignedStep) (*StepPayload, error) { if len(public) != ed25519.PublicKeySize { return nil, fmt.Errorf("loginseal: the signing key has %d bytes, not %d", len(public), ed25519.PublicKeySize) } if signed.V != Version { return nil, fmt.Errorf("%w: version %d", ErrMalformed, signed.V) } if signed.Kid != KeyID(public) { return nil, ErrKeyChanged } payload, err := decode(signed.Payload) if err != nil { return nil, fmt.Errorf("%w: payload is not unpadded base64url", ErrMalformed) } sig, err := decode(signed.Sig) if err != nil || len(sig) != ed25519.SignatureSize { return nil, fmt.Errorf("%w: sig is not %d bytes of unpadded base64url", ErrMalformed, ed25519.SignatureSize) } if !ed25519.Verify(public, append([]byte(stepContext), payload...), sig) { return nil, ErrSignature } var step StepPayload if err = json.Unmarshal(payload, &step); err != nil { return nil, fmt.Errorf("%w: %v", ErrMalformed, err) } return &step, nil } // decode takes canonical unpadded base64url only: Go's decoder also skips line breaks. func decode(field string) ([]byte, error) { value, err := base64.RawURLEncoding.DecodeString(field) if err != nil { return nil, err } if base64.RawURLEncoding.EncodeToString(value) != field { return nil, errors.New("not canonical") } return value, nil }