From cfd5fcba7efbfe116e2c08848075240ec3a92718 Mon Sep 17 00:00:00 2001 From: EKR Date: Sat, 30 Jun 2018 16:45:09 -0700 Subject: [PATCH] Bug 1494901 - Implement ESNI. r=mt Phabricator: https://phabricator.services.mozilla.com/D6042 --- cmd/tstclnt/Makefile | 2 +- cmd/tstclnt/tstclnt.c | 33 +- gtests/ssl_gtest/manifest.mn | 1 + gtests/ssl_gtest/rsa8193.h | 2 +- gtests/ssl_gtest/ssl_extension_unittest.cc | 27 +- gtests/ssl_gtest/ssl_gtest.gyp | 1 + gtests/ssl_gtest/tls_esni_unittest.cc | 453 +++++++++++ gtests/ssl_gtest/tls_filter.cc | 11 + gtests/ssl_gtest/tls_filter.h | 14 + lib/ssl/SSLerrs.h | 9 + lib/ssl/config.mk | 4 + lib/ssl/manifest.mn | 2 +- lib/ssl/ssl.gyp | 6 + lib/ssl/ssl3con.c | 91 ++- lib/ssl/ssl3ecc.c | 7 +- lib/ssl/ssl3ext.c | 13 +- lib/ssl/ssl3ext.h | 10 + lib/ssl/ssl3exthandle.c | 72 +- lib/ssl/ssl3exthandle.h | 4 + lib/ssl/sslerr.h | 3 + lib/ssl/sslexp.h | 59 +- lib/ssl/sslimpl.h | 30 +- lib/ssl/sslsock.c | 23 + lib/ssl/sslspec.c | 2 +- lib/ssl/sslt.h | 3 +- lib/ssl/tls13con.c | 153 ++-- lib/ssl/tls13con.h | 26 +- lib/ssl/tls13esni.c | 844 +++++++++++++++++++++ lib/ssl/tls13esni.h | 51 ++ lib/ssl/tls13exthandle.c | 361 ++++++++- lib/ssl/tls13exthandle.h | 9 + lib/util/secitem.c | 4 +- lib/util/secitem.h | 2 +- 33 files changed, 2156 insertions(+), 176 deletions(-) create mode 100644 gtests/ssl_gtest/tls_esni_unittest.cc create mode 100644 lib/ssl/tls13esni.c create mode 100644 lib/ssl/tls13esni.h diff --git a/cmd/tstclnt/Makefile b/cmd/tstclnt/Makefile index a27a3ce97f..aae7b445cb 100644 --- a/cmd/tstclnt/Makefile +++ b/cmd/tstclnt/Makefile @@ -1,5 +1,5 @@ #! gmake -# +# # 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/. diff --git a/cmd/tstclnt/tstclnt.c b/cmd/tstclnt/tstclnt.c index b09b292220..520eeff648 100644 --- a/cmd/tstclnt/tstclnt.c +++ b/cmd/tstclnt/tstclnt.c @@ -28,6 +28,7 @@ #include "prio.h" #include "prnetdb.h" #include "nss.h" +#include "nssb64.h" #include "ocsp.h" #include "ssl.h" #include "sslproto.h" @@ -224,7 +225,8 @@ PrintUsageHeader() " [-V [min-version]:[max-version]] [-K] [-T] [-U]\n" " [-r N] [-w passwd] [-W pwfile] [-q [-t seconds]]\n" " [-I groups] [-J signatureschemes]\n" - " [-A requestfile] [-L totalconnections] [-P {client,server}] [-Q]\n" + " [-A requestfile] [-L totalconnections] [-P {client,server}]\n" + " [-N encryptedSniKeys] [-Q]\n" "\n", progName); } @@ -308,6 +310,7 @@ PrintParameterUsage() fprintf(stderr, "%-20s Enable alternative TLS 1.3 handshake\n", "-X alt-server-hello"); fprintf(stderr, "%-20s Use DTLS\n", "-P {client, server}"); fprintf(stderr, "%-20s Exit after handshake\n", "-Q"); + fprintf(stderr, "%-20s Encrypted SNI Keys\n", "-N"); } static void @@ -985,6 +988,7 @@ PRBool stopAfterHandshake = PR_FALSE; PRBool requestToExit = PR_FALSE; char *versionString = NULL; PRBool handshakeComplete = PR_FALSE; +char *encryptedSNIKeys = NULL; static int writeBytesToServer(PRFileDesc *s, const PRUint8 *buf, int nb) @@ -1424,6 +1428,26 @@ run() } } + if (encryptedSNIKeys) { + SECItem esniKeysBin = { siBuffer, NULL, 0 }; + + if (!NSSBase64_DecodeBuffer(NULL, &esniKeysBin, encryptedSNIKeys, + strlen(encryptedSNIKeys))) { + SECU_PrintError(progName, "ESNIKeys record is invalid base64"); + error = 1; + goto done; + } + + rv = SSL_EnableESNI(s, esniKeysBin.data, esniKeysBin.len, + "dummy.invalid"); + SECITEM_FreeItem(&esniKeysBin, PR_FALSE); + if (rv < 0) { + SECU_PrintError(progName, "SSL_EnableESNI failed"); + error = 1; + goto done; + } + } + serverCertAuth.dbHandle = CERT_GetDefaultCertDB(); SSL_AuthCertificateHook(s, ownAuthCertificate, &serverCertAuth); @@ -1683,7 +1707,7 @@ main(int argc, char **argv) * Please leave some time before reusing these. */ optstate = PL_CreateOptState(argc, argv, - "46A:CDFGHI:J:KL:M:OP:QR:STUV:W:X:YZa:bc:d:fgh:m:n:op:qr:st:uvw:"); + "46A:CDFGHI:J:KL:M:N:OP:QR:STUV:W:X:YZa:bc:d:fgh:m:n:op:qr:st:uvw:"); while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) { switch (optstate->option) { case '?': @@ -1760,6 +1784,10 @@ main(int argc, char **argv) }; break; + case 'N': + encryptedSNIKeys = PORT_Strdup(optstate->value); + break; + case 'P': useDTLS = PR_TRUE; if (!strcmp(optstate->value, "server")) { @@ -2108,6 +2136,7 @@ main(int argc, char **argv) PORT_Free(pwdata.data); PORT_Free(host); PORT_Free(zeroRttData); + PORT_Free(encryptedSNIKeys); if (enabledGroups) { PORT_Free(enabledGroups); diff --git a/gtests/ssl_gtest/manifest.mn b/gtests/ssl_gtest/manifest.mn index 8547e56d1d..7f4ee79539 100644 --- a/gtests/ssl_gtest/manifest.mn +++ b/gtests/ssl_gtest/manifest.mn @@ -52,6 +52,7 @@ CPPSRCS = \ tls_hkdf_unittest.cc \ tls_filter.cc \ tls_protect.cc \ + tls_esni_unittest.cc \ $(NULL) INCLUDES += -I$(CORE_DEPTH)/gtests/google_test/gtest/include \ diff --git a/gtests/ssl_gtest/rsa8193.h b/gtests/ssl_gtest/rsa8193.h index 6265163896..1ac8503bc0 100644 --- a/gtests/ssl_gtest/rsa8193.h +++ b/gtests/ssl_gtest/rsa8193.h @@ -206,4 +206,4 @@ static const uint8_t rsa8193[] = { 0x13, 0x34, 0x9d, 0x34, 0xb8, 0xef, 0x13, 0x3a, 0x20, 0xf5, 0x74, 0x02, 0x70, 0x3b, 0x41, 0x60, 0x1f, 0x5e, 0x76, 0x0a, 0xb1, 0x17, 0xd5, 0xcf, 0x79, 0xef, 0xf7, 0xab, 0xe7, 0xd6, 0x0f, 0xad, 0x85, 0x2c, 0x52, 0x67, - 0xb5, 0xa0, 0x4a, 0xfd, 0xaf}; \ No newline at end of file + 0xb5, 0xa0, 0x4a, 0xfd, 0xaf}; diff --git a/gtests/ssl_gtest/ssl_extension_unittest.cc b/gtests/ssl_gtest/ssl_extension_unittest.cc index a3a3c1191f..ed0a000752 100644 --- a/gtests/ssl_gtest/ssl_extension_unittest.cc +++ b/gtests/ssl_gtest/ssl_extension_unittest.cc @@ -44,28 +44,6 @@ class TlsExtensionTruncator : public TlsExtensionFilter { size_t length_; }; -class TlsExtensionDamager : public TlsExtensionFilter { - public: - TlsExtensionDamager(const std::shared_ptr& a, uint16_t extension, - size_t index) - : TlsExtensionFilter(a), extension_(extension), index_(index) {} - virtual PacketFilter::Action FilterExtension(uint16_t extension_type, - const DataBuffer& input, - DataBuffer* output) { - if (extension_type != extension_) { - return KEEP; - } - - *output = input; - output->data()[index_] += 73; // Increment selected for maximum damage - return CHANGE; - } - - private: - uint16_t extension_; - size_t index_; -}; - class TlsExtensionAppender : public TlsHandshakeFilter { public: TlsExtensionAppender(const std::shared_ptr& a, @@ -611,7 +589,6 @@ TEST_F(TlsExtensionTest13Stream, WrongServerKeyShare) { EXPECT_EQ(SSL_ERROR_BAD_MAC_READ, server_->error_code()); } -// TODO(ekr@rtfm.com): This is the wrong error code. See bug 1307269. TEST_F(TlsExtensionTest13Stream, UnknownServerKeyShare) { const uint16_t wrong_group = 0xffff; @@ -625,10 +602,10 @@ TEST_F(TlsExtensionTest13Stream, UnknownServerKeyShare) { DataBuffer buf(key_share, sizeof(key_share)); EnsureTlsSetup(); MakeTlsFilter(server_, ssl_tls13_key_share_xtn, buf); - client_->ExpectSendAlert(kTlsAlertMissingExtension); + client_->ExpectSendAlert(kTlsAlertIllegalParameter); server_->ExpectSendAlert(kTlsAlertBadRecordMac); ConnectExpectFail(); - EXPECT_EQ(SSL_ERROR_MISSING_KEY_SHARE, client_->error_code()); + EXPECT_EQ(SSL_ERROR_RX_MALFORMED_KEY_SHARE, client_->error_code()); EXPECT_EQ(SSL_ERROR_BAD_MAC_READ, server_->error_code()); } diff --git a/gtests/ssl_gtest/ssl_gtest.gyp b/gtests/ssl_gtest/ssl_gtest.gyp index 17677713d6..be1c4ea325 100644 --- a/gtests/ssl_gtest/ssl_gtest.gyp +++ b/gtests/ssl_gtest/ssl_gtest.gyp @@ -51,6 +51,7 @@ 'tls_connect.cc', 'tls_filter.cc', 'tls_hkdf_unittest.cc', + 'tls_esni_unittest.cc', 'tls_protect.cc' ], 'dependencies': [ diff --git a/gtests/ssl_gtest/tls_esni_unittest.cc b/gtests/ssl_gtest/tls_esni_unittest.cc new file mode 100644 index 0000000000..8619214ade --- /dev/null +++ b/gtests/ssl_gtest/tls_esni_unittest.cc @@ -0,0 +1,453 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* 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/. */ + +#include + +#include "secerr.h" +#include "ssl.h" + +#include "gtest_utils.h" +#include "tls_agent.h" +#include "tls_connect.h" + +namespace nss_test { + +static const char* kDummySni("dummy.invalid"); + +std::vector kDefaultSuites = {TLS_AES_256_GCM_SHA384, + TLS_AES_128_GCM_SHA256}; +std::vector kChaChaSuite = {TLS_CHACHA20_POLY1305_SHA256}; +std::vector kBogusSuites = {0}; +std::vector kTls12Suites = { + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256}; + +static void NamedGroup2ECParams(SSLNamedGroup group, SECItem* params) { + auto groupDef = ssl_LookupNamedGroup(group); + ASSERT_NE(nullptr, groupDef); + + auto oidData = SECOID_FindOIDByTag(groupDef->oidTag); + ASSERT_NE(nullptr, oidData); + ASSERT_NE(nullptr, + SECITEM_AllocItem(nullptr, params, (2 + oidData->oid.len))); + + /* + * params->data needs to contain the ASN encoding of an object ID (OID) + * representing the named curve. The actual OID is in + * oidData->oid.data so we simply prepend 0x06 and OID length + */ + params->data[0] = SEC_ASN1_OBJECT_ID; + params->data[1] = oidData->oid.len; + memcpy(params->data + 2, oidData->oid.data, oidData->oid.len); +} + +/* Checksum is a 4-byte array. */ +static void UpdateEsniKeysChecksum(DataBuffer* buf) { + SECStatus rv; + PRUint8 sha256[32]; + + /* Stomp the checksum. */ + PORT_Memset(buf->data() + 2, 0, 4); + + rv = PK11_HashBuf(ssl3_HashTypeToOID(ssl_hash_sha256), sha256, buf->data(), + buf->len()); + ASSERT_EQ(SECSuccess, rv); + buf->Write(2, sha256, 4); +} + +static void GenerateEsniKey(time_t windowStart, SSLNamedGroup group, + std::vector& cipher_suites, + DataBuffer* record, + ScopedSECKEYPublicKey* pubKey = nullptr, + ScopedSECKEYPrivateKey* privKey = nullptr) { + SECKEYECParams ecParams = {siBuffer, NULL, 0}; + NamedGroup2ECParams(group, &ecParams); + + SECKEYPublicKey* pub = nullptr; + SECKEYPrivateKey* priv = SECKEY_CreateECPrivateKey(&ecParams, &pub, nullptr); + ASSERT_NE(nullptr, priv); + SECITEM_FreeItem(&ecParams, PR_FALSE); + PRUint8 encoded[1024]; + unsigned int encoded_len; + + SECStatus rv = SSL_EncodeESNIKeys( + &cipher_suites[0], cipher_suites.size(), group, pub, 100, windowStart, + windowStart + 10, encoded, &encoded_len, sizeof(encoded)); + ASSERT_EQ(SECSuccess, rv); + ASSERT_GT(encoded_len, 0U); + + if (pubKey) { + pubKey->reset(pub); + } else { + SECKEY_DestroyPublicKey(pub); + } + if (privKey) { + privKey->reset(priv); + } else { + SECKEY_DestroyPrivateKey(priv); + } + record->Truncate(0); + record->Write(0, encoded, encoded_len); +} + +static void SetupEsni(const std::shared_ptr& client, + const std::shared_ptr& server, + SSLNamedGroup group = ssl_grp_ec_curve25519) { + ScopedSECKEYPublicKey pub; + ScopedSECKEYPrivateKey priv; + DataBuffer record; + + GenerateEsniKey(time(nullptr), ssl_grp_ec_curve25519, kDefaultSuites, &record, + &pub, &priv); + SECStatus rv = SSL_SetESNIKeyPair(server->ssl_fd(), priv.get(), record.data(), + record.len()); + ASSERT_EQ(SECSuccess, rv); + + rv = SSL_EnableESNI(client->ssl_fd(), record.data(), record.len(), kDummySni); + ASSERT_EQ(SECSuccess, rv); +} + +static void CheckSniExtension(const DataBuffer& data) { + TlsParser parser(data.data(), data.len()); + uint32_t tmp; + ASSERT_TRUE(parser.Read(&tmp, 2)); + ASSERT_EQ(parser.remaining(), tmp); + ASSERT_TRUE(parser.Read(&tmp, 1)); + ASSERT_EQ(0U, tmp); /* sni_nametype_hostname */ + DataBuffer name; + ASSERT_TRUE(parser.ReadVariable(&name, 2)); + ASSERT_EQ(0U, parser.remaining()); + DataBuffer expected(reinterpret_cast(kDummySni), + strlen(kDummySni)); + ASSERT_EQ(expected, name); +} + +static void ClientInstallEsni(std::shared_ptr& agent, + const DataBuffer& record, PRErrorCode err = 0) { + SECStatus rv = + SSL_EnableESNI(agent->ssl_fd(), record.data(), record.len(), kDummySni); + if (err == 0) { + ASSERT_EQ(SECSuccess, rv); + } else { + ASSERT_EQ(SECFailure, rv); + ASSERT_EQ(err, PORT_GetError()); + } +} + +TEST_P(TlsAgentTestClient13, EsniInstall) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + ClientInstallEsni(agent_, record); +} + +// The next set of tests fail at setup time. +TEST_P(TlsAgentTestClient13, EsniInvalidHash) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.data()[2]++; + ClientInstallEsni(agent_, record, SSL_ERROR_RX_MALFORMED_ESNI_KEYS); +} + +TEST_P(TlsAgentTestClient13, EsniInvalidVersion) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.Write(0, 0xffff, 2); + ClientInstallEsni(agent_, record, SSL_ERROR_UNSUPPORTED_VERSION); +} + +TEST_P(TlsAgentTestClient13, EsniShort) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.Truncate(record.len() - 1); + UpdateEsniKeysChecksum(&record); + ClientInstallEsni(agent_, record, SSL_ERROR_RX_MALFORMED_ESNI_KEYS); +} + +TEST_P(TlsAgentTestClient13, EsniLong) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.Write(record.len(), 1, 1); + UpdateEsniKeysChecksum(&record); + ClientInstallEsni(agent_, record, SSL_ERROR_RX_MALFORMED_ESNI_KEYS); +} + +TEST_P(TlsAgentTestClient13, EsniExtensionMismatch) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.Write(record.len() - 1, 1, 1); + UpdateEsniKeysChecksum(&record); + ClientInstallEsni(agent_, record, SSL_ERROR_RX_MALFORMED_ESNI_KEYS); +} + +// The following tests fail by ignoring the Esni block. +TEST_P(TlsAgentTestClient13, EsniUnknownGroup) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + record.Write(8, 0xffff, 2); // Fake group + UpdateEsniKeysChecksum(&record); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_EQ(TlsAgent::STATE_CONNECTING, agent_->state()); + ASSERT_TRUE(!filter->captured()); +} + +TEST_P(TlsAgentTestClient13, EsniUnknownCS) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kBogusSuites, &record); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_EQ(TlsAgent::STATE_CONNECTING, agent_->state()); + ASSERT_TRUE(!filter->captured()); +} + +TEST_P(TlsAgentTestClient13, EsniInvalidCS) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kTls12Suites, &record); + UpdateEsniKeysChecksum(&record); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_EQ(TlsAgent::STATE_CONNECTING, agent_->state()); + ASSERT_TRUE(!filter->captured()); +} + +TEST_P(TlsAgentTestClient13, EsniNotReady) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0) + 1000, ssl_grp_ec_curve25519, kDefaultSuites, + &record); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_TRUE(!filter->captured()); +} + +TEST_P(TlsAgentTestClient13, EsniExpired) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0) - 1000, ssl_grp_ec_curve25519, kDefaultSuites, + &record); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_TRUE(!filter->captured()); +} + +TEST_P(TlsAgentTestClient13, NoSniSoNoEsni) { + EnsureInit(); + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + SSL_SetURL(agent_->ssl_fd(), ""); + ClientInstallEsni(agent_, record, 0); + auto filter = + MakeTlsFilter(agent_, ssl_tls13_encrypted_sni_xtn); + agent_->Handshake(); + ASSERT_TRUE(!filter->captured()); +} + +static int32_t SniCallback(TlsAgent* agent, const SECItem* srvNameAddr, + PRUint32 srvNameArrSize) { + EXPECT_EQ(1U, srvNameArrSize); + SECItem expected = { + siBuffer, reinterpret_cast(const_cast("server")), + 6}; + EXPECT_TRUE(!SECITEM_CompareItem(&expected, &srvNameAddr[0])); + return SECSuccess; +} + +TEST_P(TlsConnectTls13, ConnectEsni) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + auto cFilterSni = + MakeTlsFilter(client_, ssl_server_name_xtn); + auto cFilterEsni = + MakeTlsFilter(client_, ssl_tls13_encrypted_sni_xtn); + client_->SetFilter(std::make_shared( + ChainedPacketFilterInit({cFilterSni, cFilterEsni}))); + auto sfilter = + MakeTlsFilter(server_, ssl_server_name_xtn); + sfilter->EnableDecryption(); + server_->SetSniCallback(SniCallback); + Connect(); + CheckSniExtension(cFilterSni->extension()); + ASSERT_TRUE(cFilterEsni->captured()); + // Check that our most preferred suite got chosen. + uint32_t suite; + ASSERT_TRUE(cFilterEsni->extension().Read(0, 2, &suite)); + ASSERT_EQ(TLS_AES_128_GCM_SHA256, static_cast(suite)); + ASSERT_TRUE(!sfilter->captured()); +} + +TEST_P(TlsConnectTls13, ConnectEsniHrr) { + EnsureTlsSetup(); + const std::vector groups = {ssl_grp_ec_secp384r1}; + server_->ConfigNamedGroups(groups); + SetupEsni(client_, server_); + auto hrr_capture = MakeTlsFilter( + server_, kTlsHandshakeHelloRetryRequest); + auto filter = + MakeTlsFilter(client_, ssl_server_name_xtn); + auto cfilter = + MakeTlsFilter(client_, ssl_server_name_xtn); + server_->SetSniCallback(SniCallback); + Connect(); + CheckSniExtension(cfilter->extension()); + EXPECT_NE(0UL, hrr_capture->buffer().len()); +} + +TEST_P(TlsConnectTls13, ConnectEsniNoDummy) { + EnsureTlsSetup(); + ScopedSECKEYPublicKey pub; + ScopedSECKEYPrivateKey priv; + DataBuffer record; + + GenerateEsniKey(time(nullptr), ssl_grp_ec_curve25519, kDefaultSuites, &record, + &pub, &priv); + SECStatus rv = SSL_SetESNIKeyPair(server_->ssl_fd(), priv.get(), + record.data(), record.len()); + ASSERT_EQ(SECSuccess, rv); + rv = SSL_EnableESNI(client_->ssl_fd(), record.data(), record.len(), ""); + ASSERT_EQ(SECSuccess, rv); + + auto cfilter = + MakeTlsFilter(client_, ssl_server_name_xtn); + auto sfilter = + MakeTlsFilter(server_, ssl_server_name_xtn); + server_->SetSniCallback(SniCallback); + Connect(); + ASSERT_TRUE(!cfilter->captured()); + ASSERT_TRUE(!sfilter->captured()); +} + +TEST_P(TlsConnectTls13, ConnectEsniNullDummy) { + EnsureTlsSetup(); + ScopedSECKEYPublicKey pub; + ScopedSECKEYPrivateKey priv; + DataBuffer record; + + GenerateEsniKey(time(nullptr), ssl_grp_ec_curve25519, kDefaultSuites, &record, + &pub, &priv); + SECStatus rv = SSL_SetESNIKeyPair(server_->ssl_fd(), priv.get(), + record.data(), record.len()); + ASSERT_EQ(SECSuccess, rv); + rv = SSL_EnableESNI(client_->ssl_fd(), record.data(), record.len(), nullptr); + ASSERT_EQ(SECSuccess, rv); + + auto cfilter = + MakeTlsFilter(client_, ssl_server_name_xtn); + auto sfilter = + MakeTlsFilter(server_, ssl_server_name_xtn); + server_->SetSniCallback(SniCallback); + Connect(); + ASSERT_TRUE(!cfilter->captured()); + ASSERT_TRUE(!sfilter->captured()); +} + +/* Tell the client that it supports AES but the server that it supports ChaCha + */ +TEST_P(TlsConnectTls13, ConnectEsniCSMismatch) { + EnsureTlsSetup(); + ScopedSECKEYPublicKey pub; + ScopedSECKEYPrivateKey priv; + DataBuffer record; + + GenerateEsniKey(time(nullptr), ssl_grp_ec_curve25519, kDefaultSuites, &record, + &pub, &priv); + PRUint8 encoded[1024]; + unsigned int encoded_len; + + SECStatus rv = SSL_EncodeESNIKeys( + &kChaChaSuite[0], kChaChaSuite.size(), ssl_grp_ec_curve25519, pub.get(), + 100, time(0), time(0) + 10, encoded, &encoded_len, sizeof(encoded)); + rv = SSL_SetESNIKeyPair(server_->ssl_fd(), priv.get(), encoded, encoded_len); + ASSERT_EQ(SECSuccess, rv); + rv = SSL_EnableESNI(client_->ssl_fd(), record.data(), record.len(), ""); + ASSERT_EQ(SECSuccess, rv); + ConnectExpectAlert(server_, illegal_parameter); + server_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); +} + +TEST_P(TlsConnectTls13, ConnectEsniP256) { + EnsureTlsSetup(); + SetupEsni(client_, server_, ssl_grp_ec_secp256r1); + auto cfilter = + MakeTlsFilter(client_, ssl_server_name_xtn); + auto sfilter = + MakeTlsFilter(server_, ssl_server_name_xtn); + server_->SetSniCallback(SniCallback); + Connect(); + CheckSniExtension(cfilter->extension()); + ASSERT_TRUE(!sfilter->captured()); +} + +TEST_P(TlsConnectTls13, ConnectMismatchedEsniKeys) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + // Now install a new set of keys on the client, so we have a mismatch. + DataBuffer record; + GenerateEsniKey(time(0), ssl_grp_ec_curve25519, kDefaultSuites, &record); + ClientInstallEsni(client_, record, 0); + ConnectExpectAlert(server_, illegal_parameter); + server_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); +} + +TEST_P(TlsConnectTls13, ConnectDamagedEsniExtensionCH) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + auto filter = MakeTlsFilter( + client_, ssl_tls13_encrypted_sni_xtn, 50); // in the ciphertext + ConnectExpectAlert(server_, illegal_parameter); + server_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); +} + +TEST_P(TlsConnectTls13, ConnectRemoveEsniExtensionEE) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + auto filter = + MakeTlsFilter(server_, ssl_tls13_encrypted_sni_xtn); + filter->EnableDecryption(); + ConnectExpectAlert(client_, missing_extension); + client_->CheckErrorCode(SSL_ERROR_MISSING_ESNI_EXTENSION); +} + +TEST_P(TlsConnectTls13, ConnectShortEsniExtensionEE) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + DataBuffer shortNonce; + auto filter = MakeTlsFilter( + server_, ssl_tls13_encrypted_sni_xtn, shortNonce); + filter->EnableDecryption(); + ConnectExpectAlert(client_, illegal_parameter); + client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION); +} + +TEST_P(TlsConnectTls13, ConnectBogusEsniExtensionEE) { + EnsureTlsSetup(); + SetupEsni(client_, server_); + const uint8_t bogusNonceBuf[16] = {0}; + DataBuffer bogusNonce(bogusNonceBuf, sizeof(bogusNonceBuf)); + auto filter = MakeTlsFilter( + server_, ssl_tls13_encrypted_sni_xtn, bogusNonce); + filter->EnableDecryption(); + ConnectExpectAlert(client_, illegal_parameter); + client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION); +} +} diff --git a/gtests/ssl_gtest/tls_filter.cc b/gtests/ssl_gtest/tls_filter.cc index e824a16fd5..25ad606fcc 100644 --- a/gtests/ssl_gtest/tls_filter.cc +++ b/gtests/ssl_gtest/tls_filter.cc @@ -878,6 +878,17 @@ PacketFilter::Action TlsExtensionDropper::FilterExtension( return KEEP; } +PacketFilter::Action TlsExtensionDamager::FilterExtension( + uint16_t extension_type, const DataBuffer& input, DataBuffer* output) { + if (extension_type != extension_) { + return KEEP; + } + + *output = input; + output->data()[index_] += 73; // Increment selected for maximum damage + return CHANGE; +} + PacketFilter::Action TlsExtensionInjector::FilterHandshake( const HandshakeHeader& header, const DataBuffer& input, DataBuffer* output) { diff --git a/gtests/ssl_gtest/tls_filter.h b/gtests/ssl_gtest/tls_filter.h index 087b23b147..2b6e886456 100644 --- a/gtests/ssl_gtest/tls_filter.h +++ b/gtests/ssl_gtest/tls_filter.h @@ -465,6 +465,20 @@ class TlsExtensionInjector : public TlsHandshakeFilter { const DataBuffer data_; }; +class TlsExtensionDamager : public TlsExtensionFilter { + public: + TlsExtensionDamager(const std::shared_ptr& a, uint16_t extension, + size_t index) + : TlsExtensionFilter(a), extension_(extension), index_(index) {} + virtual PacketFilter::Action FilterExtension(uint16_t extension_type, + const DataBuffer& input, + DataBuffer* output); + + private: + uint16_t extension_; + size_t index_; +}; + typedef std::function VoidFunction; class AfterRecordN : public TlsRecordFilter { diff --git a/lib/ssl/SSLerrs.h b/lib/ssl/SSLerrs.h index f01d165833..dda6dc2fde 100644 --- a/lib/ssl/SSLerrs.h +++ b/lib/ssl/SSLerrs.h @@ -552,3 +552,12 @@ ER3(SSL_ERROR_RX_MALFORMED_DTLS_ACK, (SSL_ERROR_BASE + 174), ER3(SSL_ERROR_DH_KEY_TOO_LONG, (SSL_ERROR_BASE + 175), "SSL received a DH key share that's too long (>8192 bit).") + +ER3(SSL_ERROR_RX_MALFORMED_ESNI_KEYS, (SSL_ERROR_BASE + 176), + "SSL received a malformed ESNI keys structure") + +ER3(SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION, (SSL_ERROR_BASE + 177), + "SSL received a malformed ESNI extension") + +ER3(SSL_ERROR_MISSING_ESNI_EXTENSION, (SSL_ERROR_BASE + 178), + "SSL did not receive an ESNI extension") diff --git a/lib/ssl/config.mk b/lib/ssl/config.mk index d13613f78c..b901a8830d 100644 --- a/lib/ssl/config.mk +++ b/lib/ssl/config.mk @@ -60,3 +60,7 @@ endif ifdef NSS_DISABLE_TLS_1_3 DEFINES += -DNSS_DISABLE_TLS_1_3 endif + +ifeq (,$(filter-out DragonFly FreeBSD Linux NetBSD OpenBSD, $(OS_TARGET))) +CFLAGS += -std=gnu99 +endif diff --git a/lib/ssl/manifest.mn b/lib/ssl/manifest.mn index ca9b9ee7bd..fe9470bd01 100644 --- a/lib/ssl/manifest.mn +++ b/lib/ssl/manifest.mn @@ -1,4 +1,3 @@ -# # 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/. @@ -56,6 +55,7 @@ CSRCS = \ tls13replay.c \ sslcert.c \ sslgrp.c \ + tls13esni.c \ $(NULL) LIBRARY_NAME = ssl diff --git a/lib/ssl/ssl.gyp b/lib/ssl/ssl.gyp index 3694ab91a5..2e28f67757 100644 --- a/lib/ssl/ssl.gyp +++ b/lib/ssl/ssl.gyp @@ -43,6 +43,7 @@ 'ssltrace.c', 'sslver.c', 'tls13con.c', + 'tls13esni.c', 'tls13exthandle.c', 'tls13hashstate.c', 'tls13hkdf.c', @@ -67,6 +68,11 @@ 'UNSAFE_FUZZER_MODE', ], }], + [ 'OS=="dragonfly" or OS=="freebsd" or OS=="netbsd" or OS=="openbsd" or OS=="linux"', { + 'cflags': [ + '-std=gnu99', + ], + }], ], 'dependencies': [ '<(DEPTH)/exports.gyp:nss_exports', diff --git a/lib/ssl/ssl3con.c b/lib/ssl/ssl3con.c index 26efdfdc0d..e82ab09877 100644 --- a/lib/ssl/ssl3con.c +++ b/lib/ssl/ssl3con.c @@ -656,7 +656,7 @@ ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite, return NULL; } -const static ssl3CipherSuiteCfg * +const ssl3CipherSuiteCfg * ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites) { return ssl_LookupCipherSuiteCfgMutable(suite, @@ -854,9 +854,9 @@ ssl3_config_match_init(sslSocket *ss) /* Return PR_TRUE if suite is usable. This if the suite is permitted by policy, * enabled, has a certificate (as needed), has a viable key agreement method, is * usable with the negotiated TLS version, and is otherwise usable. */ -static PRBool -config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy, - const SSLVersionRange *vrange, const sslSocket *ss) +PRBool +ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy, + const SSLVersionRange *vrange, const sslSocket *ss) { const ssl3CipherSuiteDef *cipher_def; const ssl3KEADef *kea_def; @@ -899,7 +899,7 @@ count_cipher_suites(sslSocket *ss, PRUint8 policy) return 0; } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - if (config_match(&ss->cipherSuites[i], policy, &ss->vrange, ss)) + if (ssl3_config_match(&ss->cipherSuites[i], policy, &ss->vrange, ss)) count++; } if (count == 0) { @@ -4798,7 +4798,7 @@ ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) suite = ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite, ss->cipherSuites); PORT_Assert(suite); - if (!suite || !config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { + if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { sidOK = PR_FALSE; } @@ -4946,6 +4946,14 @@ ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) PR_RWLock_Rlock(sid->u.ssl3.lock); } + /* Generate a new random if this is the first attempt. */ + if (type == client_hello_initial) { + rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random); + if (rv != SECSuccess) { + goto loser; /* err set by GetNewRandom. */ + } + } + if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 && type == client_hello_initial) { rv = tls13_SetupClientHello(ss); @@ -4953,6 +4961,7 @@ ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) goto loser; } } + if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello); if (rv != SECSuccess) { @@ -5024,13 +5033,6 @@ ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) goto loser; /* err set by ssl3_AppendHandshake* */ } - /* Generate a new random if this is the first attempt. */ - if (type == client_hello_initial) { - rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random); - if (rv != SECSuccess) { - goto loser; /* err set by GetNewRandom. */ - } - } rv = ssl3_AppendHandshake(ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { @@ -5085,7 +5087,7 @@ ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { + if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { actual_count++; if (actual_count > num_suites) { /* set error card removal/insertion error */ @@ -6326,7 +6328,7 @@ ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version, ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i]; if (suite == suiteCfg->cipher_suite) { SSLVersionRange vrange = { version, version }; - if (!config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) { + if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) { /* config_match already checks whether the cipher suite is * acceptable for the version, but the check is repeated here * in order to give a more precise error code. */ @@ -7858,6 +7860,30 @@ ssl3_KEASupportsTickets(const ssl3KEADef *kea_def) return PR_TRUE; } +SECStatus +ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites, + PRUint16 version, PRUint16 *suitep) +{ + unsigned int j; + unsigned int i; + + for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; + SSLVersionRange vrange = { version, version }; + if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) { + continue; + } + for (i = 0; i + 1 < suites->len; i += 2) { + PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1]; + if (suite_i == suite->cipher_suite) { + *suitep = suite_i; + return SECSuccess; + } + } + } + return SECFailure; +} + /* Select a cipher suite. ** ** NOTE: This suite selection algorithm should be the same as the one in @@ -7876,24 +7902,16 @@ SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites, PRBool initHashes) { - unsigned int j; - unsigned int i; + PRUint16 selected; + SECStatus rv; - for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; - SSLVersionRange vrange = { ss->version, ss->version }; - if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) { - continue; - } - for (i = 0; i + 1 < suites->len; i += 2) { - PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1]; - if (suite_i == suite->cipher_suite) { - ss->ssl3.hs.cipher_suite = suite_i; - return ssl3_SetupCipherSuite(ss, initHashes); - } - } + rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected); + if (rv != SECSuccess) { + return SECFailure; } - return SECFailure; + + ss->ssl3.hs.cipher_suite = selected; + return ssl3_SetupCipherSuite(ss, initHashes); } /* @@ -8025,9 +8043,12 @@ ssl3_ServerCallSNICallback(sslSocket *ss) } /* Need to tell the client that application has picked * the name from the offered list and reconfigured the socket. + * Don't do this if we negotiated ESNI. */ - ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn, - ssl_SendEmptyExtension); + if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_encrypted_sni_xtn)) { + ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn, + ssl_SendEmptyExtension); + } } else { /* Callback returned index outside of the boundary. */ PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize); @@ -8631,7 +8652,7 @@ ssl3_HandleClientHelloPart2(sslSocket *ss, * The product policy won't change during the process lifetime. * Implemented ("isPresent") shouldn't change for servers. */ - if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) + if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) break; #else if (!suite->enabled) @@ -9013,7 +9034,7 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int leng for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; SSLVersionRange vrange = { ss->version, ss->version }; - if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) { + if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) { continue; } for (i = 0; i + 2 < suite_length; i += 3) { diff --git a/lib/ssl/ssl3ecc.c b/lib/ssl/ssl3ecc.c index f8b9a94000..52d5bb5152 100644 --- a/lib/ssl/ssl3ecc.c +++ b/lib/ssl/ssl3ecc.c @@ -327,16 +327,13 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, PRUint8 *b, ** Take an encoded key share and make a public key out of it. */ SECStatus -ssl_ImportECDHKeyShare(sslSocket *ss, SECKEYPublicKey *peerKey, +ssl_ImportECDHKeyShare(SECKEYPublicKey *peerKey, PRUint8 *b, PRUint32 length, const sslNamedGroupDef *ecGroup) { SECStatus rv; SECItem ecPoint = { siBuffer, NULL, 0 }; - PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); - PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - if (!length) { PORT_SetError(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE); return SECFailure; @@ -616,7 +613,7 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length) peerKey->arena = arena; /* create public key from point data */ - rv = ssl_ImportECDHKeyShare(ss, peerKey, ec_point.data, ec_point.len, + rv = ssl_ImportECDHKeyShare(peerKey, ec_point.data, ec_point.len, ecGroup); if (rv != SECSuccess) { /* error code is set */ diff --git a/lib/ssl/ssl3ext.c b/lib/ssl/ssl3ext.c index 9b6c719f88..60b5889e72 100644 --- a/lib/ssl/ssl3ext.c +++ b/lib/ssl/ssl3ext.c @@ -50,6 +50,7 @@ static const ssl3ExtensionHandler clientHelloHandlers[] = { { ssl_tls13_early_data_xtn, &tls13_ServerHandleEarlyDataXtn }, { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ServerHandlePskModesXtn }, { ssl_tls13_cookie_xtn, &tls13_ServerHandleCookieXtn }, + { ssl_tls13_encrypted_sni_xtn, &tls13_ServerHandleEsniXtn }, { ssl_record_size_limit_xtn, &ssl_HandleRecordSizeLimitXtn }, { 0, NULL } }; @@ -136,6 +137,7 @@ static const sslExtensionBuilder clientHelloSendersTLS[] = { ssl_signature_algorithms_xtn, &ssl3_SendSigAlgsXtn }, { ssl_tls13_cookie_xtn, &tls13_ClientSendHrrCookieXtn }, { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ClientSendPskModesXtn }, + { ssl_tls13_encrypted_sni_xtn, &tls13_ClientSendEsniXtn }, { ssl_record_size_limit_xtn, &ssl_SendRecordSizeLimitXtn }, /* The pre_shared_key extension MUST be last. */ { ssl_tls13_pre_shared_key_xtn, &tls13_ClientSendPreSharedKeyXtn }, @@ -338,8 +340,6 @@ ssl3_ParseExtensions(sslSocket *ss, PRUint8 **b, PRUint32 *length) return SECFailure; /* alert already sent */ } - SSL_TRC(10, ("%d: SSL3[%d]: parsing extension %d", - SSL_GETPID(), ss->fd, extension_type)); /* Check whether an extension has been sent multiple times. */ for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions); cursor != &ss->ssl3.hs.remoteExtensions; @@ -357,6 +357,9 @@ ssl3_ParseExtensions(sslSocket *ss, PRUint8 **b, PRUint32 *length) return rv; /* alert already sent */ } + SSL_TRC(10, ("%d: SSL3[%d]: parsed extension %d len=%u", + SSL_GETPID(), ss->fd, extension_type, extension_data.len)); + extension = PORT_ZNew(TLSExtension); if (!extension) { return SECFailure; @@ -409,7 +412,9 @@ ssl_CallExtensionHandler(sslSocket *ss, SSLHandshakeType handshakeMessage, /* Find extension_type in table of Hello Extension Handlers. */ for (; handler->ex_handler != NULL; ++handler) { if (handler->ex_type == extension->type) { - rv = (*handler->ex_handler)(ss, &ss->xtnData, &extension->data); + SECItem tmp = extension->data; + + rv = (*handler->ex_handler)(ss, &ss->xtnData, &tmp); break; } } @@ -960,6 +965,8 @@ ssl3_DestroyExtensionData(TLSExtensionData *xtnData) xtnData->certReqAuthorities.arena = NULL; } PORT_Free(xtnData->advertised); + ssl_FreeEphemeralKeyPair(xtnData->esniPrivateKey); + SECITEM_FreeItem(&xtnData->keyShareExtension, PR_FALSE); } /* Free everything that has been allocated and then reset back to diff --git a/lib/ssl/ssl3ext.h b/lib/ssl/ssl3ext.h index 6d77c7459e..d96b4cffe6 100644 --- a/lib/ssl/ssl3ext.h +++ b/lib/ssl/ssl3ext.h @@ -11,6 +11,8 @@ #include "sslencode.h" +#define TLS13_ESNI_NONCE_SIZE 16 + typedef enum { sni_nametype_hostname } SNINameType; @@ -101,6 +103,14 @@ struct TLSExtensionDataStr { /* The record size limit set by the peer. Our value is kept in ss->opt. */ PRUint16 recordSizeLimit; + + /* ESNI working state */ + SECItem keyShareExtension; + ssl3CipherSuite esniSuite; + sslEphemeralKeyPair *esniPrivateKey; + /* Pointer into |ss->esniKeys->keyShares| */ + TLS13KeyShareEntry *peerEsniShare; + PRUint8 esniNonce[TLS13_ESNI_NONCE_SIZE]; }; typedef struct TLSExtensionStr { diff --git a/lib/ssl/ssl3exthandle.c b/lib/ssl/ssl3exthandle.c index dfedf636ad..a2d83fa97a 100644 --- a/lib/ssl/ssl3exthandle.c +++ b/lib/ssl/ssl3exthandle.c @@ -15,30 +15,40 @@ #include "selfencrypt.h" #include "ssl3ext.h" #include "ssl3exthandle.h" +#include "tls13esni.h" #include "tls13exthandle.h" /* For tls13_ServerSendStatusRequestXtn. */ +PRBool +ssl_ShouldSendSNIExtension(const sslSocket *ss, const char *url) +{ + PRNetAddr netAddr; + + /* must have a hostname */ + if (!url || !url[0]) { + return PR_FALSE; + } + /* must not be an IPv4 or IPv6 address */ + if (PR_SUCCESS == PR_StringToNetAddr(url, &netAddr)) { + /* is an IP address (v4 or v6) */ + return PR_FALSE; + } + + return PR_TRUE; +} + /* Format an SNI extension, using the name from the socket's URL, * unless that name is a dotted decimal string. * Used by client and server. */ SECStatus -ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, - sslBuffer *buf, PRBool *added) +ssl3_ClientFormatServerNameXtn(const sslSocket *ss, const char *url, + TLSExtensionData *xtnData, + sslBuffer *buf) { unsigned int len; - PRNetAddr netAddr; SECStatus rv; - /* must have a hostname */ - if (!ss->url || !ss->url[0]) { - return SECSuccess; - } - /* must not be an IPv4 or IPv6 address */ - if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) { - /* is an IP address (v4 or v6) */ - return SECSuccess; - } - len = PORT_Strlen(ss->url); + len = PORT_Strlen(url); /* length of server_name_list */ rv = sslBuffer_AppendNumber(buf, len + 3, 2); if (rv != SECSuccess) { @@ -50,7 +60,33 @@ ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, return SECFailure; } /* HostName (length and value) */ - rv = sslBuffer_AppendVariable(buf, (const PRUint8 *)ss->url, len, 2); + rv = sslBuffer_AppendVariable(buf, (const PRUint8 *)url, len, 2); + if (rv != SECSuccess) { + return SECFailure; + } + + return SECSuccess; +} + +SECStatus +ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, + sslBuffer *buf, PRBool *added) +{ + SECStatus rv; + + const char *url = ss->url; + + /* We only make an ESNI private key if we are going to + * send ESNI. */ + if (ss->xtnData.esniPrivateKey != NULL) { + url = ss->esniKeys->dummySni; + } + + if (!ssl_ShouldSendSNIExtension(ss, url)) { + return SECSuccess; + } + + rv = ssl3_ClientFormatServerNameXtn(ss, url, xtnData, buf); if (rv != SECSuccess) { return SECFailure; } @@ -59,7 +95,6 @@ ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, return SECSuccess; } -/* Handle an incoming SNI extension. */ SECStatus ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data) @@ -72,6 +107,13 @@ ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, return SECSuccess; /* ignore extension */ } + if (ssl3_ExtensionNegotiated(ss, ssl_tls13_encrypted_sni_xtn)) { + /* If we already have ESNI, make sure we don't overwrite + * the value. */ + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); + return SECSuccess; + } + /* Server side - consume client data and register server sender. */ /* do not parse the data if don't have user extension handling function. */ if (!ss->sniSocketConfig) { diff --git a/lib/ssl/ssl3exthandle.h b/lib/ssl/ssl3exthandle.h index eaf7f0081c..3e9b418cfe 100644 --- a/lib/ssl/ssl3exthandle.h +++ b/lib/ssl/ssl3exthandle.h @@ -91,6 +91,10 @@ SECStatus ssl3_HandleExtendedMasterSecretXtn(const sslSocket *ss, SECItem *data); SECStatus ssl3_ProcessSessionTicketCommon(sslSocket *ss, const SECItem *ticket, /* out */ SECItem *appToken); +PRBool ssl_ShouldSendSNIExtension(const sslSocket *ss, const char *url); +SECStatus ssl3_ClientFormatServerNameXtn(const sslSocket *ss, const char *url, + TLSExtensionData *xtnData, + sslBuffer *buf); SECStatus ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, sslBuffer *buf, PRBool *added); diff --git a/lib/ssl/sslerr.h b/lib/ssl/sslerr.h index 518a2b8875..98247afb73 100644 --- a/lib/ssl/sslerr.h +++ b/lib/ssl/sslerr.h @@ -264,6 +264,9 @@ typedef enum { SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR = (SSL_ERROR_BASE + 173), SSL_ERROR_RX_MALFORMED_DTLS_ACK = (SSL_ERROR_BASE + 174), SSL_ERROR_DH_KEY_TOO_LONG = (SSL_ERROR_BASE + 175), + SSL_ERROR_RX_MALFORMED_ESNI_KEYS = (SSL_ERROR_BASE + 176), + SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION = (SSL_ERROR_BASE + 177), + SSL_ERROR_MISSING_ESNI_EXTENSION = (SSL_ERROR_BASE + 178), SSL_ERROR_END_OF_LIST /* let the c compiler determine the value of this. */ } SSLErrorCodes; #endif /* NO_SECURITY_ERROR_ENUM */ diff --git a/lib/ssl/sslexp.h b/lib/ssl/sslexp.h index 08654f8854..15adba4d89 100644 --- a/lib/ssl/sslexp.h +++ b/lib/ssl/sslexp.h @@ -452,8 +452,65 @@ typedef SECStatus(PR_CALLBACK *SSLResumptionTokenCallback)( (PRFileDesc * _fd, PRUint32 _size), \ (fd, size)) -/* Deprecated experimental APIs */ +/* Set the ESNI key pair on a socket (server side) + * + * fd -- the socket + * record/recordLen -- the encoded DNS record (not base64) + * + * Important: the suites that are advertised in the record must + * be configured on, or this call will fail. + */ +#define SSL_SetESNIKeyPair(fd, \ + privKey, record, recordLen) \ + SSL_EXPERIMENTAL_API("SSL_SetESNIKeyPair", \ + (PRFileDesc * _fd, \ + SECKEYPrivateKey * _privKey, \ + const PRUint8 *_record, unsigned int _recordLen), \ + (fd, privKey, \ + record, recordLen)) +/* Set the ESNI keys on a client + * + * fd -- the socket + * ensikeys/esniKeysLen -- the ESNI key structure (not base64) + * dummyESNI -- the dummy ESNI to use (if any) + */ +#define SSL_EnableESNI(fd, esniKeys, esniKeysLen, dummySNI) \ + SSL_EXPERIMENTAL_API("SSL_EnableESNI", \ + (PRFileDesc * _fd, \ + const PRUint8 *_esniKeys, \ + unsigned int _esniKeysLen, \ + const char *_dummySNI), \ + (fd, esniKeys, esniKeysLen, dummySNI)) + +/* + * Generate an encoded ESNIKeys structure (presumably server side). + * + * cipherSuites -- the cipher suites that can be used + * cipherSuitesCount -- the number of suites in cipherSuites + * group -- the named group this key corresponds to + * pubKey -- the public key for the key pair + * pad -- the length to pad to + * notBefore/notAfter -- validity range + * out/outlen/maxlen -- where to output the data + */ +#define SSL_EncodeESNIKeys(cipherSuites, cipherSuiteCount, \ + group, pubKey, pad, notBefore, notAfter, \ + out, outlen, maxlen) \ + SSL_EXPERIMENTAL_API("SSL_EncodeESNIKeys", \ + (PRUint16 * _cipherSuites, \ + unsigned int _cipherSuiteCount, \ + SSLNamedGroup _group, \ + SECKEYPublicKey *_pubKey, \ + PRUint16 _pad, \ + PRUint64 _notBefore, PRUint64 _notAfter, \ + PRUint8 *_out, unsigned int *_outlen, \ + unsigned int _maxlen), \ + (cipherSuites, cipherSuiteCount, \ + group, pubKey, pad, notBefore, notAfter, \ + out, outlen, maxlen)) + +/* Deprecated experimental APIs */ #define SSL_UseAltServerHelloType(fd, enable) SSL_DEPRECATED_EXPERIMENTAL_API SEC_END_PROTOS diff --git a/lib/ssl/sslimpl.h b/lib/ssl/sslimpl.h index 4419a83e70..59d2c3cb19 100644 --- a/lib/ssl/sslimpl.h +++ b/lib/ssl/sslimpl.h @@ -36,6 +36,10 @@ typedef struct sslSocketStr sslSocket; typedef struct sslNamedGroupDefStr sslNamedGroupDef; +typedef struct sslEsniKeysStr sslEsniKeys; +typedef struct sslEphemeralKeyPairStr sslEphemeralKeyPair; +typedef struct TLS13KeyShareEntryStr TLS13KeyShareEntry; + #include "sslencode.h" #include "sslexp.h" #include "ssl3ext.h" @@ -559,11 +563,11 @@ typedef struct DTLSQueuedMessageStr { PRUint16 len; /* The data length */ } DTLSQueuedMessage; -typedef struct TLS13KeyShareEntryStr { +struct TLS13KeyShareEntryStr { PRCList link; /* The linked list link */ const sslNamedGroupDef *group; /* The group for the entry */ SECItem key_exchange; /* The share itself */ -} TLS13KeyShareEntry; +}; typedef struct TLS13EarlyDataStr { PRCList link; /* The linked list link */ @@ -805,11 +809,11 @@ struct sslKeyPairStr { PRInt32 refCount; /* use PR_Atomic calls for this. */ }; -typedef struct { +struct sslEphemeralKeyPairStr { PRCList link; const sslNamedGroupDef *group; sslKeyPair *keys; -} sslEphemeralKeyPair; +}; struct ssl3DHParamsStr { SSLNamedGroup name; @@ -1066,6 +1070,10 @@ struct sslSocketStr { /* Whether we are doing stream or datagram mode */ SSLProtocolVariant protocolVariant; + + /* The information from the ESNI keys record + * (also the private key for the server). */ + sslEsniKeys *esniKeys; }; struct sslSelfEncryptKeysStr { @@ -1170,6 +1178,7 @@ extern int ssl_Do1stHandshake(sslSocket *ss); extern SECStatus ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive); +extern void ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial); extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server); extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, const char *urlSvrName); @@ -1499,7 +1508,7 @@ extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, sslKeyPair *serverKeys); extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss); extern SECStatus ssl_ImportECDHKeyShare( - sslSocket *ss, SECKEYPublicKey *peerKey, + SECKEYPublicKey *peerKey, PRUint8 *b, PRUint32 length, const sslNamedGroupDef *curve); extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, @@ -1564,6 +1573,12 @@ extern void ssl_FreePRSocket(PRFileDesc *fd); * various ciphers */ extern unsigned int ssl3_config_match_init(sslSocket *); +/* Return PR_TRUE if suite is usable. This if the suite is permitted by policy, + * enabled, has a certificate (as needed), has a viable key agreement method, is + * usable with the negotiated TLS version, and is otherwise usable. */ +PRBool ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy, + const SSLVersionRange *vrange, const sslSocket *ss); + /* calls for accessing wrapping keys across processes. */ extern SECStatus ssl_GetWrappingKey(unsigned int symWrapMechIndex, unsigned int wrapKeyIndex, @@ -1593,6 +1608,8 @@ extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit); extern SECStatus ssl_FreeSessionCacheLocks(void); CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg); +SECStatus ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites, + PRUint16 version, PRUint16 *suitep); SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites, PRBool initHashes); SECStatus ssl3_InitHandshakeHashes(sslSocket *ss); @@ -1640,6 +1657,9 @@ PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss, SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret); const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite); +const ssl3CipherSuiteCfg *ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, + const ssl3CipherSuiteCfg *suites); + SECStatus ssl3_SelectServerCert(sslSocket *ss); SECStatus ssl_PickSignatureScheme(sslSocket *ss, CERTCertificate *cert, diff --git a/lib/ssl/sslsock.c b/lib/ssl/sslsock.c index 85551b125c..9caae0ec2c 100644 --- a/lib/ssl/sslsock.c +++ b/lib/ssl/sslsock.c @@ -18,6 +18,7 @@ #include "private/pprio.h" #include "nss.h" #include "pk11pqg.h" +#include "tls13esni.h" static const sslSocketOps ssl_default_ops = { /* No SSL. */ ssl_DefConnect, @@ -361,6 +362,13 @@ ssl_DupSocket(sslSocket *os) ss->resumptionTokenCallback = os->resumptionTokenCallback; ss->resumptionTokenContext = os->resumptionTokenContext; + if (os->esniKeys) { + ss->esniKeys = tls13_CopyESNIKeys(os->esniKeys); + if (!ss->esniKeys) { + goto loser; + } + } + /* Create security data */ rv = ssl_CopySecurityInfo(ss, os); if (rv != SECSuccess) { @@ -446,6 +454,8 @@ ssl_DestroySocketContents(sslSocket *ss) ssl_ClearPRCList(&ss->ssl3.hs.dtlsSentHandshake, NULL); ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL); + + tls13_DestroyESNIKeys(ss->esniKeys); } /* @@ -3772,6 +3782,10 @@ ssl_GetKeyPairRef(sslKeyPair *keyPair) void ssl_FreeKeyPair(sslKeyPair *keyPair) { + if (!keyPair) { + return; + } + PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); if (!newCount) { SECKEY_DestroyPrivateKey(keyPair->privKey); @@ -3831,6 +3845,10 @@ ssl_CopyEphemeralKeyPair(sslEphemeralKeyPair *keyPair) void ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair) { + if (!keyPair) { + return; + } + ssl_FreeKeyPair(keyPair->keys); PR_REMOVE_LINK(&keyPair->link); PORT_Free(keyPair); @@ -3938,6 +3956,8 @@ ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) PR_INIT_CLIST(&ss->ssl3.hs.dtlsRcvdHandshake); dtls_InitTimers(ss); + ss->esniKeys = NULL; + if (makeLocks) { rv = ssl_MakeLocks(ss); if (rv != SECSuccess) @@ -4014,6 +4034,9 @@ struct { EXP(SetResumptionToken), EXP(GetResumptionTokenInfo), EXP(DestroyResumptionTokenInfo), + EXP(SetESNIKeyPair), + EXP(EncodeESNIKeys), + EXP(EnableESNI), #endif { "", NULL } }; diff --git a/lib/ssl/sslspec.c b/lib/ssl/sslspec.c index 7833eeab69..f2e72a4ec4 100644 --- a/lib/ssl/sslspec.c +++ b/lib/ssl/sslspec.c @@ -203,7 +203,7 @@ ssl_CipherSpecAddRef(ssl3CipherSpec *spec) SSL_GETPID(), SPEC_DIR(spec), spec, spec->refCt)); } -static void +void ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial) { PK11_FreeSymKey(keyMaterial->key); diff --git a/lib/ssl/sslt.h b/lib/ssl/sslt.h index 978f88642f..bd32a6e180 100644 --- a/lib/ssl/sslt.h +++ b/lib/ssl/sslt.h @@ -454,7 +454,8 @@ typedef enum { ssl_tls13_key_share_xtn = 51, ssl_next_proto_nego_xtn = 13172, /* Deprecated. */ ssl_renegotiation_info_xtn = 0xff01, - ssl_tls13_short_header_xtn = 0xff03 /* Deprecated. */ + ssl_tls13_short_header_xtn = 0xff03, /* Deprecated. */ + ssl_tls13_encrypted_sni_xtn = 0xffce, } SSLExtensionType; /* This is the old name for the supported_groups extensions. */ diff --git a/lib/ssl/tls13con.c b/lib/ssl/tls13con.c index ee7ff69d86..cef287a2c9 100644 --- a/lib/ssl/tls13con.c +++ b/lib/ssl/tls13con.c @@ -21,6 +21,7 @@ #include "tls13hkdf.h" #include "tls13con.h" #include "tls13err.h" +#include "tls13esni.h" #include "tls13exthandle.h" #include "tls13hashstate.h" @@ -133,21 +134,6 @@ const char keylogLabelExporterSecret[] = "EXPORTER_SECRET"; PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <= SSL_LIBRARY_VERSION_TLS_1_3); -/* Use this instead of FATAL_ERROR when no alert shall be sent. */ -#define LOG_ERROR(ss, prError) \ - do { \ - SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \ - SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \ - PORT_SetError(prError); \ - } while (0) - -/* Log an error and generate an alert because something is irreparably wrong. */ -#define FATAL_ERROR(ss, prError, desc) \ - do { \ - LOG_ERROR(ss, prError); \ - tls13_FatalError(ss, prError, desc); \ - } while (0) - void tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc) { @@ -355,16 +341,16 @@ tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes, } SECStatus -tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef) +tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef, + sslEphemeralKeyPair **keyPair) { SECStatus rv; - sslEphemeralKeyPair *keyPair = NULL; const ssl3DHParams *params; PORT_Assert(groupDef); switch (groupDef->keaType) { case ssl_kea_ecdh: - rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, &keyPair); + rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, keyPair); if (rv != SECSuccess) { return SECFailure; } @@ -372,7 +358,7 @@ tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef) case ssl_kea_dh: params = ssl_GetDHEParams(groupDef); PORT_Assert(params->name != ssl_grp_ffdhe_custom); - rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair); + rv = ssl_CreateDHEKeyPair(groupDef, params, keyPair); if (rv != SECSuccess) { return SECFailure; } @@ -383,10 +369,23 @@ tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef) return SECFailure; } - PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); return rv; } +SECStatus +tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef) +{ + sslEphemeralKeyPair *keyPair = NULL; + SECStatus rv; + + rv = tls13_CreateKeyShare(ss, groupDef, &keyPair); + if (rv != SECSuccess) { + return SECFailure; + } + PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); + return SECSuccess; +} + SECStatus SSL_SendAdditionalKeyShares(PRFileDesc *fd, unsigned int count) { @@ -414,20 +413,26 @@ tls13_SetupClientHello(sslSocket *ss) NewSessionTicket *session_ticket = NULL; sslSessionID *sid = ss->sec.ci.sid; unsigned int numShares = 0; + SECStatus rv; PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)); + /* Do encrypted SNI. This may create a key share as a side effect. */ + rv = tls13_ClientSetupESNI(ss); + if (rv != SECSuccess) { + return SECFailure; + } + /* Select the first enabled group. * TODO(ekr@rtfm.com): be smarter about offering the group * that the other side negotiated if we are resuming. */ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) { - SECStatus rv; if (!ss->namedGroupPreferences[i]) { continue; } - rv = tls13_CreateKeyShare(ss, ss->namedGroupPreferences[i]); + rv = tls13_AddKeyShare(ss, ss->namedGroupPreferences[i]); if (rv != SECSuccess) { return SECFailure; } @@ -456,8 +461,6 @@ tls13_SetupClientHello(sslSocket *ss) } if (ss->statelessResume) { - SECStatus rv; - PORT_Assert(ss->sec.ci.sid); rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid); if (rv != SECSuccess) { @@ -487,7 +490,7 @@ tls13_SetupClientHello(sslSocket *ss) } static SECStatus -tls13_ImportDHEKeyShare(sslSocket *ss, SECKEYPublicKey *peerKey, +tls13_ImportDHEKeyShare(SECKEYPublicKey *peerKey, PRUint8 *b, PRUint32 length, SECKEYPublicKey *pubKey) { @@ -518,15 +521,18 @@ tls13_ImportDHEKeyShare(sslSocket *ss, SECKEYPublicKey *peerKey, return SECSuccess; } -static SECStatus +SECStatus tls13_HandleKeyShare(sslSocket *ss, TLS13KeyShareEntry *entry, - sslKeyPair *keyPair) + sslKeyPair *keyPair, + SSLHashType hash, + PK11SymKey **out) { PORTCheapArenaPool arena; SECKEYPublicKey *peerKey; CK_MECHANISM_TYPE mechanism; PRErrorCode errorCode; + PK11SymKey *key; SECStatus rv; int keySize = 0; @@ -541,14 +547,14 @@ tls13_HandleKeyShare(sslSocket *ss, switch (entry->group->keaType) { case ssl_kea_ecdh: - rv = ssl_ImportECDHKeyShare(ss, peerKey, + rv = ssl_ImportECDHKeyShare(peerKey, entry->key_exchange.data, entry->key_exchange.len, entry->group); mechanism = CKM_ECDH1_DERIVE; break; case ssl_kea_dh: - rv = tls13_ImportDHEKeyShare(ss, peerKey, + rv = tls13_ImportDHEKeyShare(peerKey, entry->key_exchange.data, entry->key_exchange.len, keyPair->pubKey); @@ -563,13 +569,14 @@ tls13_HandleKeyShare(sslSocket *ss, goto loser; } - ss->ssl3.hs.dheSecret = PK11_PubDeriveWithKDF( + key = PK11_PubDeriveWithKDF( keyPair->privKey, peerKey, PR_FALSE, NULL, NULL, mechanism, - tls13_GetHkdfMechanism(ss), CKA_DERIVE, keySize, CKD_NULL, NULL, NULL); - if (!ss->ssl3.hs.dheSecret) { + tls13_GetHkdfMechanismForHash(hash), CKA_DERIVE, keySize, CKD_NULL, NULL, NULL); + if (!key) { ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE); goto loser; } + *out = key; PORT_DestroyCheapArena(&arena); return SECSuccess; @@ -2027,7 +2034,7 @@ tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare) tls13_SetKeyExchangeType(ss, peerShare->group); /* Generate our key */ - rv = tls13_CreateKeyShare(ss, peerShare->group); + rv = tls13_AddKeyShare(ss, peerShare->group); if (rv != SECSuccess) { return rv; } @@ -2047,7 +2054,9 @@ tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare) return SECFailure; /* Error code set already. */ } - rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys); + rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys, + tls13_GetHash(ss), + &ss->ssl3.hs.dheSecret); return rv; /* Error code set already. */ } @@ -2647,7 +2656,9 @@ tls13_HandleServerKeyShare(sslSocket *ss) PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group)); - rv = tls13_HandleKeyShare(ss, entry, keyPair->keys); + rv = tls13_HandleKeyShare(ss, entry, keyPair->keys, + tls13_GetHash(ss), + &ss->ssl3.hs.dheSecret); if (rv != SECSuccess) return SECFailure; /* Error code set by caller. */ @@ -3203,6 +3214,21 @@ tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec) SSL_GETPID(), ss->fd, spec, spec->recordVersion)); } +SSLAEADCipher +tls13_GetAead(const ssl3BulkCipherDef *cipherDef) +{ + switch (cipherDef->calg) { + case ssl_calg_aes_gcm: + return tls13_AESGCM; + case ssl_calg_chacha20: + return tls13_ChaCha20Poly1305; + default: + PORT_Assert(PR_FALSE); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return NULL; + } +} + static SECStatus tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) { @@ -3226,16 +3252,9 @@ tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) SSL_GETPID(), ss->fd, suite)); spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite)); - switch (spec->cipherDef->calg) { - case ssl_calg_aes_gcm: - spec->aead = tls13_AESGCM; - break; - case ssl_calg_chacha20: - spec->aead = tls13_ChaCha20Poly1305; - break; - default: - PORT_Assert(0); - return SECFailure; + spec->aead = tls13_GetAead(spec->cipherDef); + if (!spec->aead) { + return SECFailure; } if (spec->epoch == TrafficKeyEarlyApplicationData) { @@ -3417,9 +3436,30 @@ tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes) return SECFailure; } +TLS13KeyShareEntry * +tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o) +{ + TLS13KeyShareEntry *n; + + PORT_Assert(o); + n = PORT_ZNew(TLS13KeyShareEntry); + if (!n) { + return NULL; + } + + if (SECSuccess != SECITEM_CopyItem(NULL, &n->key_exchange, &o->key_exchange)) { + PORT_Free(n); + } + n->group = o->group; + return n; +} + void tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer) { + if (!offer) { + return; + } SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE); PORT_ZFree(offer, sizeof(*offer)); } @@ -3540,7 +3580,7 @@ tls13_AESGCM(ssl3KeyMaterial *keys, CK_GCM_PARAMS gcmParams; unsigned char nonce[12]; - PORT_Assert(additionalDataLen > 8); + PORT_Assert(additionalDataLen >= 8); memset(&gcmParams, 0, sizeof(gcmParams)); gcmParams.pIv = nonce; gcmParams.ulIvLen = sizeof(nonce); @@ -3617,7 +3657,23 @@ tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length) ss->xtnData.nextProto.data = NULL; ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT; } - rv = ssl3_HandleExtensions(ss, &b, &length, ssl_hs_encrypted_extensions); + + rv = ssl3_ParseExtensions(ss, &b, &length); + if (rv != SECSuccess) { + return SECFailure; /* Error code set below */ + } + + /* If we sent ESNI, check the nonce. */ + if (ss->xtnData.esniPrivateKey) { + PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_sni_xtn)); + rv = tls13_ClientCheckEsniXtn(ss); + if (rv != SECSuccess) { + return SECFailure; + } + } + + /* Handle the rest of the extensions. */ + rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions); if (rv != SECSuccess) { return SECFailure; /* Error code set below */ } @@ -4749,7 +4805,8 @@ static const struct { { ssl_tls13_certificate_authorities_xtn, _M1(certificate_request) }, { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello, hello_retry_request) }, - { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) } + { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) }, + { ssl_tls13_encrypted_sni_xtn, _M2(client_hello, encrypted_extensions) } }; tls13ExtensionStatus diff --git a/lib/ssl/tls13con.h b/lib/ssl/tls13con.h index 215a7282dc..f3b2cb3905 100644 --- a/lib/ssl/tls13con.h +++ b/lib/ssl/tls13con.h @@ -85,9 +85,17 @@ SECStatus tls13_ConstructHelloRetryRequest(sslSocket *ss, sslBuffer *buffer); SECStatus tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *b, PRUint32 length); +SECStatus tls13_HandleKeyShare(sslSocket *ss, + TLS13KeyShareEntry *entry, + sslKeyPair *keyPair, + SSLHashType hash, + PK11SymKey **out); +TLS13KeyShareEntry *tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o); void tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *entry); void tls13_DestroyKeyShares(PRCList *list); -SECStatus tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef); +SECStatus tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef, + sslEphemeralKeyPair **keyPair); +SECStatus tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef); void tls13_DestroyEarlyData(PRCList *list); SECStatus tls13_SetAlertCipherSpec(sslSocket *ss); tls13ExtensionStatus tls13_ExtensionStatus(PRUint16 extension, @@ -121,6 +129,22 @@ SECStatus tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request, PRBool buffer); SECStatus SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate); PRBool tls13_MaybeTls13(sslSocket *ss); +SSLAEADCipher tls13_GetAead(const ssl3BulkCipherDef *cipherDef); void tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec); +/* Use this instead of FATAL_ERROR when no alert shall be sent. */ +#define LOG_ERROR(ss, prError) \ + do { \ + SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \ + SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \ + PORT_SetError(prError); \ + } while (0) + +/* Log an error and generate an alert because something is irreparably wrong. */ +#define FATAL_ERROR(ss, prError, desc) \ + do { \ + LOG_ERROR(ss, prError); \ + tls13_FatalError(ss, prError, desc); \ + } while (0) + #endif /* __tls13con_h_ */ diff --git a/lib/ssl/tls13esni.c b/lib/ssl/tls13esni.c new file mode 100644 index 0000000000..e2328769bc --- /dev/null +++ b/lib/ssl/tls13esni.c @@ -0,0 +1,844 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. */ + +#define TLS13_ESNI_VERSION 0xff01 + +/* + * struct { + * uint16 version; + * uint8 checksum[4]; + * KeyShareEntry keys<4..2^16-1>; + * CipherSuite cipher_suites<2..2^16-2>; + * uint16 padded_length; + * uint64 not_before; + * uint64 not_after; + * Extension extensions<0..2^16-1>; + * } ESNIKeys; + */ +#include "nss.h" +#include "pk11func.h" +#include "ssl.h" +#include "sslproto.h" +#include "sslimpl.h" +#include "ssl3exthandle.h" +#include "tls13esni.h" +#include "tls13exthandle.h" +#include "tls13hkdf.h" + +const char kHkdfPurposeEsniKey[] = "esni key"; +const char kHkdfPurposeEsniIv[] = "esni iv"; + +void +tls13_DestroyESNIKeys(sslEsniKeys *keys) +{ + if (!keys) { + return; + } + SECITEM_FreeItem(&keys->data, PR_FALSE); + PORT_Free((void *)keys->dummySni); + tls13_DestroyKeyShares(&keys->keyShares); + ssl_FreeEphemeralKeyPair(keys->privKey); + SECITEM_FreeItem(&keys->suites, PR_FALSE); + PORT_ZFree(keys, sizeof(sslEsniKeys)); +} + +sslEsniKeys * +tls13_CopyESNIKeys(sslEsniKeys *okeys) +{ + sslEsniKeys *nkeys; + SECStatus rv; + + PORT_Assert(okeys); + + nkeys = PORT_ZNew(sslEsniKeys); + if (!nkeys) { + return NULL; + } + PR_INIT_CLIST(&nkeys->keyShares); + rv = SECITEM_CopyItem(NULL, &nkeys->data, &okeys->data); + if (rv != SECSuccess) { + goto loser; + } + if (okeys->dummySni) { + nkeys->dummySni = PORT_Strdup(okeys->dummySni); + if (!nkeys->dummySni) { + goto loser; + } + } + for (PRCList *cur_p = PR_LIST_HEAD(&okeys->keyShares); + cur_p != &okeys->keyShares; + cur_p = PR_NEXT_LINK(cur_p)) { + TLS13KeyShareEntry *copy = tls13_CopyKeyShareEntry( + (TLS13KeyShareEntry *)cur_p); + if (!copy) { + goto loser; + } + PR_APPEND_LINK(©->link, &nkeys->keyShares); + } + if (okeys->privKey) { + nkeys->privKey = ssl_CopyEphemeralKeyPair(okeys->privKey); + if (!nkeys->privKey) { + goto loser; + } + } + rv = SECITEM_CopyItem(NULL, &nkeys->suites, &okeys->suites); + if (rv != SECSuccess) { + goto loser; + } + nkeys->paddedLength = okeys->paddedLength; + nkeys->notBefore = okeys->notBefore; + nkeys->notAfter = okeys->notAfter; + return nkeys; + +loser: + tls13_DestroyESNIKeys(nkeys); + return NULL; +} + +/* Checksum is a 4-byte array. */ +static SECStatus +tls13_ComputeESNIKeysChecksum(const PRUint8 *buf, unsigned int len, + PRUint8 *checksum) +{ + SECItem copy; + SECStatus rv; + PRUint8 sha256[32]; + + rv = SECITEM_MakeItem(NULL, ©, buf, len); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Stomp the checksum. */ + PORT_Memset(copy.data + 2, 0, 4); + + rv = PK11_HashBuf(ssl3_HashTypeToOID(ssl_hash_sha256), + sha256, + copy.data, copy.len); + SECITEM_FreeItem(©, PR_FALSE); + if (rv != SECSuccess) { + return SECFailure; + } + PORT_Memcpy(checksum, sha256, 4); + return SECSuccess; +} + +static SECStatus +tls13_DecodeESNIKeys(SECItem *data, sslEsniKeys **keysp) +{ + SECStatus rv; + sslReadBuffer tmp; + PRUint64 tmpn; + sslEsniKeys *keys; + PRUint8 checksum[4]; + sslReader rdr = SSL_READER(data->data, data->len); + + rv = sslRead_ReadNumber(&rdr, 2, &tmpn); + if (rv != SECSuccess) { + return SECFailure; + } + if (tmpn != TLS13_ESNI_VERSION) { + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + return SECFailure; + } + keys = PORT_ZNew(sslEsniKeys); + if (!keys) { + return SECFailure; + } + PR_INIT_CLIST(&keys->keyShares); + + /* Make a copy. */ + rv = SECITEM_CopyItem(NULL, &keys->data, data); + if (rv != SECSuccess) { + goto loser; + } + + rv = tls13_ComputeESNIKeysChecksum(data->data, data->len, checksum); + if (rv != SECSuccess) { + goto loser; + } + + /* Read and check checksum. */ + rv = sslRead_Read(&rdr, 4, &tmp); + if (rv != SECSuccess) { + goto loser; + } + + if (0 != NSS_SecureMemcmp(tmp.buf, checksum, 4)) { + goto loser; + } + + /* Parse the key shares. */ + rv = sslRead_ReadVariable(&rdr, 2, &tmp); + if (rv != SECSuccess) { + goto loser; + } + + sslReader rdr2 = SSL_READER(tmp.buf, tmp.len); + while (SSL_READER_REMAINING(&rdr2)) { + TLS13KeyShareEntry *ks = NULL; + + rv = tls13_DecodeKeyShareEntry(&rdr2, &ks); + if (rv != SECSuccess) { + goto loser; + } + + if (ks) { + PR_APPEND_LINK(&ks->link, &keys->keyShares); + } + } + + /* Parse cipher suites. */ + rv = sslRead_ReadVariable(&rdr, 2, &tmp); + if (rv != SECSuccess) { + goto loser; + } + /* This can't be odd. */ + if (tmp.len & 1) { + goto loser; + } + rv = SECITEM_MakeItem(NULL, &keys->suites, (PRUint8 *)tmp.buf, tmp.len); + if (rv != SECSuccess) { + goto loser; + } + + /* Padded Length */ + rv = sslRead_ReadNumber(&rdr, 2, &tmpn); + if (rv != SECSuccess) { + goto loser; + } + keys->paddedLength = (PRUint16)tmpn; + + /* Not Before */ + rv = sslRead_ReadNumber(&rdr, 8, &keys->notBefore); + if (rv != SECSuccess) { + goto loser; + } + + /* Not After */ + rv = sslRead_ReadNumber(&rdr, 8, &keys->notAfter); + if (rv != SECSuccess) { + goto loser; + } + + /* Extensions, which we ignore. */ + rv = sslRead_ReadVariable(&rdr, 2, &tmp); + if (rv != SECSuccess) { + goto loser; + } + + /* Check that this is empty. */ + if (SSL_READER_REMAINING(&rdr) > 0) { + goto loser; + } + + *keysp = keys; + return SECSuccess; + +loser: + tls13_DestroyESNIKeys(keys); + PORT_SetError(SSL_ERROR_RX_MALFORMED_ESNI_KEYS); + + return SECFailure; +} + +/* Encode an ESNI keys structure. We only allow one key + * share. */ +SECStatus +SSLExp_EncodeESNIKeys(PRUint16 *cipherSuites, unsigned int cipherSuiteCount, + SSLNamedGroup group, SECKEYPublicKey *pubKey, + PRUint16 pad, PRUint64 notBefore, PRUint64 notAfter, + PRUint8 *out, unsigned int *outlen, unsigned int maxlen) +{ + unsigned int savedOffset; + SECStatus rv; + sslBuffer b = SSL_BUFFER_EMPTY; + + rv = sslBuffer_AppendNumber(&b, TLS13_ESNI_VERSION, 2); + if (rv != SECSuccess) { + goto loser; + } + + rv = sslBuffer_Skip(&b, 4, &savedOffset); + if (rv != SECSuccess) { + goto loser; + } + + /* Length of vector. */ + rv = sslBuffer_AppendNumber( + &b, tls13_SizeOfKeyShareEntry(pubKey), 2); + if (rv != SECSuccess) { + goto loser; + } + + /* Our one key share. */ + rv = tls13_EncodeKeyShareEntry(&b, group, pubKey); + if (rv != SECSuccess) { + goto loser; + } + + /* Cipher suites. */ + rv = sslBuffer_AppendNumber(&b, cipherSuiteCount * 2, 2); + if (rv != SECSuccess) { + goto loser; + } + for (unsigned int i = 0; i < cipherSuiteCount; i++) { + rv = sslBuffer_AppendNumber(&b, cipherSuites[i], 2); + if (rv != SECSuccess) { + goto loser; + } + } + + /* Padding Length. Fixed for now. */ + rv = sslBuffer_AppendNumber(&b, pad, 2); + if (rv != SECSuccess) { + goto loser; + } + + /* Start time. */ + rv = sslBuffer_AppendNumber(&b, notBefore, 8); + if (rv != SECSuccess) { + goto loser; + } + + /* End time. */ + rv = sslBuffer_AppendNumber(&b, notAfter, 8); + if (rv != SECSuccess) { + goto loser; + } + + /* No extensions. */ + rv = sslBuffer_AppendNumber(&b, 0, 2); + if (rv != SECSuccess) { + goto loser; + } + + rv = tls13_ComputeESNIKeysChecksum(SSL_BUFFER_BASE(&b), + SSL_BUFFER_LEN(&b), + SSL_BUFFER_BASE(&b) + 2); + if (rv != SECSuccess) { + PORT_Assert(PR_FALSE); + goto loser; + } + + if (SSL_BUFFER_LEN(&b) > maxlen) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + PORT_Memcpy(out, SSL_BUFFER_BASE(&b), SSL_BUFFER_LEN(&b)); + *outlen = SSL_BUFFER_LEN(&b); + + sslBuffer_Clear(&b); + return SECSuccess; +loser: + sslBuffer_Clear(&b); + return SECFailure; +} + +SECStatus +SSLExp_SetESNIKeyPair(PRFileDesc *fd, + SECKEYPrivateKey *privKey, + const PRUint8 *record, unsigned int recordLen) +{ + sslSocket *ss; + SECStatus rv; + sslEsniKeys *keys = NULL; + SECKEYPublicKey *pubKey = NULL; + SECItem data = { siBuffer, CONST_CAST(PRUint8, record), recordLen }; + PLArenaPool *arena = NULL; + + ss = ssl_FindSocket(fd); + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in %s", + SSL_GETPID(), fd, __FUNCTION__)); + return SECFailure; + } + + rv = tls13_DecodeESNIKeys(&data, &keys); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Check the cipher suites. */ + (void)ssl3_config_match_init(ss); + /* Make sure the cipher suite is OK. */ + SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3, + SSL_LIBRARY_VERSION_TLS_1_3 }; + + sslReader csrdr = SSL_READER(keys->suites.data, + keys->suites.len); + while (SSL_READER_REMAINING(&csrdr)) { + PRUint64 asuite; + + rv = sslRead_ReadNumber(&csrdr, 2, &asuite); + if (rv != SECSuccess) { + goto loser; + } + const ssl3CipherSuiteCfg *suiteCfg = + ssl_LookupCipherSuiteCfg(asuite, ss->cipherSuites); + if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) { + /* Illegal suite. */ + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + } + + if (PR_CLIST_IS_EMPTY(&keys->keyShares)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + if (PR_PREV_LINK(&keys->keyShares) != PR_NEXT_LINK(&keys->keyShares)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + TLS13KeyShareEntry *entry = (TLS13KeyShareEntry *)PR_LIST_HEAD( + &keys->keyShares); + if (entry->group->keaType != ssl_kea_ecdh) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + goto loser; + } + pubKey = PORT_ArenaZNew(arena, SECKEYPublicKey); + if (!pubKey) { + goto loser; + } + pubKey->arena = arena; + arena = NULL; /* From here, this will be destroyed with the pubkey. */ + /* Dummy PKCS11 values because this key isn't on a slot. */ + pubKey->pkcs11Slot = NULL; + pubKey->pkcs11ID = CK_INVALID_HANDLE; + rv = ssl_ImportECDHKeyShare(pubKey, + entry->key_exchange.data, + entry->key_exchange.len, + entry->group); + if (rv != SECSuccess) { + goto loser; + } + + privKey = SECKEY_CopyPrivateKey(privKey); + if (!privKey) { + goto loser; + } + keys->privKey = ssl_NewEphemeralKeyPair(entry->group, privKey, pubKey); + if (!keys->privKey) { + goto loser; + } + pubKey = NULL; + ss->esniKeys = keys; + return SECSuccess; + +loser: + PORT_FreeArena(arena, PR_FALSE); + SECKEY_DestroyPublicKey(pubKey); + tls13_DestroyESNIKeys(keys); + return SECFailure; +} + +SECStatus +SSLExp_EnableESNI(PRFileDesc *fd, + const PRUint8 *esniKeys, + unsigned int esniKeysLen, + const char *dummySNI) +{ + sslSocket *ss; + sslEsniKeys *keys = NULL; + SECItem data = { siBuffer, CONST_CAST(PRUint8, esniKeys), esniKeysLen }; + SECStatus rv; + + ss = ssl_FindSocket(fd); + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in %s", + SSL_GETPID(), fd, __FUNCTION__)); + return SECFailure; + } + + rv = tls13_DecodeESNIKeys(&data, &keys); + if (rv != SECSuccess) { + return SECFailure; + } + + if (dummySNI) { + keys->dummySni = PORT_Strdup(dummySNI); + if (!keys->dummySni) { + tls13_DestroyESNIKeys(keys); + return SECFailure; + } + } + + /* Delete in case it was set before. */ + tls13_DestroyESNIKeys(ss->esniKeys); + ss->esniKeys = keys; + + return SECSuccess; +} + +/* + * struct { + * opaque record_digest<0..2^16-1>; + * KeyShareEntry esni_key_share; + * Random client_hello_random; + * } ESNIContents; + */ +SECStatus +tls13_ComputeESNIKeys(const sslSocket *ss, + TLS13KeyShareEntry *entry, + sslKeyPair *keyPair, + const ssl3CipherSuiteDef *suite, + const PRUint8 *esniKeysHash, + const PRUint8 *keyShareBuf, + unsigned int keyShareBufLen, + const PRUint8 *clientRandom, + ssl3KeyMaterial *keyMat) +{ + PK11SymKey *Z = NULL; + PK11SymKey *Zx = NULL; + SECStatus ret = SECFailure; + PRUint8 esniContentsBuf[256]; /* Just big enough. */ + sslBuffer esniContents = SSL_BUFFER(esniContentsBuf); + PRUint8 hash[64]; + const ssl3BulkCipherDef *cipherDef = ssl_GetBulkCipherDef(suite); + size_t keySize = cipherDef->key_size; + size_t ivSize = cipherDef->iv_size + + cipherDef->explicit_nonce_size; /* This isn't always going to + * work, but it does for + * AES-GCM */ + unsigned int hashSize = tls13_GetHashSizeForHash(suite->prf_hash); + SECStatus rv; + + rv = tls13_HandleKeyShare(CONST_CAST(sslSocket, ss), entry, keyPair, + suite->prf_hash, &Z); + if (rv != SECSuccess) { + goto loser; + } + rv = tls13_HkdfExtract(NULL, Z, suite->prf_hash, &Zx); + if (rv != SECSuccess) { + goto loser; + } + + /* Encode ESNIContents. */ + rv = sslBuffer_AppendVariable(&esniContents, + esniKeysHash, hashSize, 2); + if (rv != SECSuccess) { + goto loser; + } + rv = sslBuffer_Append(&esniContents, keyShareBuf, keyShareBufLen); + if (rv != SECSuccess) { + goto loser; + } + rv = sslBuffer_Append(&esniContents, clientRandom, SSL3_RANDOM_LENGTH); + if (rv != SECSuccess) { + goto loser; + } + + PORT_Assert(hashSize <= sizeof(hash)); + rv = PK11_HashBuf(ssl3_HashTypeToOID(suite->prf_hash), + hash, + SSL_BUFFER_BASE(&esniContents), + SSL_BUFFER_LEN(&esniContents)); + ; + if (rv != SECSuccess) { + goto loser; + } + + rv = tls13_HkdfExpandLabel(Zx, suite->prf_hash, + hash, hashSize, + kHkdfPurposeEsniKey, strlen(kHkdfPurposeEsniKey), + ssl3_Alg2Mech(cipherDef->calg), + keySize, + &keyMat->key); + if (rv != SECSuccess) { + goto loser; + } + rv = tls13_HkdfExpandLabelRaw(Zx, suite->prf_hash, + hash, hashSize, + kHkdfPurposeEsniIv, strlen(kHkdfPurposeEsniIv), + keyMat->iv, ivSize); + if (rv != SECSuccess) { + goto loser; + } + + ret = SECSuccess; + +loser: + PK11_FreeSymKey(Z); + PK11_FreeSymKey(Zx); + return ret; +} + +/* Set up ESNI. This generates a private key as a side effect. */ +SECStatus +tls13_ClientSetupESNI(sslSocket *ss) +{ + ssl3CipherSuite suite; + sslEphemeralKeyPair *keyPair; + size_t i; + PRCList *cur; + SECStatus rv; + TLS13KeyShareEntry *share; + const sslNamedGroupDef *group = NULL; + PRTime now = PR_Now() / PR_USEC_PER_SEC; + + if (!ss->esniKeys) { + return SECSuccess; + } + + if ((ss->esniKeys->notBefore > now) || (ss->esniKeys->notAfter < now)) { + return SECSuccess; + } + + /* If we're not sending SNI, don't send ESNI. */ + if (!ssl_ShouldSendSNIExtension(ss, ss->url)) { + return SECSuccess; + } + + /* Pick the group. */ + for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) { + for (cur = PR_NEXT_LINK(&ss->esniKeys->keyShares); + cur != &ss->esniKeys->keyShares; + cur = PR_NEXT_LINK(cur)) { + if (!ss->namedGroupPreferences[i]) { + continue; + } + share = (TLS13KeyShareEntry *)cur; + if (share->group->name == ss->namedGroupPreferences[i]->name) { + group = ss->namedGroupPreferences[i]; + break; + } + } + } + + if (!group) { + /* No compatible group. */ + return SECSuccess; + } + + rv = ssl3_NegotiateCipherSuiteInner(ss, &ss->esniKeys->suites, + SSL_LIBRARY_VERSION_TLS_1_3, &suite); + if (rv != SECSuccess) { + return SECSuccess; + } + + rv = tls13_CreateKeyShare(ss, group, &keyPair); + if (rv != SECSuccess) { + return SECFailure; + } + + ss->xtnData.esniPrivateKey = keyPair; + ss->xtnData.esniSuite = suite; + ss->xtnData.peerEsniShare = share; + + return SECSuccess; +} + +/* + * struct { + * CipherSuite suite; + * KeyShareEntry key_share; + * opaque record_digest<0..2^16-1>; + * opaque encrypted_sni<0..2^16-1>; + * } ClientEncryptedSNI; + * + * struct { + * ServerNameList sni; + * opaque zeros[ESNIKeys.padded_length - length(sni)]; + * } PaddedServerNameList; + * + * struct { + * uint8 nonce[16]; + * PaddedServerNameList realSNI; + * } ClientESNIInner; + */ +SECStatus +tls13_FormatEsniAADInput(sslBuffer *aadInput, + PRUint8 *keyShare, unsigned int keyShareLen) +{ + SECStatus rv; + + /* 8 bytes of 0 for the sequence number. */ + rv = sslBuffer_AppendNumber(aadInput, 0, 8); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Key share. */ + PORT_Assert(keyShareLen > 0); + rv = sslBuffer_Append(aadInput, keyShare, keyShareLen); + if (rv != SECSuccess) { + return SECFailure; + } + + return SECSuccess; +} + +static SECStatus +tls13_ServerGetEsniAEAD(const sslSocket *ss, PRUint64 suite, + const ssl3CipherSuiteDef **suiteDefp, + SSLAEADCipher *aeadp) +{ + SECStatus rv; + const ssl3CipherSuiteDef *suiteDef; + SSLAEADCipher aead; + + /* Check against the suite list for ESNI */ + PRBool csMatch = PR_FALSE; + sslReader csrdr = SSL_READER(ss->esniKeys->suites.data, + ss->esniKeys->suites.len); + while (SSL_READER_REMAINING(&csrdr)) { + PRUint64 asuite; + + rv = sslRead_ReadNumber(&csrdr, 2, &asuite); + if (rv != SECSuccess) { + return SECFailure; + } + if (asuite == suite) { + csMatch = PR_TRUE; + break; + } + } + if (!csMatch) { + return SECFailure; + } + + suiteDef = ssl_LookupCipherSuiteDef(suite); + PORT_Assert(suiteDef); + if (!suiteDef) { + return SECFailure; + } + aead = tls13_GetAead(ssl_GetBulkCipherDef(suiteDef)); + if (!aead) { + return SECFailure; + } + + *suiteDefp = suiteDef; + *aeadp = aead; + return SECSuccess; +} + +SECStatus +tls13_ServerDecryptEsniXtn(const sslSocket *ss, PRUint8 *in, unsigned int inLen, + PRUint8 *out, int *outLen, int maxLen) +{ + sslReader rdr = SSL_READER(in, inLen); + PRUint64 suite; + const ssl3CipherSuiteDef *suiteDef; + SSLAEADCipher aead = NULL; + TLSExtension *keyShareExtension; + TLS13KeyShareEntry *entry = NULL; + ssl3KeyMaterial keyMat = { NULL }; + + sslBuffer aadInput = SSL_BUFFER_EMPTY; + const PRUint8 *keyShareBuf; + sslReadBuffer buf; + unsigned int keyShareBufLen; + PRUint8 hash[64]; + SECStatus rv; + + /* Read the cipher suite. */ + rv = sslRead_ReadNumber(&rdr, 2, &suite); + if (rv != SECSuccess) { + goto loser; + } + + /* Find the AEAD */ + rv = tls13_ServerGetEsniAEAD(ss, suite, &suiteDef, &aead); + if (rv != SECSuccess) { + goto loser; + } + + /* Note where the KeyShare starts. */ + keyShareBuf = SSL_READER_CURRENT(&rdr); + rv = tls13_DecodeKeyShareEntry(&rdr, &entry); + if (rv != SECSuccess) { + goto loser; + } + keyShareBufLen = SSL_READER_CURRENT(&rdr) - keyShareBuf; + if (!entry || entry->group->name != ss->esniKeys->privKey->group->name) { + goto loser; + } + + /* The hash of the ESNIKeys structure. */ + rv = sslRead_ReadVariable(&rdr, 2, &buf); + if (rv != SECSuccess) { + goto loser; + } + + /* Check that the hash matches. */ + unsigned int hashLen = tls13_GetHashSizeForHash(suiteDef->prf_hash); + PORT_Assert(hashLen <= sizeof(hash)); + rv = PK11_HashBuf(ssl3_HashTypeToOID(suiteDef->prf_hash), + hash, + ss->esniKeys->data.data, ss->esniKeys->data.len); + if (rv != SECSuccess) { + goto loser; + } + + if (buf.len != hashLen) { + /* This is malformed. */ + goto loser; + } + if (0 != NSS_SecureMemcmp(hash, buf.buf, hashLen)) { + goto loser; + } + + rv = tls13_ComputeESNIKeys(ss, entry, + ss->esniKeys->privKey->keys, + suiteDef, + hash, keyShareBuf, keyShareBufLen, + ((sslSocket *)ss)->ssl3.hs.client_random, + &keyMat); + if (rv != SECSuccess) { + goto loser; + } + + /* Read the ciphertext. */ + rv = sslRead_ReadVariable(&rdr, 2, &buf); + if (rv != SECSuccess) { + goto loser; + } + + /* Check that this is empty. */ + if (SSL_READER_REMAINING(&rdr) > 0) { + goto loser; + } + + /* Find the key share extension. */ + keyShareExtension = ssl3_FindExtension(CONST_CAST(sslSocket, ss), + ssl_tls13_key_share_xtn); + if (!keyShareExtension) { + goto loser; + } + rv = tls13_FormatEsniAADInput(&aadInput, + keyShareExtension->data.data, + keyShareExtension->data.len); + if (rv != SECSuccess) { + goto loser; + } + + rv = aead(&keyMat, PR_TRUE /* Decrypt */, + out, outLen, maxLen, + buf.buf, buf.len, + SSL_BUFFER_BASE(&aadInput), + SSL_BUFFER_LEN(&aadInput)); + sslBuffer_Clear(&aadInput); + if (rv != SECSuccess) { + goto loser; + } + + ssl_DestroyKeyMaterial(&keyMat); + tls13_DestroyKeyShareEntry(entry); + return SECSuccess; + +loser: + FATAL_ERROR(CONST_CAST(sslSocket, ss), SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION, illegal_parameter); + ssl_DestroyKeyMaterial(&keyMat); /* Safe because zeroed. */ + if (entry) { + tls13_DestroyKeyShareEntry(entry); + } + return SECFailure; +} diff --git a/lib/ssl/tls13esni.h b/lib/ssl/tls13esni.h new file mode 100644 index 0000000000..6c52c99525 --- /dev/null +++ b/lib/ssl/tls13esni.h @@ -0,0 +1,51 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is PRIVATE to SSL. + * + * 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/. */ + +#ifndef __tls13esni_h_ +#define __tls13esni_h_ + +struct sslEsniKeysStr { + SECItem data; /* The encoded record. */ + sslEphemeralKeyPair *privKey; + const char *dummySni; + PRCList keyShares; /* List of TLS13KeyShareEntry */ + SECItem suites; + PRUint16 paddedLength; + PRUint64 notBefore; + PRUint64 notAfter; +}; + +SECStatus SSLExp_SetESNIKeyPair(PRFileDesc *fd, + SECKEYPrivateKey *privKey, + const PRUint8 *record, unsigned int recordLen); + +SECStatus SSLExp_EnableESNI(PRFileDesc *fd, const PRUint8 *esniKeys, + unsigned int esniKeysLen, const char *dummySNI); +SECStatus SSLExp_EncodeESNIKeys(PRUint16 *cipherSuites, unsigned int cipherSuiteCount, + SSLNamedGroup group, SECKEYPublicKey *pubKey, + PRUint16 pad, PRUint64 notBefore, PRUint64 notAfter, + PRUint8 *out, unsigned int *outlen, unsigned int maxlen); +sslEsniKeys *tls13_CopyESNIKeys(sslEsniKeys *okeys); +void tls13_DestroyESNIKeys(sslEsniKeys *keys); +SECStatus tls13_ClientSetupESNI(sslSocket *ss); +SECStatus tls13_ComputeESNIKeys(const sslSocket *ss, + TLS13KeyShareEntry *entry, + sslKeyPair *keyPair, + const ssl3CipherSuiteDef *suite, + const PRUint8 *esniKeysHash, + const PRUint8 *keyShareBuf, + unsigned int keyShareBufLen, + const PRUint8 *clientRandom, + ssl3KeyMaterial *keyMat); +SECStatus tls13_FormatEsniAADInput(sslBuffer *aadInput, + PRUint8 *keyShare, unsigned int keyShareLen); + +SECStatus tls13_ServerDecryptEsniXtn(const sslSocket *ss, PRUint8 *in, unsigned int inLen, + PRUint8 *out, int *outLen, int maxLen); + +#endif diff --git a/lib/ssl/tls13exthandle.c b/lib/ssl/tls13exthandle.c index b155a9c462..cc0ce02b56 100644 --- a/lib/ssl/tls13exthandle.c +++ b/lib/ssl/tls13exthandle.c @@ -12,6 +12,7 @@ #include "pk11pub.h" #include "ssl3ext.h" #include "ssl3exthandle.h" +#include "tls13esni.h" #include "tls13exthandle.h" SECStatus @@ -71,7 +72,7 @@ tls13_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, * * opaque point <1..2^8-1>; */ -static PRUint32 +PRUint32 tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey) { /* Size = NamedGroup(2) + length(2) + opaque share */ @@ -86,14 +87,14 @@ tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey) return 0; } -static SECStatus -tls13_EncodeKeyShareEntry(sslBuffer *buf, const sslEphemeralKeyPair *keyPair) +SECStatus +tls13_EncodeKeyShareEntry(sslBuffer *buf, SSLNamedGroup group, + SECKEYPublicKey *pubKey) { SECStatus rv; - SECKEYPublicKey *pubKey = keyPair->keys->pubKey; unsigned int size = tls13_SizeOfKeyShareEntry(pubKey); - rv = sslBuffer_AppendNumber(buf, keyPair->group->name, 2); + rv = sslBuffer_AppendNumber(buf, group, 2); if (rv != SECSuccess) return rv; rv = sslBuffer_AppendNumber(buf, size - 4, 2); @@ -123,6 +124,7 @@ tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, { SECStatus rv; PRCList *cursor; + unsigned int extStart; unsigned int lengthOffset; if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) { @@ -134,6 +136,8 @@ tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, SSL_TRC(3, ("%d: TLS13[%d]: send client key share xtn", SSL_GETPID(), ss->fd)); + extStart = SSL_BUFFER_LEN(buf); + /* Save the offset to the length. */ rv = sslBuffer_Skip(buf, 2, &lengthOffset); if (rv != SECSuccess) { @@ -144,7 +148,9 @@ tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, cursor != &ss->ephemeralKeyPairs; cursor = PR_NEXT_LINK(cursor)) { sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor; - rv = tls13_EncodeKeyShareEntry(buf, keyPair); + rv = tls13_EncodeKeyShareEntry(buf, + keyPair->group->name, + keyPair->keys->pubKey); if (rv != SECSuccess) { return SECFailure; } @@ -154,50 +160,62 @@ tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, return SECFailure; } + rv = SECITEM_MakeItem(NULL, &xtnData->keyShareExtension, + SSL_BUFFER_BASE(buf) + extStart, + SSL_BUFFER_LEN(buf) - extStart); + if (rv != SECSuccess) { + return SECFailure; + } + *added = PR_TRUE; return SECSuccess; } -static SECStatus -tls13_HandleKeyShareEntry(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data) +SECStatus +tls13_DecodeKeyShareEntry(sslReader *rdr, TLS13KeyShareEntry **ksp) { SECStatus rv; - PRUint32 group; + PRUint64 group; const sslNamedGroupDef *groupDef; TLS13KeyShareEntry *ks = NULL; - SECItem share = { siBuffer, NULL, 0 }; + sslReadBuffer share; - rv = ssl3_ExtConsumeHandshakeNumber(ss, &group, 2, &data->data, &data->len); + rv = sslRead_ReadNumber(rdr, 2, &group); if (rv != SECSuccess) { - PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); goto loser; } groupDef = ssl_LookupNamedGroup(group); - rv = ssl3_ExtConsumeHandshakeVariable(ss, &share, 2, &data->data, - &data->len); + rv = sslRead_ReadVariable(rdr, 2, &share); if (rv != SECSuccess) { goto loser; } + + /* This has to happen here because we want to consume + * the entire entry even if the group is unknown + * or disabled. */ /* If the group is disabled, continue. */ if (!groupDef) { return SECSuccess; } ks = PORT_ZNew(TLS13KeyShareEntry); - if (!ks) + if (!ks) { goto loser; + } ks->group = groupDef; - rv = SECITEM_CopyItem(NULL, &ks->key_exchange, &share); - if (rv != SECSuccess) + rv = SECITEM_MakeItem(NULL, &ks->key_exchange, + share.buf, share.len); + if (rv != SECSuccess) { goto loser; + } - PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares); + *ksp = ks; return SECSuccess; loser: - if (ks) - tls13_DestroyKeyShareEntry(ks); + tls13_DestroyKeyShareEntry(ks); + return SECFailure; } /* Handle an incoming KeyShare extension at the client and copy to @@ -209,6 +227,7 @@ tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, { SECStatus rv; PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares)); + TLS13KeyShareEntry *ks = NULL; PORT_Assert(!ss->sec.isServer); @@ -221,16 +240,19 @@ tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension", SSL_GETPID(), ss->fd)); - rv = tls13_HandleKeyShareEntry(ss, xtnData, data); - if (rv != SECSuccess) { + sslReader rdr = SSL_READER(data->data, data->len); + rv = tls13_DecodeKeyShareEntry(&rdr, &ks); + if ((rv != SECSuccess) || !ks) { + ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter); PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); return SECFailure; } - if (data->len) { + if (SSL_READER_REMAINING(&rdr)) { PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); return SECFailure; } + PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares); return SECSuccess; } @@ -273,7 +295,7 @@ tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData, ssl_FreeEphemeralKeyPairs(CONST_CAST(sslSocket, ss)); /* And replace with our new share. */ - rv = tls13_CreateKeyShare(CONST_CAST(sslSocket, ss), group); + rv = tls13_AddKeyShare(CONST_CAST(sslSocket, ss), group); if (rv != SECSuccess) { ssl3_ExtSendAlert(ss, alert_fatal, internal_error); PORT_SetError(SEC_ERROR_KEYGEN_FAIL); @@ -315,12 +337,24 @@ tls13_ServerHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, goto loser; } - while (data->len) { - rv = tls13_HandleKeyShareEntry(ss, xtnData, data); - if (rv != SECSuccess) + sslReader rdr = SSL_READER(data->data, data->len); + while (SSL_READER_REMAINING(&rdr)) { + TLS13KeyShareEntry *ks = NULL; + rv = tls13_DecodeKeyShareEntry(&rdr, &ks); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); goto loser; + } + if (ks) { + /* |ks| == NULL if this is an unknown group. */ + PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares); + } } + /* Keep track of negotiated extensions. */ + xtnData->negotiated[xtnData->numNegotiated++] = + ssl_tls13_key_share_xtn; + return SECSuccess; loser: @@ -342,7 +376,8 @@ tls13_ServerSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs); - rv = tls13_EncodeKeyShareEntry(buf, keyPair); + rv = tls13_EncodeKeyShareEntry(buf, keyPair->group->name, + keyPair->keys->pubKey); if (rv != SECSuccess) { return SECFailure; } @@ -1060,3 +1095,273 @@ tls13_ServerSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData, *added = PR_TRUE; return SECSuccess; } + +SECStatus +tls13_ClientSendEsniXtn(const sslSocket *ss, TLSExtensionData *xtnData, + sslBuffer *buf, PRBool *added) +{ + SECStatus rv; + PRUint8 sniBuf[1024]; + PRUint8 hash[64]; + sslBuffer sni = SSL_BUFFER(sniBuf); + const ssl3CipherSuiteDef *suiteDef; + ssl3KeyMaterial keyMat; + SSLAEADCipher aead; + PRUint8 outBuf[1024]; + int outLen; + unsigned int sniStart; + unsigned int sniLen; + sslBuffer aadInput = SSL_BUFFER_EMPTY; + unsigned int keyShareBufStart; + unsigned int keyShareBufLen; + + PORT_Memset(&keyMat, 0, sizeof(keyMat)); + + if (!ss->xtnData.esniPrivateKey) { + return SECSuccess; + } + + /* nonce */ + rv = PK11_GenerateRandom( + (unsigned char *)xtnData->esniNonce, sizeof(xtnData->esniNonce)); + if (rv != SECSuccess) { + return SECFailure; + } + rv = sslBuffer_Append(&sni, xtnData->esniNonce, sizeof(xtnData->esniNonce)); + if (rv != SECSuccess) { + return SECFailure; + } + + /* sni */ + sniStart = SSL_BUFFER_LEN(&sni); + rv = ssl3_ClientFormatServerNameXtn(ss, ss->url, xtnData, &sni); + if (rv != SECSuccess) { + return SECFailure; + } + + sniLen = SSL_BUFFER_LEN(&sni) - sniStart; + /* Padding. */ + if (ss->esniKeys->paddedLength > sniLen) { + unsigned int paddingRequired = ss->esniKeys->paddedLength - sniLen; + while (paddingRequired--) { + rv = sslBuffer_AppendNumber(&sni, 0, 1); + if (rv != SECSuccess) { + return SECFailure; + } + } + } + + suiteDef = ssl_LookupCipherSuiteDef(xtnData->esniSuite); + PORT_Assert(suiteDef); + if (!suiteDef) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + aead = tls13_GetAead(ssl_GetBulkCipherDef(suiteDef)); + if (!aead) { + return SECFailure; + } + + /* Format the first part of the extension so we have the + * encoded KeyShareEntry. */ + rv = sslBuffer_AppendNumber(buf, xtnData->esniSuite, 2); + if (rv != SECSuccess) { + return SECFailure; + } + keyShareBufStart = SSL_BUFFER_LEN(buf); + rv = tls13_EncodeKeyShareEntry(buf, + xtnData->esniPrivateKey->group->name, + xtnData->esniPrivateKey->keys->pubKey); + if (rv != SECSuccess) { + return SECFailure; + } + keyShareBufLen = SSL_BUFFER_LEN(buf) - keyShareBufStart; + + if (tls13_GetHashSizeForHash(suiteDef->prf_hash) > sizeof(hash)) { + PORT_Assert(PR_FALSE); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + rv = PK11_HashBuf(ssl3_HashTypeToOID(suiteDef->prf_hash), + hash, + ss->esniKeys->data.data, + ss->esniKeys->data.len); + if (rv != SECSuccess) { + PORT_Assert(PR_FALSE); + return SECFailure; + } + + rv = sslBuffer_AppendVariable(buf, hash, + tls13_GetHashSizeForHash(suiteDef->prf_hash), 2); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Compute the ESNI keys. */ + rv = tls13_ComputeESNIKeys(ss, xtnData->peerEsniShare, + xtnData->esniPrivateKey->keys, + suiteDef, + hash, + SSL_BUFFER_BASE(buf) + keyShareBufStart, + keyShareBufLen, + CONST_CAST(PRUint8, ss->ssl3.hs.client_random), + &keyMat); + if (rv != SECSuccess) { + return SECFailure; + } + + rv = tls13_FormatEsniAADInput(&aadInput, + xtnData->keyShareExtension.data, + xtnData->keyShareExtension.len); + if (rv != SECSuccess) { + ssl_DestroyKeyMaterial(&keyMat); + return SECFailure; + } + /* Now encrypt. */ + rv = aead(&keyMat, PR_FALSE /* Encrypt */, + outBuf, &outLen, sizeof(outBuf), + SSL_BUFFER_BASE(&sni), + SSL_BUFFER_LEN(&sni), + SSL_BUFFER_BASE(&aadInput), + SSL_BUFFER_LEN(&aadInput)); + ssl_DestroyKeyMaterial(&keyMat); + sslBuffer_Clear(&aadInput); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Encode the rest. */ + rv = sslBuffer_AppendVariable(buf, outBuf, outLen, 2); + if (rv != SECSuccess) { + return SECFailure; + } + + *added = PR_TRUE; + return SECSuccess; +} + +static SECStatus +tls13_ServerSendEsniXtn(const sslSocket *ss, TLSExtensionData *xtnData, + sslBuffer *buf, PRBool *added) +{ + SECStatus rv; + + rv = sslBuffer_Append(buf, xtnData->esniNonce, sizeof(xtnData->esniNonce)); + if (rv != SECSuccess) { + return SECFailure; + } + + *added = PR_TRUE; + return SECSuccess; +} + +SECStatus +tls13_ServerHandleEsniXtn(const sslSocket *ss, TLSExtensionData *xtnData, + SECItem *data) +{ + sslReadBuffer buf; + PRUint8 *plainText = NULL; + int ptLen; + SECStatus rv; + + /* If we are doing < TLS 1.3, then ignore this. */ + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + return SECSuccess; + } + + if (!ss->esniKeys) { + /* Apparently we used to be configured for ESNI, but + * no longer. This violates the spec, or the client is + * broken. */ + return SECFailure; + } + + plainText = PORT_ZAlloc(data->len); + if (!plainText) { + return SECFailure; + } + rv = tls13_ServerDecryptEsniXtn(ss, data->data, data->len, + plainText, &ptLen, data->len); + if (rv) { + goto loser; + } + + /* Read out the interior extension. */ + sslReader sniRdr = SSL_READER(plainText, ptLen); + + rv = sslRead_Read(&sniRdr, sizeof(xtnData->esniNonce), &buf); + if (rv != SECSuccess) { + goto loser; + } + PORT_Memcpy(xtnData->esniNonce, buf.buf, sizeof(xtnData->esniNonce)); + + /* We need to capture the whole block with the length. */ + SECItem sniItem = { siBuffer, (unsigned char *)SSL_READER_CURRENT(&sniRdr), 0 }; + rv = sslRead_ReadVariable(&sniRdr, 2, &buf); + if (rv != SECSuccess) { + goto loser; + } + sniItem.len = buf.len + 2; + + /* Check the padding. Note we don't need to do this in constant time + * because it's inside the AEAD boundary. */ + /* TODO(ekr@rtfm.com): check that the padding is the right length. */ + PRUint64 tmp; + while (SSL_READER_REMAINING(&sniRdr)) { + rv = sslRead_ReadNumber(&sniRdr, 1, &tmp); + if (tmp != 0) { + goto loser; + } + } + + rv = ssl3_HandleServerNameXtn(ss, xtnData, &sniItem); + if (rv != SECSuccess) { + goto loser; + } + + rv = ssl3_RegisterExtensionSender(ss, xtnData, + ssl_tls13_encrypted_sni_xtn, + tls13_ServerSendEsniXtn); + if (rv != SECSuccess) { + goto loser; + } + + /* Keep track of negotiated extensions. */ + xtnData->negotiated[xtnData->numNegotiated++] = + ssl_tls13_encrypted_sni_xtn; + + PORT_ZFree(plainText, data->len); + return SECSuccess; +loser: + PORT_ZFree(plainText, data->len); + return SECFailure; +} + +/* Function to check the extension. We don't install a handler here + * because we need to check for the presence of the extension as + * well and it's easier to do it in one place. */ +SECStatus +tls13_ClientCheckEsniXtn(sslSocket *ss) +{ + TLSExtension *esniExtension = + ssl3_FindExtension(ss, ssl_tls13_encrypted_sni_xtn); + if (!esniExtension) { + FATAL_ERROR(ss, SSL_ERROR_MISSING_ESNI_EXTENSION, missing_extension); + return SECFailure; + } + + if (esniExtension->data.len != sizeof(ss->xtnData.esniNonce)) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION, illegal_parameter); + return SECFailure; + } + + if (0 != NSS_SecureMemcmp(esniExtension->data.data, + ss->xtnData.esniNonce, + sizeof(ss->xtnData.esniNonce))) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION, illegal_parameter); + return SECFailure; + } + + return SECSuccess; +} diff --git a/lib/ssl/tls13exthandle.h b/lib/ssl/tls13exthandle.h index edce94d831..dd64b44ff4 100644 --- a/lib/ssl/tls13exthandle.h +++ b/lib/ssl/tls13exthandle.h @@ -84,5 +84,14 @@ SECStatus tls13_ServerSendHrrKeyShareXtn(const sslSocket *ss, SECStatus tls13_ServerSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData, sslBuffer *buf, PRBool *added); +SECStatus tls13_DecodeKeyShareEntry(sslReader *rdr, TLS13KeyShareEntry **ksp); +PRUint32 tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey); +SECStatus tls13_EncodeKeyShareEntry(sslBuffer *buf, SSLNamedGroup group, + SECKEYPublicKey *pubKey); +SECStatus tls13_ClientSendEsniXtn(const sslSocket *ss, TLSExtensionData *xtnData, + sslBuffer *buf, PRBool *added); +SECStatus tls13_ServerHandleEsniXtn(const sslSocket *ss, TLSExtensionData *xtnData, + SECItem *data); +SECStatus tls13_ClientCheckEsniXtn(sslSocket *ss); #endif diff --git a/lib/util/secitem.c b/lib/util/secitem.c index 1e505a9af1..cd69961782 100644 --- a/lib/util/secitem.c +++ b/lib/util/secitem.c @@ -76,10 +76,10 @@ SECITEM_AllocItem(PLArenaPool *arena, SECItem *item, unsigned int len) } SECStatus -SECITEM_MakeItem(PLArenaPool *arena, SECItem *dest, unsigned char *data, +SECITEM_MakeItem(PLArenaPool *arena, SECItem *dest, const unsigned char *data, unsigned int len) { - SECItem it = { siBuffer, data, len }; + SECItem it = { siBuffer, (unsigned char *)data, len }; return SECITEM_CopyItem(arena, dest, &it); } diff --git a/lib/util/secitem.h b/lib/util/secitem.h index 4fb1239382..f7a8241b5d 100644 --- a/lib/util/secitem.h +++ b/lib/util/secitem.h @@ -41,7 +41,7 @@ extern SECItem *SECITEM_AllocItem(PLArenaPool *arena, SECItem *item, * always siBuffer. */ extern SECStatus SECITEM_MakeItem(PLArenaPool *arena, SECItem *dest, - unsigned char *data, unsigned int len); + const unsigned char *data, unsigned int len); /* ** This is a legacy function containing bugs. It doesn't update item->len,