Commit 826e00c6 authored by jan.koester's avatar jan.koester
Browse files

tls perf

parent cf549ff7
Loading
Loading
Loading
Loading
+212 −3
Changes for src/crypto/tls.cpp: 212 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -483,6 +483,23 @@ namespace netplus {
                if (chosenSuite == 0)
                    throwSSL(NetException::Error, "No supported cipher suite");

                // --- TLS 1.2 Session Resumption Check ---
                // If client sent a non-empty session_id and we have a cache,
                // look it up.  On hit the expensive RSA decrypt is skipped.
                if (session_cache && !client_session_id.empty()) {
                    TlsSessionCacheEntry cached;
                    if (session_cache->lookup(client_session_id, cached)) {
                        // Verify cipher suite matches what client still offers
                        if (hasSuite(cached.cipher_suite)) {
                            chosenSuite = cached.cipher_suite;
                            masterSecret = cached.master_secret;
                            is_resumption = true;
                            hs_state = HsState::SEND_ABBREVIATED_FLIGHT;
                            continue;
                        }
                    }
                }

                hs_state = HsState::SEND_SERVER_FLIGHT;

                if (rx_handshake_buf.size() < 4) {
@@ -700,6 +717,102 @@ namespace netplus {
                hs_state = HsState::CLI_WAIT_CERT;
                break;
            }
            // ============================================================
            // SEND_ABBREVIATED_FLIGHT (TLS 1.2 session resumption)
            // Server sends: ServerHello(echoed session_id) + CCS + Finished
            // Skips Certificate / ServerHelloDone / waiting for CKE.
            // ============================================================
            case HsState::SEND_ABBREVIATED_FLIGHT: {
                if (!serverFlightQueued) {
                    // --- Build ServerHello with echoed session_id ---
                    {
                        std::vector<uint8_t> body;
                        body.reserve(128);
                        body.push_back(0x03); body.push_back(0x03); // TLS 1.2
                        serverRandom.resize(32);
                        fillRandomBytes(serverRandom.data(), 32);
                        body.insert(body.end(), serverRandom.begin(), serverRandom.end());
                        // Echo client session_id so client knows resumption succeeded
                        body.push_back(static_cast<uint8_t>(client_session_id.size()));
                        body.insert(body.end(), client_session_id.begin(), client_session_id.end());
                        body.push_back((chosenSuite >> 8) & 0xFF);
                        body.push_back((chosenSuite >> 0) & 0xFF);
                        body.push_back(0x00); // null compression
                        // renegotiation_info
                        if (secure_reneg) {
                            std::vector<uint8_t> exts;
                            exts.push_back(0xFF); exts.push_back(0x01);
                            exts.push_back(0x00); exts.push_back(0x01);
                            exts.push_back(0x00);
                            body.push_back((exts.size() >> 8) & 0xFF);
                            body.push_back((exts.size() >> 0) & 0xFF);
                            body.insert(body.end(), exts.begin(), exts.end());
                        } else {
                            body.push_back(0x00); body.push_back(0x00);
                        }
                        sendHandshake(0x02, body);
                    }

                    // --- Derive keys from cached masterSecret + new randoms ---
                    {
                        std::vector<uint8_t> kbSeed = serverRandom;
                        kbSeed.insert(kbSeed.end(), clientRandom.begin(), clientRandom.end());

                        size_t keyLen = (chosenSuite == 0x0035) ? 32 : 16;
                        size_t kbLen = 20 + 20 + keyLen + keyLen; // 2 MAC keys + 2 write keys
                        std::vector<uint8_t> keyBlock = prf(masterSecret, "key expansion", kbSeed, kbLen);

                        size_t k = 0;
                        client_mac_key.assign(keyBlock.begin() + k, keyBlock.begin() + k + 20); k += 20;
                        mac_key.assign(keyBlock.begin() + k, keyBlock.begin() + k + 20); k += 20;
                        std::vector<uint8_t> clientKey(keyBlock.begin() + k, keyBlock.begin() + k + keyLen); k += keyLen;
                        std::vector<uint8_t> serverKey(keyBlock.begin() + k, keyBlock.begin() + k + keyLen);

                        if (keyLen == 32) {
                            aes_recv = std::make_unique<aes256>(clientKey);
                            aes      = std::make_unique<aes256>(serverKey);
                        } else {
                            aes_recv = std::make_unique<aes128>(clientKey);
                            aes      = std::make_unique<aes128>(serverKey);
                        }
                    }

                    // --- Queue CCS + server Finished ---
                    {
                        static const uint8_t sccs[] = { 0x14, 0x03, 0x03, 0x00, 0x01, 0x01 };
                        queueRaw(sccs, sizeof(sccs));
                        send_seq = 0;

                        std::vector<uint8_t> th = sha256_hash(handshake_transcript);
                        std::vector<uint8_t> verifyServer = prf(masterSecret, "server finished", th, 12);

                        std::vector<uint8_t> sFin;
                        sFin.reserve(16);
                        sFin.push_back(0x14);
                        sFin.push_back(0x00); sFin.push_back(0x00); sFin.push_back(0x0c);
                        sFin.insert(sFin.end(), verifyServer.begin(), verifyServer.end());
                        handshake_transcript.insert(handshake_transcript.end(), sFin.begin(), sFin.end());
                        sendTLS12Record(0x16, sFin);
                    }

                    serverFlightQueued = true;
                }

                // Flush
                try {
                    flush_out();
                } catch (NetException& e) {
                    if (e.getErrorType() == NetException::Note) return;
                    throw;
                }

                if (!hasPendingWrite()) {
                    recv_seq = 0; // reset recv seq for encrypted records from client
                    hs_state = HsState::WAIT_CCS;
                }
                return;
            }

            // ============================================================
            // SEND_SERVER_FLIGHT
            // ============================================================
@@ -881,6 +994,12 @@ namespace netplus {
                if (!hasPendingWrite()) {
                    handshakeDone = true;
                    hs_state = HsState::DONE;

                    // --- Cache the session for future resumption ---
                    if (session_cache && !is_tls13 && !client_session_id.empty()
                        && !masterSecret.empty()) {
                        session_cache->store(client_session_id, masterSecret, chosenSuite);
                    }
                    return;
                }
                return;
@@ -1384,6 +1503,8 @@ namespace netplus {
                        e[NetException::Error] << "ServerHello SID overflow";
                        throw e;
                    }
                    // Save server's echoed session_id for resumption check
                    std::vector<uint8_t> server_sid(p + off, p + off + sid_len);
                    off += sid_len;

                    // cipher_suite (2)
@@ -1555,6 +1676,50 @@ namespace netplus {
                    }

                    // else: TLS 1.2 flow continues

                    // --- Client-side session resumption check ---
                    // If we attempted resumption and server echoed our session_id,
                    // derive keys from cached master_secret and skip cert/CKE.
                    if (attempt_resumption && !resumption_session_id.empty()
                        && server_sid == resumption_session_id
                        && !resumption_master_secret.empty()) {
                        masterSecret = resumption_master_secret;
                        is_resumption = true;

                        // Add ServerHello to transcript for Finished verification
                        handshake_transcript.insert(handshake_transcript.end(),
                                                    sh.begin(), sh.end());

                        // Derive key_block from cached masterSecret + new randoms
                        std::vector<uint8_t> kbSeed = serverRandom;
                        kbSeed.insert(kbSeed.end(), clientRandom.begin(), clientRandom.end());

                        size_t keyLen = (chosenSuite == 0x0035) ? 32 : 16;
                        size_t kbLen = 20 + 20 + keyLen + keyLen;
                        std::vector<uint8_t> keyBlock = prf(masterSecret, "key expansion", kbSeed, kbLen);

                        size_t k = 0;
                        client_mac_key.assign(keyBlock.begin() + k, keyBlock.begin() + k + 20); k += 20;
                        mac_key.assign(keyBlock.begin() + k, keyBlock.begin() + k + 20); k += 20;
                        std::vector<uint8_t> clientKey(keyBlock.begin() + k, keyBlock.begin() + k + keyLen); k += keyLen;
                        std::vector<uint8_t> serverKey(keyBlock.begin() + k, keyBlock.begin() + k + keyLen);

                        if (keyLen == 32) {
                            aes      = std::make_unique<aes256>(clientKey);
                            aes_recv = std::make_unique<aes256>(serverKey);
                        } else {
                            aes      = std::make_unique<aes128>(clientKey);
                            aes_recv = std::make_unique<aes128>(serverKey);
                        }

                        // Wait for server CCS + Finished (abbreviated flow)
                        hs_state = HsState::CLI_WAIT_SCCS;
                        break;
                    }

                    // Save server's session_id for future resumption
                    client_session_id = server_sid;

                    hs_state = HsState::CLI_WAIT_CERT;
                    break;
                }
@@ -2079,8 +2244,41 @@ namespace netplus {
                    handshake_transcript.insert(handshake_transcript.end(),
                                                finPT.begin(), finPT.begin() + 4 + 12);

                    // In abbreviated (resumption) handshake the client must
                    // still send CCS + Finished after verifying the server's.
                    if (is_resumption && !cli_ccs_fin_sent) {
                        static const uint8_t ccs[6] = {0x14,0x03,0x03,0x00,0x01,0x01};
                        queueRaw(ccs, sizeof(ccs));
                        send_seq = 0;

                        std::vector<uint8_t> cth = sha256_hash(handshake_transcript);
                        std::vector<uint8_t> verifyClient = prf(masterSecret, "client finished", cth, 12);

                        std::vector<uint8_t> finMsg;
                        finMsg.reserve(16);
                        finMsg.push_back(0x14);
                        finMsg.push_back(0x00); finMsg.push_back(0x00); finMsg.push_back(0x0c);
                        finMsg.insert(finMsg.end(), verifyClient.begin(), verifyClient.end());
                        handshake_transcript.insert(handshake_transcript.end(),
                                                    finMsg.begin(), finMsg.end());
                        sendTLS12Record(0x16, finMsg);
                        cli_ccs_fin_sent = true;

                        // Flush before completing
                        try { flush_out(); } catch (NetException& e) {
                            if (e.getErrorType() == NetException::Note) return;
                            throw;
                        }
                    }

                    handshakeDone = true;
                    hs_state = HsState::DONE;

                    // --- Client-side: cache session for future resumption ---
                    if (session_cache && !is_tls13 && !client_session_id.empty()
                        && !masterSecret.empty()) {
                        session_cache->store(client_session_id, masterSecret, chosenSuite);
                    }
                    return;
                }

@@ -2661,6 +2859,10 @@ namespace netplus {
        tls13_encflight_queued = false;
        ccs_received = false;

        // Reset session resumption flags (keep session_cache pointer and
        // resumption_* data — they are set externally for the next handshake)
        is_resumption = false;

        // -------------------------
        // generic
        // -------------------------
@@ -3350,8 +3552,11 @@ namespace netplus {
        fillRandomBytes(serverRandom.data(), 32);
        body.insert(body.end(), serverRandom.begin(), serverRandom.end());

        // 3) SessionID (we send none)
        body.push_back(0x00);
        // 3) SessionID — echo back for resumption support
        body.push_back(static_cast<uint8_t>(client_session_id.size()));
        if (!client_session_id.empty()) {
            body.insert(body.end(), client_session_id.begin(), client_session_id.end());
        }

        // 4) CipherSuite
        body.push_back((chosenSuiteArg >> 8) & 0xFF);
@@ -3829,9 +4034,13 @@ namespace netplus {
        fillRandomBytes(clientRandom.data(), 32);
        ch.insert(ch.end(), clientRandom.begin(), clientRandom.end());

        // Session ID (32 random bytes for middlebox compatibility)
        // Session ID — use saved session_id for resumption, else random for middlebox compat
        if (attempt_resumption && !resumption_session_id.empty()) {
            client_session_id = resumption_session_id;
        } else {
            client_session_id.resize(32);
            fillRandomBytes(client_session_id.data(), 32);
        }
        ch.push_back(uint8_t(client_session_id.size()));
        ch.insert(ch.end(), client_session_id.begin(), client_session_id.end());

+99 −0
Changes for src/crypto/tls.h: 99 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@
#include <deque>
#include <atomic>
#include <functional>
#include <chrono>

#include <mutex>
#include "config.h"
@@ -20,6 +21,90 @@ namespace netplus {
    class buffer;
    class socket;

    // =====================================================================
    // TLS Session Cache — enables TLS 1.2 abbreviated handshakes.
    // Shared across connections; protected by its own mutex.
    // =====================================================================
    struct TlsSessionCacheEntry {
        std::vector<uint8_t> session_id;         // session ID for resumption
        std::vector<uint8_t> master_secret;      // 48 bytes
        uint16_t             cipher_suite;       // e.g. 0x002F (AES-128-CBC-SHA)
        std::chrono::steady_clock::time_point created;
    };

    class TlsSessionCache {
    public:
        // Look up a session by session_id; returns true if found and not expired.
        bool lookup(const std::vector<uint8_t>& session_id,
                    TlsSessionCacheEntry& out) const {
            std::lock_guard<std::mutex> lk(mtx_);
            auto it = map_.find(session_id);
            if (it == map_.end()) return false;
            auto age = std::chrono::steady_clock::now() - it->second.created;
            if (age > max_age_) { return false; }
            out = it->second;
            return true;
        }

        // Store a session keyed by session_id.
        void store(const std::vector<uint8_t>& session_id,
                   const std::vector<uint8_t>& master_secret,
                   uint16_t cipher_suite) {
            std::lock_guard<std::mutex> lk(mtx_);
            if (map_.size() >= max_entries_ && map_.find(session_id) == map_.end()) {
                evict_oldest();
            }
            map_[session_id] = { session_id, master_secret, cipher_suite,
                                 std::chrono::steady_clock::now() };
        }

        // Look up by host:port key (for client-side reconnection).
        bool lookup_by_host(const std::string& host_key,
                            TlsSessionCacheEntry& out) const {
            std::lock_guard<std::mutex> lk(mtx_);
            auto it = host_map_.find(host_key);
            if (it == host_map_.end()) return false;
            auto age = std::chrono::steady_clock::now() - it->second.created;
            if (age > max_age_) { return false; }
            out = it->second;
            return true;
        }

        // Store by host:port key (client-side).
        void store_by_host(const std::string& host_key,
                           const std::vector<uint8_t>& session_id,
                           const std::vector<uint8_t>& master_secret,
                           uint16_t cipher_suite) {
            std::lock_guard<std::mutex> lk(mtx_);
            host_map_[host_key] = { session_id, master_secret, cipher_suite,
                                    std::chrono::steady_clock::now() };
            // Also store by session_id for server-side lookup
            if (map_.size() >= max_entries_ && map_.find(session_id) == map_.end()) {
                evict_oldest();
            }
            map_[session_id] = host_map_[host_key];
        }

        void setMaxAge(std::chrono::seconds s) { max_age_ = s; }
        void setMaxEntries(size_t n) { max_entries_ = n; }

    private:
        void evict_oldest() {
            auto oldest = map_.begin();
            for (auto it = map_.begin(); it != map_.end(); ++it) {
                if (it->second.created < oldest->second.created)
                    oldest = it;
            }
            if (oldest != map_.end()) map_.erase(oldest);
        }

        mutable std::mutex mtx_;
        std::map<std::vector<uint8_t>, TlsSessionCacheEntry> map_;       // by session_id
        std::map<std::string, TlsSessionCacheEntry>          host_map_;  // by host:port
        size_t max_entries_ = 4096;
        std::chrono::seconds max_age_{7200};  // 2 hours default
    };

    class tls {
    public:
        // --- Cryptographic Helper Methods (Static) ---
@@ -38,6 +123,7 @@ namespace netplus {
            TLS13_SEND_ENCRYPTED_FLIGHT,
            TLS13_WAIT_CLIENT_FINISHED,
            SEND_SERVER_FLIGHT,
            SEND_ABBREVIATED_FLIGHT,   // TLS 1.2 session resumption (server)
            WAIT_CKE,
            WAIT_CCS,
            WAIT_FIN,
@@ -294,6 +380,19 @@ namespace netplus {
        bool serverFinishedQueued = false;
        bool serverFlightQueued = false;

        // --- TLS 1.2 Session Resumption ---
        // Shared session cache (set by server or client code)
        TlsSessionCache* session_cache = nullptr;

        // Server-side: true when abbreviated handshake is in progress
        bool is_resumption = false;

        // Client-side: set these before connect to attempt resumption
        bool attempt_resumption = false;
        std::vector<uint8_t> resumption_session_id;
        std::vector<uint8_t> resumption_master_secret;
        uint16_t resumption_cipher = 0;

        // --- TLS Version and Cipher Suite ---
        bool is_tls13 = false;
        uint16_t neg_version = 0x0303;        // 0x0303 = TLS 1.2, 0x0304 = TLS 1.3
+2 −0
Changes for src/ssl.cpp: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -88,6 +88,8 @@ void ssl::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    // Propagate ALPN select callback and framing callback to child socket
    cssock->_tls.alpn_select_cb = _tls.alpn_select_cb;
    cssock->_framing_cb = _framing_cb;
    // Propagate TLS session cache for abbreviated handshake support
    cssock->_tls.session_cache = _tls.session_cache;
    cssock->_tls.setSocket(cssock.get());
    cssock->_Type = sockettype::SSL;