// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "TlsChannel.h" #include #include #include #include #include #include #include namespace koutnet { namespace { constexpr int kMaxFrame = 16 * 1024 * 1024; // The default name of a peer, the CN of its self-signed certificate. The app // signs identities up as base32-ish ids, so a CN with whitespace or control // characters is not a peer worth keeping: refuse it before it claims a name. QString peerIdOf(const QSslCertificate &cert) { const QString cn = cert.subjectInfo(QSslCertificate::CommonName).value(0, QString()); for (const QChar &c : cn) { if (!c.isPrint() || c.isSpace()) { return {}; } } return cn; } QByteArray lengthPrefixed(const QByteArray &payload) { const quint32 len = quint32(payload.size()); QByteArray out(4, '\0'); out[0] = char((len >> 24) & 0xFF); out[1] = char((len >> 16) & 0xFF); out[2] = char((len >> 8) & 0xFF); out[3] = char(len & 0xFF); out.append(payload); return out; } } // namespace // Pins are stored as a peer id, a tab and a 64-hex-digit SPKI fingerprint per line. // One store per channel: the file is state, not something to re-read per handshake. class TlsChannel::TofuPins { public: explicit TofuPins(const QString &file) : m_file(file) { load(); } // true when the fingerprint is (now) the pinned one. A peer whose key // changed identity is refused and outExpected gets the old pin. bool admit(const QString &peerId, const QByteArray &fingerprint, QByteArray *outExpected) { const auto it = m_pins.constFind(peerId); if (it != m_pins.cend()) { if (outExpected) { *outExpected = it.value(); } return it.value() == fingerprint; } m_pins.insert(peerId, fingerprint); save(); return true; } // the fingerprint pinned to this identity, empty when it was never seen. QByteArray fingerprintFor(const QString &peerId) const { return m_pins.value(peerId); } // Drop a pinned identity so the next presentation is treated as a first // contact again. Returns true when a pin was removed. bool forget(const QString &peerId) { if (!m_pins.contains(peerId)) return false; m_pins.remove(peerId); save(); return true; } private: void load() { QFile file(m_file); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } while (!file.atEnd()) { const QByteArray line = file.readLine().trimmed(); if (line.isEmpty()) { continue; } const int tab = line.indexOf('\t'); if (tab <= 0) { continue; } const QByteArray fp = QByteArray::fromHex(line.mid(tab + 1)); if (fp.size() != 32) { continue; } m_pins.insert(QString::fromUtf8(line.left(tab)), fp); } } void save() const { QDir().mkpath(QFileInfo(m_file).absolutePath()); QSaveFile file(m_file); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { return; } for (auto it = m_pins.cbegin(); it != m_pins.cend(); ++it) { file.write(it.key().toUtf8()); file.write("\t"); file.write(it.value().toHex()); file.write("\n"); } file.commit(); } QString m_file; QHash m_pins; }; TlsChannel::TlsChannel(const IdentityCertificate &identity, QObject *parent) : QTcpServer(parent) , m_identity(identity) , m_pins(std::make_unique(pinFile())) { if (!m_identity.isValid()) { qWarning("TlsChannel: identity certificate is not valid, TLS is disabled"); return; } m_cfg.setProtocol(QSsl::TlsV1_3OrLater); // request the peer's certificate without validating it - trust is decided // on the pinned fingerprint, not on a CA chain (VerifyNone would not even // ask the peer for its certificate, which is what we need to see). m_cfg.setPeerVerifyMode(QSslSocket::QueryPeer); m_cfg.setLocalCertificate(m_identity.cert); m_cfg.setPrivateKey(m_identity.key); } TlsChannel::~TlsChannel() = default; bool TlsChannel::listen(quint16 port) { if (!m_identity.isValid() || !QTcpServer::listen(QHostAddress::Any, port)) { return false; } m_listenPort = serverPort(); return true; } bool TlsChannel::connectTo(const QString &host, quint16 port) { if (!m_identity.isValid()) { return false; } QSslSocket *socket = new QSslSocket(this); m_clients.append(socket); wireSocket(socket); socket->setSslConfiguration(m_cfg); // the same clock the accepted side runs: an outbound dial that never reaches // "encrypted" must not hold its address in the owner's dialing set forever. startHandshakeClock(socket); socket->connectToHostEncrypted(host, port); return true; } void TlsChannel::stop() { const auto peers = m_peers; for (auto it = peers.cbegin(); it != peers.cend(); ++it) { it.value().socket->disconnectFromHost(); } m_peers.clear(); m_socketIds.clear(); for (QSslSocket *socket : std::as_const(m_clients)) { socket->disconnectFromHost(); } m_clients.clear(); // every handshaking socket is either in m_clients or was refused, but the // timers have to go before the sockets do const auto handshaking = m_handshaking; for (auto it = handshaking.cbegin(); it != handshaking.cend(); ++it) { it.value()->stop(); it.value()->deleteLater(); } m_handshaking.clear(); close(); } void TlsChannel::incomingConnection(qintptr handle) { // A connection that never gets past the handshake is a descriptor held for // nothing, so the table of them is capped: past the limit this one is closed // where it stands. Refusing is the point - accepting it anyway is what the // limit exists to avoid. if (m_handshaking.size() >= kMaxHandshakingSockets) { qWarning("TlsChannel: too many sockets waiting on a handshake, refusing"); // adopted only so the descriptor has an owner to abort it; a raw handle // has no portable close of its own QSslSocket *socket = new QSslSocket(this); if (socket->setSocketDescriptor(handle)) { socket->abort(); } else { delete socket; } return; } // QTcpServer hands plain QTcpSockets out of nextPendingConnection(); // building the QSslSocket here is the one correct way to serve TLS. QSslSocket *socket = new QSslSocket(this); if (!socket->setSocketDescriptor(handle)) { delete socket; return; } wireSocket(socket); socket->setSslConfiguration(m_cfg); socket->startServerEncryption(); startHandshakeClock(socket); } void TlsChannel::startHandshakeClock(QSslSocket *socket) { auto *timer = new QTimer(this); timer->setSingleShot(true); timer->setInterval(kHandshakeTimeoutMs); // dropSocket() rather than abort(): a peer that opened the socket and went // quiet never reads the close_notify, so the descriptor would sit in the // kernel for longer than the timer that was supposed to free it. It also // retires the socket from every table (clients, ids, handshake clock), which // a bare abort() leaves behind until the event loop reaps the pointer. connect(timer, &QTimer::timeout, this, [this, socket]() { qWarning("TlsChannel: handshake did not finish in time, dropping the socket"); dropSocket(socket, false); }); m_handshaking.insert(socket, timer); timer->start(); } void TlsChannel::cancelHandshakeClock(QSslSocket *socket) { QTimer *timer = m_handshaking.take(socket); if (timer) { timer->stop(); timer->deleteLater(); } } void TlsChannel::wireSocket(QSslSocket *socket) { connect(socket, &QSslSocket::encrypted, this, [socket, this]() { onEncrypted(socket); }); connect(socket, &QSslSocket::readyRead, this, [socket, this]() { onPeerData(socket); }); connect(socket, &QSslSocket::disconnected, this, [socket, this]() { onPeerClosed(socket); }); connect(socket, &QSslSocket::errorOccurred, this, [socket, this]() { onError(socket); }); } void TlsChannel::onEncrypted(QSslSocket *socket) { if (m_socketIds.contains(socket)) { return; } // past this point the socket is either adopted or aborted, so the handshake // clock has nothing left to guard cancelHandshakeClock(socket); const QSslCertificate peerCert = socket->peerCertificate(); if (peerCert.isNull()) { qWarning("TlsChannel: peer presented no certificate"); socket->abort(); return; } const QString peerId = peerIdOf(peerCert); if (peerId.isEmpty()) { qWarning("TlsChannel: peer certificate has no usable identity"); socket->abort(); return; } const QByteArray fingerprint = identityFingerprint(peerCert); QByteArray expectedPin; if (!m_pins->admit(peerId, fingerprint, &expectedPin)) { Q_EMIT peerRejected(peerId, socket->peerAddress().toString(), expectedPin, fingerprint); socket->abort(); return; } adopt(peerId, socket); Q_EMIT peerAuthenticated(peerId, socket->peerAddress().toString()); } void TlsChannel::adopt(const QString &peerId, QSslSocket *socket) { // newest seat wins; an older wire for the same id retires silently so // reads never interleave two connections under one identity. const auto old = m_peers.constFind(peerId); if (old != m_peers.cend() && old->socket != socket) { dropSocket(old->socket, false); } m_clients.removeAll(socket); m_socketIds[socket] = peerId; auto &link = m_peers[peerId]; link.socket = socket; link.address = socket->peerAddress().toString(); link.rx.clear(); } void TlsChannel::dropSocket(QSslSocket *socket, bool notify) { cancelHandshakeClock(socket); const QString peerId = m_socketIds.take(socket); if (notify && !peerId.isEmpty()) { Q_EMIT peerDisconnected(peerId); } m_peers.remove(peerId); m_clients.removeAll(socket); socket->disconnectFromHost(); socket->deleteLater(); } void TlsChannel::onPeerData(QSslSocket *socket) { const QString peerId = m_socketIds.value(socket); if (peerId.isEmpty()) { return; } auto &link = m_peers[peerId]; if (link.socket != socket) { return; // a stale wire for a peer that reconnected } link.rx += socket->readAll(); // frames are 4-byte big-endian length then payload; one read can carry // several frames and a frame can straddle several reads. while (link.rx.size() >= 4) { const quint32 len = (quint32(quint8(link.rx.at(0))) << 24) | (quint32(quint8(link.rx.at(1))) << 16) | (quint32(quint8(link.rx.at(2))) << 8) | quint32(quint8(link.rx.at(3))); if (len > kMaxFrame) { qWarning("TlsChannel: peer sent an oversized frame, dropping the connection"); dropSocket(socket, true); return; } if (link.rx.size() < 4 + int(len)) { break; } const QByteArray frame = link.rx.mid(4, int(len)); link.rx.remove(0, 4 + int(len)); Q_EMIT frameReceived(peerId, frame); } } void TlsChannel::onPeerClosed(QSslSocket *socket) { dropSocket(socket, true); } void TlsChannel::onError(QSslSocket *socket) { if (m_socketIds.contains(socket)) { return; // an authenticated peer that dies lands in onPeerClosed } if (m_clients.contains(socket)) { const QString host = socket->peerName().isEmpty() ? socket->peerAddress().toString() : socket->peerName(); Q_EMIT connectionFailed(host, quint16(socket->peerPort())); } m_clients.removeAll(socket); // the timer holds the socket pointer, so it cannot outlive it cancelHandshakeClock(socket); socket->deleteLater(); // a server-side visitor that fails the handshake just vanishes here. } void TlsChannel::sendPeer(const QString &peerId, const QByteArray &frame) { const auto it = m_peers.constFind(peerId); if (it == m_peers.cend() || !it->socket) { return; } it->socket->write(lengthPrefixed(frame)); } void TlsChannel::dropPeer(const QString &peerId) { const auto it = m_peers.constFind(peerId); if (it != m_peers.cend() && it->socket) { dropSocket(it->socket, true); } } bool TlsChannel::hasPeer(const QString &peerId) const { return m_peers.contains(peerId); } QString TlsChannel::pinFile() const { return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/tofu-pins"); } QString TlsChannel::pinnedFingerprint(const QString &peerId) const { const QByteArray fp = m_pins->fingerprintFor(peerId); return fp.isEmpty() ? QString() : QString::fromLatin1(fp.toHex()); } bool TlsChannel::forgetPin(const QString &peerId) { if (hasPeer(peerId)) dropPeer(peerId); return m_pins->forget(peerId); } } // namespace koutnet