// 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 bridgekit import ( "context" "crypto/hkdf" "crypto/sha256" "database/sql" "encoding/hex" "errors" "fmt" "os" "path/filepath" "strings" "go.mau.fi/util/dbutil" "maunium.net/go/mautrix/bridgev2/database" ) // EnvSealKeyFile names the variable that holds the path of the bridge's own key: 32 raw bytes in a // file named after the bridge (/run/xessenger/seal/.key), which only the bridge's enclave // can open. It is the seal package's key (seal.EnvKeyFile), which seals the bridge's account // secrets. const EnvSealKeyFile = "XESSENGER_SEAL_KEY_FILE" // Purposes of the keys derived from the bridge's key. const ( purposeGhostHMAC = "ghost-hmac" purposeStore = "bridgekit-store" ) // deriveKey derives a key for one purpose of one bridge from the bridge's key, with HKDF-SHA256 like // every key the seal package derives from it ("xessenger/seal/v1//"). func deriveKey(key []byte, purpose, bridge string) ([]byte, error) { return hkdf.Key(sha256.New, key, nil, "xessenger/seal/v1/derive/"+purpose+"/"+bridge, 32) } // sealedKeys reads the bridge's key and derives the ghost and store keys from it. Without the // variable there are no keys from it (an unsealed bridge has them in its kv_store, unsealedKeys); a // set variable whose file cannot be used stops the bridge, as it does for the seal package. func sealedKeys(bridge string) (ghostKey, storeKey []byte, err error) { path, ok := os.LookupEnv(EnvSealKeyFile) if !ok { return nil, nil, nil } name, ok := strings.CutSuffix(filepath.Base(path), ".key") if !ok || name != bridge { return nil, nil, fmt.Errorf("%s=%q: the key file must be named %s.key", EnvSealKeyFile, path, bridge) } key, err := os.ReadFile(path) if err != nil { return nil, nil, fmt.Errorf("%s: %w", EnvSealKeyFile, err) } defer clear(key) if len(key) != 32 { return nil, nil, fmt.Errorf("%s=%q: the key must be 32 raw bytes, not %d", EnvSealKeyFile, path, len(key)) } if ghostKey, err = deriveKey(key, purposeGhostHMAC, bridge); err != nil { return nil, nil, err } if storeKey, err = deriveKey(key, purposeStore, bridge); err != nil { return nil, nil, err } return ghostKey, storeKey, nil } // The ghost and store keys as an unsealed bridge keeps them in its kv_store, in hex (the seal // package's DerivedKeys). Unsealing (XESSENGER_SEAL_UNSEAL=1) writes them there, so that the bridge // started without its key afterwards still names contacts and reads its own tables as before; a bridge // that has its key never stores them. const ( kvGhostKey database.Key = "xessenger_ghost_hmac_key" kvStoreKey database.Key = "xessenger_bridgekit_store_key" ) // unsealedKeys reads the ghost and store keys an unsealed bridge left in its kv_store: both or none. // Only one of them, one that is not a 32-byte key in hex, or a read that fails stops the bridge. func unsealedKeys(ctx context.Context, db *dbutil.Database, kv *database.KVQuery) (ghostKey, storeKey []byte, err error) { // A new database gets its kv_store only when the bridge starts, after the extension attached. if exists, err := db.TableExists(ctx, "kv_store"); err != nil { return nil, nil, fmt.Errorf("failed to look for kv_store: %w", err) } else if !exists { return nil, nil, nil } ghostHex, err := storedKV(ctx, kv, kvGhostKey) if err != nil { return nil, nil, err } storeHex, err := storedKV(ctx, kv, kvStoreKey) if err != nil { return nil, nil, err } if ghostHex == "" && storeHex == "" { return nil, nil, nil } if ghostKey, err = hexKey(kvGhostKey, ghostHex); err != nil { return nil, nil, err } if storeKey, err = hexKey(kvStoreKey, storeHex); err != nil { return nil, nil, err } return ghostKey, storeKey, nil } // storedKV reads a kv_store value as KVQuery.Get does, "" when there is none, but returns a read that // fails: Get answers "" for it as for none, and the bridge would start without the keys it has, with // encryption off until it starts again. The derived keys are stored as they are, never sealed // (mautrix-seal.patch xsSealKV), so Get would open nothing of them. func storedKV(ctx context.Context, kv *database.KVQuery, key database.Key) (string, error) { var value string err := kv.QueryRow(ctx, `SELECT value FROM kv_store WHERE bridge_id=$1 AND key=$2`, kv.BridgeID, key).Scan(&value) if errors.Is(err, sql.ErrNoRows) { return "", nil } else if err != nil { return "", fmt.Errorf("failed to read %s from kv_store: %w", key, err) } return value, nil } func hexKey(name database.Key, value string) ([]byte, error) { key, err := hex.DecodeString(value) if err != nil || len(key) != 32 { return nil, fmt.Errorf("kv_store %s is not a 32-byte key in hex", name) } return key, nil }