// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "CryptoManager.h" #include "SecretStore.h" #include "koutnet_crypto_debug.h" #include #include #include #include #include #include #include #include namespace koutnet { // Make sure the sizes match libsodium at compile time, not at runtime when // a packet fails to open. static_assert(CryptoManager::kSaltLen == crypto_pwhash_SALTBYTES); static_assert(CryptoManager::kNonceLen == crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); static_assert(CryptoManager::kTagLen == crypto_aead_xchacha20poly1305_ietf_ABYTES); static_assert(CryptoManager::kKeyLen == crypto_aead_xchacha20poly1305_ietf_KEYBYTES); namespace { // Must run before anything else. Static = once per process, thread-safe. // sodium_init() returns 1 if already done, negative = unusable. bool sodiumReady() { static const bool ok = sodium_init() >= 0; return ok; } // Interactive, not MODERATE: the decrypting peer pays the memory cost for // every unseen salt (the sender picks it), so MODERATE would amplify DoS // against us, not just against brute-force attackers. constexpr unsigned long long kPwhashOps = crypto_pwhash_OPSLIMIT_INTERACTIVE; constexpr size_t kPwhashMem = crypto_pwhash_MEMLIMIT_INTERACTIVE; // Domain tags, bound as AEAD associated data so that a ciphertext only opens // in the slot it was sealed for. Also the wire type byte for the two message // forms. The session-message and wire-frame slots of the old handshake-era // build are gone: peer traffic now rides TLS, only passphrase-sealed group // messages and at-rest history stay libsodium AEAD. constexpr char kAadPassphraseMessage = 0x02; // at-rest history, clear of the live-transport slot above so a log taken off // the disk can never be fed back in where a live message is read. constexpr char kAadHistoryFile = 0x20; // Bumped from KNC1 when the primitives changed. A peer on the old build now gets // "cleartext on a keyed channel" instead of a Poly1305 failure it cannot explain. QString wireMarker() { return QStringLiteral("KNC2:"); } double nowEpoch() { return QDateTime::currentMSecsSinceEpoch() / 1000.0; } // Wipe key material before freeing. QByteArray/QString only release the block, // so secrets stay in the heap (core dump, swap, etc). data() detaches first, // so this only wipes the copy we own, safe because every call site below // has the only reference. void cleanse(QByteArray &buf) { if (!buf.isEmpty()) sodium_memzero(buf.data(), size_t(buf.size())); } void cleanse(QString &str) { if (!str.isEmpty()) sodium_memzero(str.data(), size_t(str.size()) * sizeof(QChar)); } // Deleter for the shared buffer a derived key crosses the thread boundary in: // wipes the data before releasing the heap, so a dropped queued signal does not // leave the last copy of the key lying around. void wipeKeyBuffer(QByteArray *buf) { cleanse(*buf); delete buf; } // same thing at every exit path of a function, which is the part that gets // forgotten - loadStoredKeys() alone returns from five places. template class Wiper { public: explicit Wiper(T &buf) : m_buf(buf) { } ~Wiper() { cleanse(m_buf); } Wiper(const Wiper &) = delete; Wiper &operator=(const Wiper &) = delete; private: T &m_buf; }; // Store entry name; the QSettings path it replaced is in migrateLegacyKeys(). // an empty scope is the application's own identity, so its name stays as it was. QString identityStoreKey(const QString &scope) { return scope.isEmpty() ? QStringLiteral("identity_priv_b64") : QStringLiteral("identity_priv_b64_") + scope; } // where builds before the encrypted store kept the identity key, in clear text. // The old build also parked a DH secret next to it that nothing uses anymore; // it is wiped, not migrated, so no dead key material survives in plain text. QString legacyIdentityConfigKey(const QString &scope) { if (scope.isEmpty()) return QStringLiteral("security/identity_priv_b64"); return QStringLiteral("security/%1_identity_priv_b64").arg(scope); } QString legacyDhConfigKey(const QString &scope) { if (scope.isEmpty()) return QStringLiteral("security/dh_priv_b64"); return QStringLiteral("security/%1_dh_priv_b64").arg(scope); } QString supersededStoreKey(const QString &storeKey) { return storeKey + QStringLiteral("_superseded"); } QString bytesToFingerprint(const QByteArray &raw) { const QByteArray h = QCryptographicHash::hash(raw, QCryptographicHash::Sha256).toHex(); QString out; for (int i = 0; i < 24; i += 4) { if (i) out += QLatin1Char(' '); out += QString::fromLatin1(h.mid(i, 4)).toUpper(); } return out; } } // namespace // Argon2id on its own thread. Keeps the 64 MiB/2-pass derivation off the GUI // thread (see decryptAsync()). Key is wiped before returning. class DeriveWorker : public QObject { Q_OBJECT public: DeriveWorker() = default; public Q_SLOTS: void derive(const QString &passphrase, const QByteArray &salt) { QByteArray pass = passphrase.toUtf8(); Wiper wipePass(pass); // the key crosses to the GUI thread as a shared buffer whose deleter // wipes it: even if the queued signal is dropped at shutdown, the last // reference cleanses the copy Qt was holding instead of freeing it. auto key = std::shared_ptr(new QByteArray(CryptoManager::kKeyLen, 0), wipeKeyBuffer); const int rc = crypto_pwhash(reinterpret_cast(key->data()), CryptoManager::kKeyLen, pass.constData(), static_cast(pass.size()), reinterpret_cast(salt.constData()), kPwhashOps, kPwhashMem, crypto_pwhash_ALG_ARGON2ID13); const bool ok = (rc == 0); Q_EMIT derived(salt, key, ok); } Q_SIGNALS: void derived(QByteArray salt, std::shared_ptr key, bool ok); }; CryptoManager::CryptoManager(QObject *parent) : CryptoManager(QString(), parent) { } CryptoManager::CryptoManager(const QString &storageScope, QObject *parent) : QObject(parent) , m_storageScope(storageScope) { if (!sodiumReady()) { qCCritical(KOUTNET_LOG_CRYPTO, "sodium_init() failed - libsodium is unusable, so this process has no " "cryptography at all. Every call below refuses."); return; } m_valid = initKeypairs(); if (!m_valid) { qCCritical(KOUTNET_LOG_CRYPTO, "failed to initialize the identity keypair - no certificates or sealing " "for this session. Check isValid() before relying on encrypt()."); } } CryptoManager::~CryptoManager() { // if a derivation is still running when we wipe the keys below it would // read garbage. quit()+wait() lets the in-flight slot finish (can't // interrupt a stack frame) and drops queued ones. if (m_deriveThread && m_deriveThread->isRunning()) { m_deriveThread->quit(); m_deriveThread->wait(); } m_pendingDecrypts.clear(); delete m_deriveWorker; // its event loop is gone, no deleteLater will come m_deriveWorker = nullptr; delete m_deriveThread; m_deriveThread = nullptr; cleanse(m_identitySk); for (auto it = m_passphraseKeyCache.begin(); it != m_passphraseKeyCache.end(); ++it) cleanse(*it); } QByteArray CryptoManager::randomBytes(int n) { QByteArray buf(n, 0); // randombytes_buf has no failure to report: libsodium aborts rather than // return short, so there is no path here that hands back a buffer of zeroes. randombytes_buf(buf.data(), size_t(n)); return buf; } // the private key lives in the encrypted store, never in QSettings. A session without a // store still gets a keypair so the app works, it just forgets it on exit. bool CryptoManager::initKeypairs() { if (!loadStoredKeys()) { if (!generateAndStoreKeys()) return false; } if (m_identitySk.size() != crypto_sign_SECRETKEYBYTES) return false; // the public half is recomputed from the secret rather than stored, so a // store entry that was tampered with cannot make us advertise a key we // cannot sign with. m_identityPubBytes.resize(crypto_sign_PUBLICKEYBYTES); if (crypto_sign_ed25519_sk_to_pk(reinterpret_cast(m_identityPubBytes.data()), reinterpret_cast(m_identitySk.constData())) != 0) { return false; } return true; } bool CryptoManager::migrateLegacyKeys(QString *outIdentityB64) { QString legacyId; Wiper wipeId(legacyId); { // toString() and not toByteArray(): the old build stored these with a // QByteArray overload, so the file says @ByteArray(...) - QSettings hands // either type back as the same base64 text. QSettings settings; legacyId = settings.value(legacyIdentityConfigKey(m_storageScope)).toString(); } if (legacyId.isEmpty()) return false; *outIdentityB64 = legacyId; // only drop the plaintext copy once the store has it, otherwise a // store that is merely unreachable today would cost the user their identity. if (!SecretStore::write(identityStoreKey(m_storageScope), legacyId)) { qCCritical(KOUTNET_LOG_CRYPTO, "your identity key is still stored in plain text in the config file " "because it could not be moved into the secret store (%s). Make sure the store is accessible and " "restart KOutNet.", qUtf8Printable(SecretStore::lastError())); reportPlaintextKeysLeft(SecretStore::lastError()); return true; } qCInfo(KOUTNET_LOG_CRYPTO, "copied the identity key into the secret store"); dropLegacyPlaintextKeys(); return true; } // not part of the migration branch: deleting the plaintext used to be a side // effect of the one run that filled the store, so a deletion that never reached // the disk was never retried, and the readable copy stayed forever. void CryptoManager::dropLegacyPlaintextKeys() { if (!stashSupersededPlaintextKeys()) return; QString detail; if (SecretStore::purgePlaintextConfigKeys({legacyIdentityConfigKey(m_storageScope), legacyDhConfigKey(m_storageScope)}, &detail)) return; qCCritical(KOUTNET_LOG_CRYPTO, "The secret store holds your identity key, but the plaintext copy could NOT be " "deleted from the config file: %s. Anyone who can read that file can " "impersonate you - delete the identity_priv_b64 and dh_priv_b64 entries " "by hand.", qUtf8Printable(detail)); reportPlaintextKeysLeft(detail); } // the config file can carry a different key pair than the store: a run where the // store was unreachable generated a throwaway identity, or an old config file was // restored. That plaintext still has to go, but not before the store has a copy. bool CryptoManager::stashSupersededPlaintextKeys() { QString legacyId; QString storeId; Wiper wipeId(legacyId); Wiper wipeStoreId(storeId); { QSettings settings; legacyId = settings.value(legacyIdentityConfigKey(m_storageScope)).toString(); } if (legacyId.isEmpty()) return true; // nothing in the file, so nothing to preserve or delete // A read that fails leaves the value empty, which compares as "not the pair // in the file" - the safe answer, since that path preserves before deleting. // The legacy DH key is dead weight now - nothing reads it - so it is purged // with the identity's plaintext instead of being stashed. SecretStore::read(identityStoreKey(m_storageScope), &storeId); if (legacyId == storeId) return true; // the store already holds exactly this key if (!SecretStore::write(supersededStoreKey(identityStoreKey(m_storageScope)), legacyId)) { qCCritical(KOUTNET_LOG_CRYPTO, "the config file holds an identity that the store does not, and it could " "not be copied into the store (%s) - leaving the plaintext alone rather " "than destroying the only copy of it.", qUtf8Printable(SecretStore::lastError())); reportPlaintextKeysLeft(SecretStore::lastError()); return false; } qCWarning(KOUTNET_LOG_CRYPTO, "the config file held a different identity than the one in use; it was copied " "into the store as %s before the plaintext was deleted.", qUtf8Printable(supersededStoreKey(identityStoreKey(m_storageScope)))); return true; } void CryptoManager::reportPlaintextKeysLeft(const QString &reason) { // Queued: this runs from the constructor, where nothing is connected yet. QML // connects while the engine loads, before the event loop, so a zero timer works. QTimer::singleShot(0, this, [this, reason]() { Q_EMIT plaintextKeysLeftInConfig(reason); }); } bool CryptoManager::loadStoredKeys() { QString idB64; Wiper wipeIdB64(idB64); if (!SecretStore::read(identityStoreKey(m_storageScope), &idB64) || idB64.isEmpty()) { if (!migrateLegacyKeys(&idB64)) return false; } else { // the store is the only copy used from here on, so anything left in the config // file is pure liability. Checked on every start because an earlier run may // have filled the store and then failed to rewrite the file. dropLegacyPlaintextKeys(); } QByteArray idRaw = QByteArray::fromBase64(idB64.toLatin1()); Wiper wipeIdRaw(idRaw); // the store holds the Ed25519 seed, 32 bytes - the same encoding the old // build wrote, so an existing identity and its fingerprint survive this // change. Guard against a truncated or corrupted entry expanding into a // garbage key. if (idRaw.size() != crypto_sign_SEEDBYTES) return false; m_identitySk.resize(crypto_sign_SECRETKEYBYTES); QByteArray idPub(crypto_sign_PUBLICKEYBYTES, 0); if (crypto_sign_seed_keypair(reinterpret_cast(idPub.data()), reinterpret_cast(m_identitySk.data()), reinterpret_cast(idRaw.constData())) != 0) { cleanse(m_identitySk); m_identitySk.clear(); return false; } return true; } bool CryptoManager::generateAndStoreKeys() { QByteArray idRaw = randomBytes(crypto_sign_SEEDBYTES); QString idB64; Wiper wipeIdRaw(idRaw); Wiper wipeIdB64(idB64); // the seed is what gets stored; the expanded 64-byte secret is derived from // it on every start, here and in loadStoredKeys() alike. m_identitySk.resize(crypto_sign_SECRETKEYBYTES); QByteArray idPub(crypto_sign_PUBLICKEYBYTES, 0); if (crypto_sign_seed_keypair(reinterpret_cast(idPub.data()), reinterpret_cast(m_identitySk.data()), reinterpret_cast(idRaw.constData())) != 0) { cleanse(m_identitySk); m_identitySk.clear(); return false; } idB64 = QString::fromLatin1(idRaw.toBase64()); // A store we cannot reach is not a reason to refuse to run, but it is a reason // to say so: this keypair lasts the session, so peers see a new fingerprint next. if (!SecretStore::write(identityStoreKey(m_storageScope), idB64)) { const QString err = SecretStore::lastError(); m_storeDegraded = true; qCCritical(KOUTNET_LOG_CRYPTO, "could not store the identity key in the secret store (%s). Running with a " "throwaway identity for this session - it is NOT written to disk in " "plain text.", qUtf8Printable(err)); // Queued like reportPlaintextKeysLeft: nothing is connected yet during // the constructor, but QML will be by the time the event loop runs. QTimer::singleShot(0, this, [this, err]() { Q_EMIT storeDegraded(err); }); return true; } // Reached when the legacy key was unusable (missing, or corrupt), so this // identity replaces it - and the unusable copy is still readable key material. dropLegacyPlaintextKeys(); return true; } // SHA-256 of the public key. Short enough for packets and logs, can't be // confused with an address. QString CryptoManager::identityIdFor(const QByteArray &idPubRaw) { if (idPubRaw.isEmpty()) return QString(); return QString::fromLatin1(QCryptographicHash::hash(idPubRaw, QCryptographicHash::Sha256).toHex()); } QString CryptoManager::ownIdentityId() const { return identityIdFor(m_identityPubBytes); } QByteArray CryptoManager::identitySeed() const { return m_identitySk.left(kKeyLen); } QString CryptoManager::fingerprint() const { return bytesToFingerprint(m_identityPubBytes); } // XChaCha20-Poly1305, not crypto_secretstream, datagrams are independent // frames, not a stream. The 192-bit nonce lets us draw at random per frame // with no collision risk. QByteArray CryptoManager::aeadSeal(const QByteArray &key, const QByteArray &plaintext, char aad) { if (key.size() != kKeyLen) return {}; const QByteArray nonce = randomBytes(kNonceLen); QByteArray sealed(plaintext.size() + kTagLen, 0); unsigned long long sealedLen = 0; if (crypto_aead_xchacha20poly1305_ietf_encrypt(reinterpret_cast(sealed.data()), &sealedLen, reinterpret_cast(plaintext.constData()), static_cast(plaintext.size()), reinterpret_cast(&aad), 1, nullptr, reinterpret_cast(nonce.constData()), reinterpret_cast(key.constData())) != 0) { return {}; } if (sealedLen != static_cast(plaintext.size() + kTagLen)) return {}; return nonce + sealed; } bool CryptoManager::aeadOpen(const QByteArray &key, const QByteArray &data, char aad, QByteArray *outPlain) { if (key.size() != kKeyLen || data.size() < kNonceLen + kTagLen) return false; const QByteArray nonce = data.left(kNonceLen); const QByteArray sealed = data.mid(kNonceLen); QByteArray plaintext(sealed.size() - kTagLen, 0); unsigned long long plainLen = 0; // one call, and its result is the tag check - there is no setup step here // that could be skipped and leave the tag unverified. if (crypto_aead_xchacha20poly1305_ietf_decrypt(reinterpret_cast(plaintext.data()), &plainLen, nullptr, reinterpret_cast(sealed.constData()), static_cast(sealed.size()), reinterpret_cast(&aad), 1, reinterpret_cast(nonce.constData()), reinterpret_cast(key.constData())) != 0) { return false; // tag mismatch - tampered, wrong key, or the wrong slot } *outPlain = plaintext.left(qsizetype(plainLen)); return true; } QByteArray CryptoManager::deriveKey(const QString &passphrase, const QByteArray &salt) const { // A hash of the pair, not the pair itself. The cache key used to be the passphrase // with the salt appended, which kept the user's group passphrase in plain text here // for the life of the process. The salt is fixed length, so this is unambiguous. const QByteArray cacheKey = cacheKeyFor(passphrase, salt); const auto cached = m_passphraseKeyCache.constFind(cacheKey); if (cached != m_passphraseKeyCache.constEnd()) return *cached; // the only libsodium call reachable without a keypair, so it is also the only // one that has to check for itself that the library came up. if (!sodiumReady() || salt.size() != kSaltLen) return {}; QByteArray pass = passphrase.toUtf8(); Wiper wipePass(pass); QByteArray key(kKeyLen, 0); // Argon2id, which unlike PBKDF2 costs an attacker memory as well as time. A // failure here is almost always the 64 MiB allocation being refused; an // all-zero key would be shared by every peer that hit it, so it is fatal. if (crypto_pwhash(reinterpret_cast(key.data()), kKeyLen, pass.constData(), static_cast(pass.size()), reinterpret_cast(salt.constData()), kPwhashOps, kPwhashMem, crypto_pwhash_ALG_ARGON2ID13) != 0) { cleanse(key); return {}; } // each derivation is 64 MiB and two passes, which is why it is cached at all - // but a long session cycling through many passphrases must not grow this forever. if (m_passphraseKeyCache.size() >= kMaxPassphraseCacheSize) { for (auto it = m_passphraseKeyCache.begin(); it != m_passphraseKeyCache.end(); ++it) cleanse(*it); m_passphraseKeyCache.clear(); } m_passphraseKeyCache[cacheKey] = key; return key; } bool CryptoManager::checkRate(const QString &sourceAddress, int maxPerSec) const { const double now = nowEpoch(); // Keyed on source address. Entries older than 1s are evicted. if (m_rateCounters.size() > kMaxRatePeers) { for (auto it = m_rateCounters.begin(); it != m_rateCounters.end();) { if (it.value().isEmpty() || now - it.value().constLast() >= 1.0) it = m_rateCounters.erase(it); else ++it; } } QVector &window = m_rateCounters[sourceAddress]; QVector kept; kept.reserve(window.size()); for (double t : std::as_const(window)) { if (now - t < 1.0) kept.append(t); } window = kept; if (window.size() >= maxPerSec) return false; window.append(now); return true; } // Wire format (base64 after the "KNC2:" tag): // type[1] + payload, with type also bound in as the AEAD associated data // 0x02 = XChaCha20-Poly1305 under an Argon2id passphrase key (payload = salt[16]+nonce[24]+ciphertext+tag) // No passphrase at all means the caller is relying on the TLS channel, and the // plaintext rides it verbatim - this method refuses to invent a key. QString CryptoManager::encrypt(const QString &plaintext, const QString &passphrase) const { if (passphrase.isEmpty()) return plaintext; // nothing to seal with; TLS is the channel's call const QByteArray data = plaintext.toUtf8(); // an empty return says "could not seal this", never "here it is in the // clear", so a broken salt or cipher cannot leak the message const QByteArray salt = randomBytes(kSaltLen); const QByteArray key = deriveKey(passphrase, salt); if (key.size() != kKeyLen) return QString(); const QByteArray sealed = aeadSeal(key, data, kAadPassphraseMessage); if (sealed.isEmpty()) return QString(); QByteArray wire; wire.append(kAadPassphraseMessage); wire.append(salt); wire.append(sealed); return wireMarker() + QString::fromLatin1(wire.toBase64()); } QString CryptoManager::decrypt(const QString &ciphertext, const QString &passphrase) const { // whether this text was supposed to arrive sealed is decided by the keys // we hold, not by anything the sender put in the packet. otherwise // stripping the tag is all it takes to downgrade a session to cleartext. const bool expectSealed = !passphrase.isEmpty(); const QString marker = wireMarker(); if (!ciphertext.startsWith(marker)) { if (expectSealed) return i18nc("@info shown in place of a message body", "[decrypt error: cleartext on a keyed channel]"); return ciphertext; // no key on this channel anyway - pass through } const QByteArray wire = QByteArray::fromBase64(ciphertext.mid(marker.size()).toLatin1()); if (wire.isEmpty()) return i18nc("@info shown in place of a message body", "[decrypt error: empty packet]"); const char type = wire.at(0); const QByteArray payload = wire.mid(1); QByteArray plain; bool ok = false; if (type == kAadPassphraseMessage && payload.size() > kSaltLen && !passphrase.isEmpty()) { const QByteArray salt = payload.left(kSaltLen); const QByteArray key = deriveKey(passphrase, salt); if (key.size() == kKeyLen) ok = aeadOpen(key, payload.mid(kSaltLen), type, &plain); } if (!ok) return i18nc("@info shown in place of a message body", "[decrypt error: invalid key or tampered packet]"); return QString::fromUtf8(plain); } QByteArray CryptoManager::sealAtRest(const QByteArray &key, const QByteArray &payload) { // the key is HistoryManager's, brought in from SecretStore; a wrong-size // key is refused here rather than truncated into a usable-looking one. return aeadSeal(key, payload, kAadHistoryFile); } bool CryptoManager::openAtRest(const QByteArray &key, const QByteArray &data, QByteArray *outPayload) { return aeadOpen(key, data, kAadHistoryFile, outPayload); } QByteArray CryptoManager::generateAtRestKey() { return randomBytes(kKeyLen); } QByteArray CryptoManager::cacheKeyFor(const QString &passphrase, const QByteArray &salt) { QByteArray pass = passphrase.toUtf8(); Wiper wipePass(pass); QCryptographicHash tag(QCryptographicHash::Sha256); tag.addData(salt); tag.addData(pass); return tag.result(); } void CryptoManager::decryptAsync(const QString &ciphertext, const QString &passphrase, const std::function &done) { // the queue, the caches and the in-flight flag are single-threaded by // design; the receive path on the GUI thread is the only caller. Called // from anywhere else the queue races - say so loudly in debug builds. Q_ASSERT_X(QThread::currentThread() == thread(), "CryptoManager::decryptAsync", "the async decrypt queue is confined to the CryptoManager's own thread"); // the classification is exactly decrypt()'s, minus the derivation: cache // hits resolve on the spot, and only a passphrase message with an unseen // salt has to wait for the worker thread. The strings have to match // decrypt()'s, or a message would show a different error depending on // whether a slow message queued in front of it. const bool expectSealed = !passphrase.isEmpty(); const QString marker = wireMarker(); const QString errorString = i18nc("@info shown in place of a message body", "[decrypt error: invalid key or tampered packet]"); QString fastResult; // set when the message needs no derivation bool needsDerivation = false; QByteArray salt; QByteArray rest; if (!ciphertext.startsWith(marker)) { fastResult = expectSealed ? i18nc("@info shown in place of a message body", "[decrypt error: cleartext on a keyed channel]") : ciphertext; } else { const QByteArray wire = QByteArray::fromBase64(ciphertext.mid(marker.size()).toLatin1()); if (wire.isEmpty()) { fastResult = i18nc("@info shown in place of a message body", "[decrypt error: empty packet]"); } else { const char type = wire.at(0); const QByteArray payload = wire.mid(1); if (type == kAadPassphraseMessage && payload.size() > kSaltLen && !passphrase.isEmpty()) { salt = payload.left(kSaltLen); rest = payload.mid(kSaltLen); const auto cached = m_passphraseKeyCache.constFind(cacheKeyFor(passphrase, salt)); if (cached != m_passphraseKeyCache.constEnd()) { QByteArray plain; if (!aeadOpen(*cached, rest, type, &plain)) fastResult = errorString; else fastResult = QString::fromUtf8(plain); } else { needsDerivation = true; } } else { fastResult = errorString; } } } if (!needsDerivation) { // A fast message outruns nothing when the line is empty; otherwise it // takes the back of the queue so it cannot overtake a passphrase // message that is already in line in front of it. if (m_pendingDecrypts.isEmpty() && !m_derivationInFlight) { done(fastResult, true); return; } // Queue full and this message only needs a slot to stay in order, not a // derivation: under a flood it costs nothing to drop, so drop it rather // than grow the queue past the cap. if (m_pendingDecrypts.size() >= kMaxPendingDecrypts) { done({}, false); return; } PendingDecrypt entry; entry.result = fastResult; entry.done = done; m_pendingDecrypts.append(entry); return; } // Queue is full or body is too large, drop it. delivered=false so it // doesn't show up as a decrypt error row. if (rest.size() > kMaxAsyncPayloadBytes || m_pendingDecrypts.size() >= kMaxPendingDecrypts) { done({}, false); return; } PendingDecrypt entry; entry.needsDerivation = true; entry.salt = salt; entry.payload = rest; entry.passphrase = passphrase; entry.done = done; m_pendingDecrypts.append(entry); if (!m_derivationInFlight) startDerivation(); } void CryptoManager::startDerivation() { if (m_pendingDecrypts.isEmpty() || m_derivationInFlight) return; const PendingDecrypt &head = m_pendingDecrypts.first(); if (!head.needsDerivation) return; // the drain loop resolves fast entries without the worker if (!m_deriveThread) { m_deriveThread = new QThread(this); m_deriveWorker = new DeriveWorker; m_deriveWorker->moveToThread(m_deriveThread); connect(m_deriveWorker, &DeriveWorker::derived, this, &CryptoManager::onDerived); m_deriveThread->start(); } m_derivationInFlight = true; QMetaObject::invokeMethod(m_deriveWorker, "derive", Qt::QueuedConnection, Q_ARG(QString, head.passphrase), Q_ARG(QByteArray, head.salt)); } void CryptoManager::onDerived(const QByteArray &salt, std::shared_ptr key, bool ok) { m_derivationInFlight = false; if (m_pendingDecrypts.isEmpty()) return; PendingDecrypt entry = m_pendingDecrypts.takeFirst(); QByteArray plain; bool opened = false; if (ok && entry.needsDerivation && entry.salt == salt) { // Cache the derived key, same salt won't need a second derivation. const QByteArray cacheKey = cacheKeyFor(entry.passphrase, salt); m_passphraseKeyCache[cacheKey] = *key; opened = aeadOpen(*key, entry.payload, kAadPassphraseMessage, &plain); } const QString result = (opened && ok) ? QString::fromUtf8(plain) : i18nc("@info shown in place of a message body", "[decrypt error: invalid key or tampered packet]"); entry.done(result, true); // Drain fast entries (cache hits) in queue order. // Don't let a cached message jump ahead of a passphrase message. while (!m_pendingDecrypts.isEmpty() && !m_pendingDecrypts.first().needsDerivation) { PendingDecrypt fast = m_pendingDecrypts.takeFirst(); fast.done(fast.result, true); } if (!m_pendingDecrypts.isEmpty()) startDerivation(); } } // namespace koutnet #include "CryptoManager.moc"