// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // Argon2id for group passphrases, at-rest history sealing, rate limiting, and // the deterministic identity seed that TLS pins and certificates derive from. // TlsChannel handles peer authentication and transport encryption. #pragma once #include #include #include #include #include #include #include #include #include #include #include namespace koutnet { class DeriveWorker; // defined in the .cpp, moved to m_deriveThread class CryptoManager : public QObject { Q_OBJECT public: // 192-bit nonce, carried by the passphrase and at-rest ciphertexts. static constexpr int kNonceLen = 24; static constexpr int kTagLen = 16; static constexpr int kKeyLen = 32; // crypto_pwhash_SALTBYTES; static_asserted against libsodium in the .cpp. static constexpr int kSaltLen = 16; // Bound memory use when many different passphrases are encountered. static constexpr int kMaxPassphraseCacheSize = 256; // same again for the rate-limit windows, which are keyed on source address // and would otherwise be the way around the cap above. static constexpr int kMaxRatePeers = 1024; // Ceiling on the async decrypt queue, and on the ciphertext body a queued // message may carry. The derivation that heads the queue costs 64 MiB and // two passes, so a flood must cost memory slots, not memory itself - see // decryptAsync(). static constexpr int kMaxPendingDecrypts = 8; static constexpr int kMaxAsyncPayloadBytes = 1024 * 1024; explicit CryptoManager(QObject *parent = nullptr); // Identity kept under a suffix of its own, in the encrypted store and in the config // file alike. Only tests pass a scope; it is what lets two peers live in // one process without the second loading the first one's keypair. explicit CryptoManager(const QString &storageScope, QObject *parent = nullptr); ~CryptoManager() override; // True after generateAndStoreKeys() fell back to an in-memory identity // because the store was unreachable. The caller (main.cpp, QML) should // show a warning on the first run that hits this. bool isStoreDegraded() const { return m_storeDegraded; } // False when keypair generation or loading failed at startup: nothing below // can establish a session without keys, so every call simply refuses. bool isValid() const { return m_valid; } // The identity id that came down from a peer certificate's CommonName. // The id->address routing and pin trust live in NetworkManager (TlsChannel // pins), this id is only a name derived from the identity's public key. static QString identityIdFor(const QByteArray &idPubRaw); QString ownIdentityId() const; // The 32-byte seed this identity was generated from: the first half of the // expanded Ed25519 secret key, and exactly what SecretStore holds. The TLS // identity (IdentityCertificate) derives its deterministic P-256 keypair // from it. Empty when no keys were loaded. QByteArray identitySeed() const; // Fingerprint of our own identity public key, shown in the UI. QString fingerprint() const; // still keyed on the source address: it runs before anything is known about // who sent the packet. bool checkRate(const QString &sourceAddress, int maxPerSec = 200) const; QString encrypt(const QString &plaintext, const QString &passphrase = QString()) const; QString decrypt(const QString &ciphertext, const QString &passphrase = QString()) const; // Async decrypt for the receive path. Argon2id derivation (64 MiB) runs // on a worker thread so an attacker's fresh-salt flood can't freeze the // GUI. delivered=false means the queue gate refused it (flood), don't render. void decryptAsync(const QString &ciphertext, const QString &passphrase, const std::function &done); // at-rest history runs under the app's own key, kept in SecretStore and never // a peer session: a conversation must stay readable after every peer is // gone, so no wire key ever opens the logs. A domain tag keeps a stored log // from being replayed as a voice frame or a file chunk and the reverse. // sealAtRest() returns empty on a wrong-size key; openAtRest() refuses // anything that is not a genuine sealed blob. static QByteArray sealAtRest(const QByteArray &key, const QByteArray &payload); static bool openAtRest(const QByteArray &key, const QByteArray &data, QByteArray *outPayload); static QByteArray generateAtRestKey(); Q_SIGNALS: // the plaintext copy an older build left in the config file could not be // deleted and is still readable on disk; only the user can repair that. void plaintextKeysLeftInConfig(const QString &reason); // Store unreachable at startup. Throwaway identity for this session only, // won't survive restart. Warn the user. void storeDegraded(const QString &reason); private: bool initKeypairs(); bool loadStoredKeys(); bool generateAndStoreKeys(); bool migrateLegacyKeys(QString *outIdentityB64); void dropLegacyPlaintextKeys(); bool stashSupersededPlaintextKeys(); void reportPlaintextKeysLeft(const QString &reason); // the decryptAsync() queue. A fast entry (cache hit, error, cleartext // passthrough) carries its resolved text and only exists to keep its place // in line behind a slow one; a derive entry is waiting for its Argon2id // derivation on the worker thread. struct PendingDecrypt { bool needsDerivation = false; QByteArray salt; // derive entries only, kSaltLen QByteArray payload; // derive entries only, ciphertext after the salt QString passphrase; // derive entries only, for the cache key QString result; // fast entries only, computed at enqueue time std::function done; }; void startDerivation(); void onDerived(const QByteArray &salt, std::shared_ptr key, bool ok); static QByteArray cacheKeyFor(const QString &passphrase, const QByteArray &salt); // aad is the one-byte domain tag of the slot this ciphertext belongs in, so // a sealed at-rest log cannot be spliced in where a message body is read. static QByteArray aeadSeal(const QByteArray &key, const QByteArray &plaintext, char aad); static bool aeadOpen(const QByteArray &key, const QByteArray &data, char aad, QByteArray *outPlain); QByteArray deriveKey(const QString &passphrase, const QByteArray &salt) const; static QByteArray randomBytes(int n); const QString m_storageScope; bool m_valid = false; bool m_storeDegraded = false; // Expanded 64-byte Ed25519 secret; SecretStore persists the 32-byte seed. QByteArray m_identitySk; QByteArray m_identityPubBytes; // Rate limits are keyed by source address, before peer authentication. mutable QHash> m_rateCounters; // Digest of salt and passphrase -> derived key; avoids retaining plaintext keys. mutable QHash m_passphraseKeyCache; // the queue above, one derivation in flight at a time. The thread is created // on the first derivation that needs one, and the destructor stops it // before any key material is wiped. QList m_pendingDecrypts; bool m_derivationInFlight = false; QThread *m_deriveThread = nullptr; DeriveWorker *m_deriveWorker = nullptr; }; } // namespace koutnet