ssl_auth_unittest.cc (91154B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "secerr.h" 8 #include "ssl.h" 9 #include "sslerr.h" 10 #include "sslproto.h" 11 12 extern "C" { 13 // This is not something that should make you happy. 14 #include "libssl_internals.h" 15 } 16 17 #include "gtest_utils.h" 18 #include "nss_scoped_ptrs.h" 19 #include "tls_connect.h" 20 #include "tls_filter.h" 21 #include "tls_parser.h" 22 23 namespace nss_test { 24 25 TEST_P(TlsConnectGeneric, ServerAuthBigRsa) { 26 Reset(TlsAgent::kRsa2048); 27 Connect(); 28 CheckKeys(); 29 } 30 31 TEST_P(TlsConnectGeneric, PeerCertificateChainConsistency) { 32 Reset("rsa_chain"); 33 Connect(); 34 CheckKeys(); 35 client_->CheckPeerChainFunctionConsistency(); 36 server_->CheckPeerChainFunctionConsistency(); 37 } 38 39 TEST_P(TlsConnectGeneric, ServerAuthRsaChain) { 40 Reset("rsa_chain"); 41 Connect(); 42 CheckKeys(); 43 size_t chain_length; 44 EXPECT_TRUE(client_->GetPeerChainLength(&chain_length)); 45 EXPECT_EQ(2UL, chain_length); 46 } 47 48 TEST_P(TlsConnectTls12Plus, ServerAuthRsaPss) { 49 static const SSLSignatureScheme kSignatureSchemePss[] = { 50 ssl_sig_rsa_pss_pss_sha256}; 51 52 Reset(TlsAgent::kServerRsaPss); 53 client_->SetSignatureSchemes(kSignatureSchemePss, 54 PR_ARRAY_SIZE(kSignatureSchemePss)); 55 server_->SetSignatureSchemes(kSignatureSchemePss, 56 PR_ARRAY_SIZE(kSignatureSchemePss)); 57 Connect(); 58 CheckKeys(ssl_auth_rsa_pss, ssl_sig_rsa_pss_pss_sha256); 59 } 60 61 // PSS doesn't work with TLS 1.0 or 1.1 because we can't signal it. 62 TEST_P(TlsConnectPre12, ServerAuthRsaPssFails) { 63 static const SSLSignatureScheme kSignatureSchemePss[] = { 64 ssl_sig_rsa_pss_pss_sha256}; 65 66 Reset(TlsAgent::kServerRsaPss); 67 client_->SetSignatureSchemes(kSignatureSchemePss, 68 PR_ARRAY_SIZE(kSignatureSchemePss)); 69 server_->SetSignatureSchemes(kSignatureSchemePss, 70 PR_ARRAY_SIZE(kSignatureSchemePss)); 71 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 72 server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 73 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 74 } 75 76 // Check that a PSS certificate with no parameters works. 77 TEST_P(TlsConnectTls12Plus, ServerAuthRsaPssNoParameters) { 78 static const SSLSignatureScheme kSignatureSchemePss[] = { 79 ssl_sig_rsa_pss_pss_sha256}; 80 81 Reset("rsa_pss_noparam"); 82 client_->SetSignatureSchemes(kSignatureSchemePss, 83 PR_ARRAY_SIZE(kSignatureSchemePss)); 84 server_->SetSignatureSchemes(kSignatureSchemePss, 85 PR_ARRAY_SIZE(kSignatureSchemePss)); 86 Connect(); 87 CheckKeys(ssl_auth_rsa_pss, ssl_sig_rsa_pss_pss_sha256); 88 } 89 90 TEST_P(TlsConnectGeneric, ServerAuthRsaPssChain) { 91 Reset("rsa_pss_chain"); 92 Connect(); 93 CheckKeys(); 94 size_t chain_length; 95 EXPECT_TRUE(client_->GetPeerChainLength(&chain_length)); 96 EXPECT_EQ(2UL, chain_length); 97 } 98 99 TEST_P(TlsConnectGeneric, ServerAuthRsaCARsaPssChain) { 100 Reset("rsa_ca_rsa_pss_chain"); 101 Connect(); 102 CheckKeys(); 103 size_t chain_length; 104 EXPECT_TRUE(client_->GetPeerChainLength(&chain_length)); 105 EXPECT_EQ(2UL, chain_length); 106 } 107 108 TEST_P(TlsConnectGeneric, ServerAuthRejected) { 109 EnsureTlsSetup(); 110 client_->SetAuthCertificateCallback( 111 [](TlsAgent*, PRBool, PRBool) -> SECStatus { return SECFailure; }); 112 ConnectExpectAlert(client_, kTlsAlertBadCertificate); 113 client_->CheckErrorCode(SSL_ERROR_BAD_CERTIFICATE); 114 server_->CheckErrorCode(SSL_ERROR_BAD_CERT_ALERT); 115 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 116 } 117 118 struct AuthCompleteArgs : public PollTarget { 119 AuthCompleteArgs(const std::shared_ptr<TlsAgent>& a, PRErrorCode c) 120 : agent(a), code(c) {} 121 122 std::shared_ptr<TlsAgent> agent; 123 PRErrorCode code; 124 }; 125 126 static void CallAuthComplete(PollTarget* target, Event event) { 127 EXPECT_EQ(TIMER_EVENT, event); 128 auto args = reinterpret_cast<AuthCompleteArgs*>(target); 129 std::cerr << args->agent->role_str() << ": call SSL_AuthCertificateComplete " 130 << (args->code ? PR_ErrorToName(args->code) : "no error") 131 << std::endl; 132 EXPECT_EQ(SECSuccess, 133 SSL_AuthCertificateComplete(args->agent->ssl_fd(), args->code)); 134 args->agent->Handshake(); // Make the TlsAgent aware of the error. 135 delete args; 136 } 137 138 // Install an AuthCertificateCallback that blocks when called. Then 139 // SSL_AuthCertificateComplete is called on a very short timer. This allows any 140 // processing that might follow the callback to complete. 141 static void SetDeferredAuthCertificateCallback(std::shared_ptr<TlsAgent> agent, 142 PRErrorCode code) { 143 auto args = new AuthCompleteArgs(agent, code); 144 agent->SetAuthCertificateCallback( 145 [args](TlsAgent*, PRBool, PRBool) -> SECStatus { 146 // This can't be 0 or we race the message from the client to the server, 147 // and tests assume that we lose that race. 148 std::shared_ptr<Poller::Timer> timer_handle; 149 Poller::Instance()->SetTimer(1U, args, CallAuthComplete, &timer_handle); 150 return SECWouldBlock; 151 }); 152 } 153 154 TEST_P(TlsConnectTls13, ServerAuthRejectAsync) { 155 SetDeferredAuthCertificateCallback(client_, SEC_ERROR_REVOKED_CERTIFICATE); 156 ConnectExpectAlert(client_, kTlsAlertCertificateRevoked); 157 // We only detect the error here when we attempt to handshake, so all the 158 // client learns is that the handshake has already failed. 159 client_->CheckErrorCode(SSL_ERROR_HANDSHAKE_FAILED); 160 server_->CheckErrorCode(SSL_ERROR_REVOKED_CERT_ALERT); 161 } 162 163 // In TLS 1.2 and earlier, this will result in the client sending its Finished 164 // before learning that the server certificate is bad. That means that the 165 // server will believe that the handshake is complete. 166 TEST_P(TlsConnectGenericPre13, ServerAuthRejectAsync) { 167 SetDeferredAuthCertificateCallback(client_, SEC_ERROR_EXPIRED_CERTIFICATE); 168 client_->ExpectSendAlert(kTlsAlertCertificateExpired); 169 server_->ExpectReceiveAlert(kTlsAlertCertificateExpired); 170 ConnectExpectFailOneSide(TlsAgent::CLIENT); 171 client_->CheckErrorCode(SSL_ERROR_HANDSHAKE_FAILED); 172 173 // The server might not receive the alert that the client sends, which would 174 // cause the test to fail when it cleans up. Reset expectations. 175 server_->ExpectReceiveAlert(kTlsAlertCloseNotify, kTlsAlertWarning); 176 } 177 178 class TlsCertificateRequestContextRecorder : public TlsHandshakeFilter { 179 public: 180 TlsCertificateRequestContextRecorder(const std::shared_ptr<TlsAgent>& a, 181 uint8_t handshake_type) 182 : TlsHandshakeFilter(a, {handshake_type}), buffer_(), filtered_(false) { 183 EnableDecryption(); 184 } 185 186 bool filtered() const { return filtered_; } 187 const DataBuffer& buffer() const { return buffer_; } 188 189 protected: 190 virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header, 191 const DataBuffer& input, 192 DataBuffer* output) { 193 assert(1 < input.len()); 194 size_t len = input.data()[0]; 195 assert(len + 1 < input.len()); 196 buffer_.Assign(input.data() + 1, len); 197 filtered_ = true; 198 return KEEP; 199 } 200 201 private: 202 DataBuffer buffer_; 203 bool filtered_; 204 }; 205 206 using ClientAuthParam = 207 std::tuple<SSLProtocolVariant, uint16_t, ClientAuthCallbackType>; 208 209 class TlsConnectClientAuth 210 : public TlsConnectTestBase, 211 public testing::WithParamInterface<ClientAuthParam> { 212 public: 213 TlsConnectClientAuth() 214 : TlsConnectTestBase(std::get<0>(GetParam()), std::get<1>(GetParam())) {} 215 }; 216 217 // Wrapper classes for tests that target specific versions 218 219 class TlsConnectClientAuth13 : public TlsConnectClientAuth {}; 220 221 class TlsConnectClientAuth12 : public TlsConnectClientAuth {}; 222 223 class TlsConnectClientAuthStream13 : public TlsConnectClientAuth {}; 224 225 class TlsConnectClientAuthPre13 : public TlsConnectClientAuth {}; 226 227 class TlsConnectClientAuth12Plus : public TlsConnectClientAuth {}; 228 229 std::string getClientAuthTestName( 230 testing::TestParamInfo<ClientAuthParam> info) { 231 auto param = info.param; 232 auto variant = std::get<0>(param); 233 auto version = std::get<1>(param); 234 auto callback_type = std::get<2>(param); 235 236 std::string output = std::string(); 237 switch (variant) { 238 case ssl_variant_stream: 239 output.append("TLS"); 240 break; 241 case ssl_variant_datagram: 242 output.append("DTLS"); 243 break; 244 } 245 output.append(VersionString(version).replace(1, 1, "")); 246 switch (callback_type) { 247 case ClientAuthCallbackType::kAsyncImmediate: 248 output.append("AsyncImmediate"); 249 break; 250 case ClientAuthCallbackType::kAsyncDelay: 251 output.append("AsyncDelay"); 252 break; 253 case ClientAuthCallbackType::kSync: 254 output.append("Sync"); 255 break; 256 case ClientAuthCallbackType::kNone: 257 output.append("None"); 258 break; 259 } 260 return output; 261 } 262 263 auto kClientAuthCallbacks = testing::Values( 264 ClientAuthCallbackType::kAsyncImmediate, 265 ClientAuthCallbackType::kAsyncDelay, ClientAuthCallbackType::kSync, 266 ClientAuthCallbackType::kNone); 267 268 INSTANTIATE_TEST_SUITE_P( 269 ClientAuthGenericStream, TlsConnectClientAuth, 270 testing::Combine(TlsConnectTestBase::kTlsVariantsStream, 271 TlsConnectTestBase::kTlsVAll, kClientAuthCallbacks), 272 getClientAuthTestName); 273 274 INSTANTIATE_TEST_SUITE_P( 275 ClientAuthGenericDatagram, TlsConnectClientAuth, 276 testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram, 277 TlsConnectTestBase::kTlsV11Plus, kClientAuthCallbacks), 278 getClientAuthTestName); 279 280 INSTANTIATE_TEST_SUITE_P(ClientAuth13, TlsConnectClientAuth13, 281 testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 282 TlsConnectTestBase::kTlsV13, 283 kClientAuthCallbacks), 284 getClientAuthTestName); 285 286 INSTANTIATE_TEST_SUITE_P( 287 ClientAuth13, TlsConnectClientAuthStream13, 288 testing::Combine(TlsConnectTestBase::kTlsVariantsStream, 289 TlsConnectTestBase::kTlsV13, kClientAuthCallbacks), 290 getClientAuthTestName); 291 292 INSTANTIATE_TEST_SUITE_P(ClientAuth12, TlsConnectClientAuth12, 293 testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 294 TlsConnectTestBase::kTlsV12, 295 kClientAuthCallbacks), 296 getClientAuthTestName); 297 298 INSTANTIATE_TEST_SUITE_P( 299 ClientAuthPre13Stream, TlsConnectClientAuthPre13, 300 testing::Combine(TlsConnectTestBase::kTlsVariantsStream, 301 TlsConnectTestBase::kTlsV10ToV12, kClientAuthCallbacks), 302 getClientAuthTestName); 303 304 INSTANTIATE_TEST_SUITE_P( 305 ClientAuthPre13Datagram, TlsConnectClientAuthPre13, 306 testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram, 307 TlsConnectTestBase::kTlsV11V12, kClientAuthCallbacks), 308 getClientAuthTestName); 309 310 INSTANTIATE_TEST_SUITE_P(ClientAuth12Plus, TlsConnectClientAuth12Plus, 311 testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 312 TlsConnectTestBase::kTlsV12Plus, 313 kClientAuthCallbacks), 314 getClientAuthTestName); 315 316 TEST_P(TlsConnectClientAuth, ClientAuth) { 317 EnsureTlsSetup(); 318 client_->SetupClientAuth(std::get<2>(GetParam()), true); 319 server_->RequestClientAuth(true); 320 Connect(); 321 CheckKeys(); 322 client_->CheckClientAuthCompleted(); 323 } 324 325 TEST_F(TlsConnectStreamTls13, ClientAuthWithMultipleTickets) { 326 client_->SetupClientAuth(); 327 server_->RequestClientAuth(true); 328 329 ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3); 330 ConfigureSessionCache(RESUME_BOTH, RESUME_BOTH); 331 332 auto cb = [](PRFileDesc* fd, const PRUint8* ticket, unsigned int ticket_len, 333 void* arg) -> SECStatus { return SECSuccess; }; 334 EXPECT_EQ(SECSuccess, 335 SSL_SetResumptionTokenCallback(client_->ssl_fd(), cb, nullptr)); 336 337 Connect(); 338 SendReceive(50); 339 CheckKeys(); 340 // An automatic ticket has already been sent. This sends another one. 341 EXPECT_EQ(SECSuccess, SSL_SendSessionTicket(server_->ssl_fd(), nullptr, 0)); 342 SendReceive(100); 343 } 344 345 // All stream only tests; PostHandshakeAuth isn't supported for DTLS. 346 347 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuth) { 348 EnsureTlsSetup(); 349 client_->SetupClientAuth(std::get<2>(GetParam()), true); 350 auto capture_cert_req = MakeTlsFilter<TlsCertificateRequestContextRecorder>( 351 server_, kTlsHandshakeCertificateRequest); 352 auto capture_certificate = 353 MakeTlsFilter<TlsCertificateRequestContextRecorder>( 354 client_, kTlsHandshakeCertificate); 355 client_->SetOption(SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE); 356 size_t called = 0; 357 server_->SetAuthCertificateCallback( 358 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 359 called++; 360 return SECSuccess; 361 }); 362 Connect(); 363 EXPECT_EQ(0U, called); 364 EXPECT_FALSE(capture_cert_req->filtered()); 365 EXPECT_FALSE(capture_certificate->filtered()); 366 // Send CertificateRequest. 367 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 368 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 369 // Need to do a round-trip so that the post-handshake message is 370 // handled on both client and server. 371 server_->SendData(50); 372 client_->ReadBytes(50); 373 client_->ClientAuthCallbackComplete(); 374 client_->SendData(50); 375 server_->ReadBytes(50); 376 377 EXPECT_EQ(1U, called); 378 ASSERT_TRUE(capture_cert_req->filtered()); 379 ASSERT_TRUE(capture_certificate->filtered()); 380 381 client_->CheckClientAuthCompleted(); 382 // Check if a non-empty request context is generated and it is 383 // properly sent back. 384 EXPECT_LT(0U, capture_cert_req->buffer().len()); 385 EXPECT_EQ(capture_cert_req->buffer().len(), 386 capture_certificate->buffer().len()); 387 EXPECT_EQ(0, memcmp(capture_cert_req->buffer().data(), 388 capture_certificate->buffer().data(), 389 capture_cert_req->buffer().len())); 390 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 391 ASSERT_NE(nullptr, cert1.get()); 392 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 393 ASSERT_NE(nullptr, cert2.get()); 394 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert1->derCert, &cert2->derCert)); 395 } 396 397 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthAfterResumption) { 398 ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET); 399 ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3); 400 Connect(); 401 402 SendReceive(); // Need to read so that we absorb the session tickets. 403 CheckKeys(); 404 405 // Resume the connection. 406 Reset(); 407 408 ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET); 409 ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3); 410 ExpectResumption(RESUME_TICKET); 411 412 client_->SetupClientAuth(std::get<2>(GetParam()), true); 413 client_->SetOption(SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE); 414 Connect(); 415 SendReceive(); 416 417 size_t called = 0; 418 server_->SetAuthCertificateCallback( 419 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 420 called++; 421 return SECSuccess; 422 }); 423 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 424 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 425 426 server_->SendData(50); 427 client_->ReadBytes(50); 428 client_->ClientAuthCallbackComplete(); 429 client_->SendData(50); 430 server_->ReadBytes(50); 431 432 client_->CheckClientAuthCompleted(); 433 EXPECT_EQ(1U, called); 434 435 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 436 ASSERT_NE(nullptr, cert1.get()); 437 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 438 ASSERT_NE(nullptr, cert2.get()); 439 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert1->derCert, &cert2->derCert)); 440 } 441 442 static SECStatus GetClientAuthDataHook(void* self, PRFileDesc* fd, 443 CERTDistNames* caNames, 444 CERTCertificate** clientCert, 445 SECKEYPrivateKey** clientKey) { 446 ScopedCERTCertificate cert; 447 ScopedSECKEYPrivateKey priv; 448 // use a different certificate than TlsAgent::kClient 449 if (!TlsAgent::LoadCertificate(TlsAgent::kRsa2048, &cert, &priv)) { 450 return SECFailure; 451 } 452 453 *clientCert = cert.release(); 454 *clientKey = priv.release(); 455 return SECSuccess; 456 } 457 458 typedef struct AutoClientTestStr { 459 SECStatus result; 460 const std::string cert; 461 } AutoClientTest; 462 463 typedef struct AutoClientResultsStr { 464 AutoClientTest isRsa2048; 465 AutoClientTest isClient; 466 AutoClientTest isNull; 467 bool hookCalled; 468 } AutoClientResults; 469 470 void VerifyClientCertMatch(CERTCertificate* clientCert, 471 const std::string expectedName) { 472 const char* name = clientCert->nickname; 473 std::cout << "Match name=\"" << name << "\" expected=\"" << expectedName 474 << "\"" << std::endl; 475 EXPECT_TRUE(PORT_Strcmp(name, expectedName.c_str()) == 0) 476 << " Certmismatch: \"" << name << "\" != \"" << expectedName << "\""; 477 } 478 479 static SECStatus GetAutoClientAuthDataHook(void* expectResults, PRFileDesc* fd, 480 CERTDistNames* caNames, 481 CERTCertificate** clientCert, 482 SECKEYPrivateKey** clientKey) { 483 AutoClientResults& results = *(AutoClientResults*)expectResults; 484 SECStatus rv; 485 486 results.hookCalled = true; 487 *clientCert = NULL; 488 *clientKey = NULL; 489 rv = NSS_GetClientAuthData((void*)TlsAgent::kRsa2048.c_str(), fd, caNames, 490 clientCert, clientKey); 491 if (rv == SECSuccess) { 492 VerifyClientCertMatch(*clientCert, results.isRsa2048.cert); 493 CERT_DestroyCertificate(*clientCert); 494 SECKEY_DestroyPrivateKey(*clientKey); 495 *clientCert = NULL; 496 *clientKey = NULL; 497 } 498 EXPECT_EQ(results.isRsa2048.result, rv); 499 500 rv = NSS_GetClientAuthData((void*)TlsAgent::kClient.c_str(), fd, caNames, 501 clientCert, clientKey); 502 if (rv == SECSuccess) { 503 VerifyClientCertMatch(*clientCert, results.isClient.cert); 504 CERT_DestroyCertificate(*clientCert); 505 SECKEY_DestroyPrivateKey(*clientKey); 506 *clientCert = NULL; 507 *clientKey = NULL; 508 } 509 EXPECT_EQ(results.isClient.result, rv); 510 EXPECT_EQ(*clientCert, nullptr); 511 EXPECT_EQ(*clientKey, nullptr); 512 rv = NSS_GetClientAuthData(NULL, fd, caNames, clientCert, clientKey); 513 if (rv == SECSuccess) { 514 VerifyClientCertMatch(*clientCert, results.isNull.cert); 515 // return this result 516 } 517 EXPECT_EQ(results.isNull.result, rv); 518 return rv; 519 } 520 521 // while I would have liked to use a new INSTANTIATE macro the 522 // generates the following three tests, figuring out how to make that 523 // work on top of the existing TlsConnect* plumbing hurts my head. 524 TEST_P(TlsConnectTls12, AutoClientSelectRsaPss) { 525 AutoClientResults rsa = {{SECSuccess, TlsAgent::kRsa2048}, 526 {SECSuccess, TlsAgent::kClient}, 527 {SECSuccess, TlsAgent::kDelegatorRsaPss2048}, 528 false}; 529 static const SSLSignatureScheme kSchemes[] = {ssl_sig_rsa_pss_pss_sha256, 530 ssl_sig_rsa_pkcs1_sha256, 531 ssl_sig_rsa_pkcs1_sha1}; 532 Reset("rsa_pss_noparam"); 533 client_->SetupClientAuth(); 534 server_->RequestClientAuth(true); 535 EXPECT_EQ(SECSuccess, 536 SSL_GetClientAuthDataHook(client_->ssl_fd(), 537 GetAutoClientAuthDataHook, (void*)&rsa)); 538 server_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 539 client_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 540 Connect(); 541 EXPECT_TRUE(rsa.hookCalled); 542 } 543 544 TEST_P(TlsConnectTls12, AutoClientSelectEcc) { 545 AutoClientResults ecc = {{SECFailure, TlsAgent::kClient}, 546 {SECFailure, TlsAgent::kClient}, 547 {SECSuccess, TlsAgent::kDelegatorEcdsa256}, 548 false}; 549 static const SSLSignatureScheme kSchemes[] = {ssl_sig_ecdsa_secp256r1_sha256}; 550 client_->SetupClientAuth(); 551 server_->RequestClientAuth(true); 552 EXPECT_EQ(SECSuccess, 553 SSL_GetClientAuthDataHook(client_->ssl_fd(), 554 GetAutoClientAuthDataHook, (void*)&ecc)); 555 server_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 556 client_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 557 Connect(); 558 EXPECT_TRUE(ecc.hookCalled); 559 } 560 561 #ifndef NSS_DISABLE_DSA 562 TEST_P(TlsConnectTls12, AutoClientSelectDsa) { 563 AutoClientResults dsa = {{SECFailure, TlsAgent::kClient}, 564 {SECFailure, TlsAgent::kClient}, 565 {SECSuccess, TlsAgent::kServerDsa}, 566 false}; 567 static const SSLSignatureScheme kSchemes[] = {ssl_sig_dsa_sha256}; 568 client_->SetupClientAuth(); 569 server_->RequestClientAuth(true); 570 EXPECT_EQ(SECSuccess, 571 SSL_GetClientAuthDataHook(client_->ssl_fd(), 572 GetAutoClientAuthDataHook, (void*)&dsa)); 573 server_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 574 client_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 575 Connect(); 576 EXPECT_TRUE(dsa.hookCalled); 577 } 578 #endif 579 580 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthMultiple) { 581 client_->SetupClientAuth(std::get<2>(GetParam()), true); 582 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 583 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 584 size_t called = 0; 585 server_->SetAuthCertificateCallback( 586 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 587 called++; 588 return SECSuccess; 589 }); 590 Connect(); 591 EXPECT_EQ(0U, called); 592 EXPECT_EQ(nullptr, SSL_PeerCertificate(server_->ssl_fd())); 593 // Send 1st CertificateRequest. 594 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 595 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 596 597 server_->SendData(50); 598 client_->ReadBytes(50); 599 client_->ClientAuthCallbackComplete(); 600 client_->ReadBytes(50); 601 client_->SendData(50); 602 server_->ReadBytes(50); 603 EXPECT_EQ(1U, called); 604 client_->CheckClientAuthCompleted(1); 605 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 606 ASSERT_NE(nullptr, cert1.get()); 607 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 608 ASSERT_NE(nullptr, cert2.get()); 609 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert1->derCert, &cert2->derCert)); 610 // Send 2nd CertificateRequest. 611 client_->SetupClientAuth(std::get<2>(GetParam()), true); 612 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 613 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 614 615 server_->SendData(50); 616 client_->ReadBytes(50); 617 client_->ClientAuthCallbackComplete(); 618 client_->ReadBytes(50); 619 client_->SendData(50); 620 server_->ReadBytes(50); 621 client_->CheckClientAuthCompleted(2); 622 EXPECT_EQ(2U, called); 623 ScopedCERTCertificate cert3(SSL_PeerCertificate(server_->ssl_fd())); 624 ASSERT_NE(nullptr, cert3.get()); 625 ScopedCERTCertificate cert4(SSL_LocalCertificate(client_->ssl_fd())); 626 ASSERT_NE(nullptr, cert4.get()); 627 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert3->derCert, &cert4->derCert)); 628 } 629 630 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthConcurrent) { 631 client_->SetupClientAuth(std::get<2>(GetParam()), true); 632 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 633 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 634 Connect(); 635 // Send 1st CertificateRequest. 636 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 637 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 638 // Send 2nd CertificateRequest. 639 EXPECT_EQ(SECFailure, SSL_SendCertificateRequest(server_->ssl_fd())); 640 EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError()); 641 } 642 643 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthBeforeKeyUpdate) { 644 client_->SetupClientAuth(std::get<2>(GetParam()), true); 645 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 646 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 647 Connect(); 648 // Send CertificateRequest. 649 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 650 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 651 // Send KeyUpdate. 652 EXPECT_EQ(SECFailure, SSL_KeyUpdate(server_->ssl_fd(), PR_TRUE)); 653 EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError()); 654 } 655 656 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthDuringClientKeyUpdate) { 657 client_->SetupClientAuth(std::get<2>(GetParam()), true); 658 ; 659 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 660 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 661 Connect(); 662 CheckEpochs(3, 3); 663 // Send CertificateRequest from server. 664 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 665 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 666 // Send KeyUpdate from client. 667 EXPECT_EQ(SECSuccess, SSL_KeyUpdate(client_->ssl_fd(), PR_TRUE)); 668 server_->SendData(50); // server sends CertificateRequest 669 client_->SendData(50); // client sends KeyUpdate 670 server_->ReadBytes(50); // server receives KeyUpdate and defers response 671 CheckEpochs(4, 3); 672 client_->ReadBytes(60); // client receives CertificateRequest 673 client_->ClientAuthCallbackComplete(); 674 client_->ReadBytes(50); // Finish reading the remaining bytes 675 client_->SendData( 676 50); // client sends Certificate, CertificateVerify, Finished 677 server_->ReadBytes( 678 50); // server receives Certificate, CertificateVerify, Finished 679 client_->CheckClientAuthCompleted(); 680 client_->CheckEpochs(3, 4); 681 server_->CheckEpochs(4, 4); 682 server_->SendData(50); // server sends KeyUpdate 683 client_->ReadBytes(50); // client receives KeyUpdate 684 client_->CheckEpochs(4, 4); 685 } 686 687 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthMissingExtension) { 688 client_->SetupClientAuth(std::get<2>(GetParam()), true); 689 Connect(); 690 // Send CertificateRequest, should fail due to missing 691 // post_handshake_auth extension. 692 EXPECT_EQ(SECFailure, SSL_SendCertificateRequest(server_->ssl_fd())); 693 EXPECT_EQ(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION, PORT_GetError()); 694 } 695 696 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthAfterClientAuth) { 697 client_->SetupClientAuth(std::get<2>(GetParam()), true); 698 server_->RequestClientAuth(true); 699 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 700 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 701 size_t called = 0; 702 server_->SetAuthCertificateCallback( 703 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 704 called++; 705 return SECSuccess; 706 }); 707 Connect(); 708 EXPECT_EQ(1U, called); 709 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 710 ASSERT_NE(nullptr, cert1.get()); 711 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 712 ASSERT_NE(nullptr, cert2.get()); 713 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert1->derCert, &cert2->derCert)); 714 // Send CertificateRequest. 715 EXPECT_EQ(SECSuccess, SSL_GetClientAuthDataHook( 716 client_->ssl_fd(), GetClientAuthDataHook, nullptr)); 717 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 718 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 719 server_->SendData(50); 720 client_->ReadBytes(50); 721 client_->SendData(50); 722 server_->ReadBytes(50); 723 EXPECT_EQ(2U, called); 724 ScopedCERTCertificate cert3(SSL_PeerCertificate(server_->ssl_fd())); 725 ASSERT_NE(nullptr, cert3.get()); 726 ScopedCERTCertificate cert4(SSL_LocalCertificate(client_->ssl_fd())); 727 ASSERT_NE(nullptr, cert4.get()); 728 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert3->derCert, &cert4->derCert)); 729 EXPECT_FALSE(SECITEM_ItemsAreEqual(&cert3->derCert, &cert1->derCert)); 730 } 731 732 // Damages the request context in a CertificateRequest message. 733 // We don't modify a Certificate message instead, so that the client 734 // can compute CertificateVerify correctly. 735 class TlsDamageCertificateRequestContextFilter : public TlsHandshakeFilter { 736 public: 737 TlsDamageCertificateRequestContextFilter(const std::shared_ptr<TlsAgent>& a) 738 : TlsHandshakeFilter(a, {kTlsHandshakeCertificateRequest}) { 739 EnableDecryption(); 740 } 741 742 protected: 743 virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header, 744 const DataBuffer& input, 745 DataBuffer* output) { 746 *output = input; 747 assert(1 < output->len()); 748 // The request context has a 1 octet length. 749 output->data()[1] ^= 73; 750 return CHANGE; 751 } 752 }; 753 754 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthContextMismatch) { 755 EnsureTlsSetup(); 756 MakeTlsFilter<TlsDamageCertificateRequestContextFilter>(server_); 757 client_->SetupClientAuth(std::get<2>(GetParam()), true); 758 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 759 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 760 Connect(); 761 // Send CertificateRequest. 762 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 763 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 764 server_->SendData(50); 765 client_->ReadBytes(50); 766 client_->ClientAuthCallbackComplete(); 767 client_->ReadBytes(50); 768 client_->SendData(50); 769 server_->ExpectSendAlert(kTlsAlertIllegalParameter); 770 server_->ReadBytes(50); 771 EXPECT_EQ(SSL_ERROR_RX_MALFORMED_CERTIFICATE, PORT_GetError()); 772 server_->ExpectReadWriteError(); 773 server_->SendData(50); 774 client_->ExpectReceiveAlert(kTlsAlertIllegalParameter); 775 client_->ReadBytes(50); 776 EXPECT_EQ(SSL_ERROR_ILLEGAL_PARAMETER_ALERT, PORT_GetError()); 777 } 778 779 // Replaces signature in a CertificateVerify message. 780 class TlsDamageSignatureFilter : public TlsHandshakeFilter { 781 public: 782 TlsDamageSignatureFilter(const std::shared_ptr<TlsAgent>& a) 783 : TlsHandshakeFilter(a, {kTlsHandshakeCertificateVerify}) { 784 EnableDecryption(); 785 } 786 787 protected: 788 virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header, 789 const DataBuffer& input, 790 DataBuffer* output) { 791 *output = input; 792 assert(2 < output->len()); 793 // The signature follows a 2-octet signature scheme. 794 output->data()[2] ^= 73; 795 return CHANGE; 796 } 797 }; 798 799 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthBadSignature) { 800 EnsureTlsSetup(); 801 MakeTlsFilter<TlsDamageSignatureFilter>(client_); 802 client_->SetupClientAuth(std::get<2>(GetParam()), true); 803 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 804 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 805 Connect(); 806 // Send CertificateRequest. 807 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 808 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 809 server_->SendData(50); 810 client_->ReadBytes(50); 811 client_->ClientAuthCallbackComplete(); 812 client_->SendData(50); 813 client_->CheckClientAuthCompleted(); 814 server_->ExpectSendAlert(kTlsAlertDecodeError); 815 server_->ReadBytes(50); 816 EXPECT_EQ(SSL_ERROR_RX_MALFORMED_CERT_VERIFY, PORT_GetError()); 817 } 818 819 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthDecline) { 820 EnsureTlsSetup(); 821 auto capture_cert_req = MakeTlsFilter<TlsCertificateRequestContextRecorder>( 822 server_, kTlsHandshakeCertificateRequest); 823 auto capture_certificate = 824 MakeTlsFilter<TlsCertificateRequestContextRecorder>( 825 client_, kTlsHandshakeCertificate); 826 client_->SetupClientAuth(std::get<2>(GetParam()), true); 827 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 828 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 829 EXPECT_EQ(SECSuccess, 830 SSL_OptionSet(server_->ssl_fd(), SSL_REQUIRE_CERTIFICATE, 831 SSL_REQUIRE_ALWAYS)); 832 // Client to decline the certificate request. 833 EXPECT_EQ(SECSuccess, 834 SSL_GetClientAuthDataHook( 835 client_->ssl_fd(), 836 [](void*, PRFileDesc*, CERTDistNames*, CERTCertificate**, 837 SECKEYPrivateKey**) -> SECStatus { return SECFailure; }, 838 nullptr)); 839 size_t called = 0; 840 server_->SetAuthCertificateCallback( 841 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 842 called++; 843 return SECSuccess; 844 }); 845 Connect(); 846 EXPECT_EQ(0U, called); 847 // Send CertificateRequest. 848 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 849 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 850 server_->SendData(50); // send Certificate Request 851 client_->ReadBytes(50); // read Certificate Request 852 client_->SendData(50); // send empty Certificate+Finished 853 server_->ExpectSendAlert(kTlsAlertCertificateRequired); 854 server_->ReadBytes(50); // read empty Certificate+Finished 855 server_->ExpectReadWriteError(); 856 server_->SendData(50); // send alert 857 // AuthCertificateCallback is not called, because the client sends 858 // an empty certificate_list. 859 EXPECT_EQ(0U, called); 860 EXPECT_TRUE(capture_cert_req->filtered()); 861 EXPECT_TRUE(capture_certificate->filtered()); 862 // Check if a non-empty request context is generated and it is 863 // properly sent back. 864 EXPECT_LT(0U, capture_cert_req->buffer().len()); 865 EXPECT_EQ(capture_cert_req->buffer().len(), 866 capture_certificate->buffer().len()); 867 EXPECT_EQ(0, memcmp(capture_cert_req->buffer().data(), 868 capture_certificate->buffer().data(), 869 capture_cert_req->buffer().len())); 870 } 871 872 // Check if post-handshake auth still works when session tickets are enabled: 873 // https://bugzilla.mozilla.org/show_bug.cgi?id=1553443 874 TEST_P(TlsConnectClientAuthStream13, 875 PostHandshakeAuthWithSessionTicketsEnabled) { 876 EnsureTlsSetup(); 877 client_->SetupClientAuth(std::get<2>(GetParam()), true); 878 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 879 SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE)); 880 EXPECT_EQ(SECSuccess, SSL_OptionSet(client_->ssl_fd(), 881 SSL_ENABLE_SESSION_TICKETS, PR_TRUE)); 882 EXPECT_EQ(SECSuccess, SSL_OptionSet(server_->ssl_fd(), 883 SSL_ENABLE_SESSION_TICKETS, PR_TRUE)); 884 size_t called = 0; 885 server_->SetAuthCertificateCallback( 886 [&called](TlsAgent*, PRBool, PRBool) -> SECStatus { 887 called++; 888 return SECSuccess; 889 }); 890 Connect(); 891 EXPECT_EQ(0U, called); 892 // Send CertificateRequest. 893 EXPECT_EQ(SECSuccess, SSL_GetClientAuthDataHook( 894 client_->ssl_fd(), GetClientAuthDataHook, nullptr)); 895 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 896 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 897 server_->SendData(50); 898 client_->ReadBytes(50); 899 client_->SendData(50); 900 server_->ReadBytes(50); 901 EXPECT_EQ(1U, called); 902 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 903 ASSERT_NE(nullptr, cert1.get()); 904 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 905 ASSERT_NE(nullptr, cert2.get()); 906 EXPECT_TRUE(SECITEM_ItemsAreEqual(&cert1->derCert, &cert2->derCert)); 907 } 908 909 TEST_P(TlsConnectClientAuthPre13, ClientAuthRequiredRejected) { 910 client_->SetupClientAuth(std::get<2>(GetParam()), false); 911 server_->RequestClientAuth(true); 912 ConnectExpectAlert(server_, kTlsAlertBadCertificate); 913 client_->CheckErrorCode(SSL_ERROR_BAD_CERT_ALERT); 914 server_->CheckErrorCode(SSL_ERROR_NO_CERTIFICATE); 915 } 916 917 // In TLS 1.3, the client will claim that the connection is done and then 918 // receive the alert afterwards. So drive the handshake manually. 919 TEST_P(TlsConnectClientAuth13, ClientAuthRequiredRejected) { 920 client_->SetupClientAuth(std::get<2>(GetParam()), false); 921 server_->RequestClientAuth(true); 922 StartConnect(); 923 client_->Handshake(); // CH 924 server_->Handshake(); // SH.. (no resumption) 925 926 client_->Handshake(); // Next message 927 ASSERT_EQ(TlsAgent::STATE_CONNECTED, client_->state()); 928 client_->CheckClientAuthCompleted(); 929 ExpectAlert(server_, kTlsAlertCertificateRequired); 930 server_->Handshake(); // Alert 931 server_->CheckErrorCode(SSL_ERROR_NO_CERTIFICATE); 932 client_->Handshake(); // Receive Alert 933 client_->CheckErrorCode(SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT); 934 } 935 936 TEST_P(TlsConnectClientAuth, ClientAuthRequestedRejected) { 937 client_->SetupClientAuth(std::get<2>(GetParam()), false); 938 server_->RequestClientAuth(false); 939 Connect(); 940 CheckKeys(); 941 } 942 943 TEST_P(TlsConnectClientAuth, ClientAuthEcdsa) { 944 Reset(TlsAgent::kServerEcdsa256); 945 client_->SetupClientAuth(std::get<2>(GetParam()), true); 946 server_->RequestClientAuth(true); 947 Connect(); 948 CheckKeys(ssl_auth_ecdsa); 949 } 950 951 TEST_P(TlsConnectClientAuth, ClientAuthWithEch) { 952 if (variant_ == ssl_variant_datagram) { 953 GTEST_SKIP(); 954 } 955 Reset(TlsAgent::kServerEcdsa256); 956 EnsureTlsSetup(); 957 SetupEch(client_, server_); 958 client_->SetupClientAuth(std::get<2>(GetParam()), true); 959 server_->RequestClientAuth(true); 960 Connect(); 961 CheckKeys(ssl_auth_ecdsa); 962 } 963 964 TEST_P(TlsConnectClientAuth, ClientAuthBigRsa) { 965 Reset(TlsAgent::kServerRsa, TlsAgent::kRsa2048); 966 client_->SetupClientAuth(std::get<2>(GetParam()), true); 967 server_->RequestClientAuth(true); 968 Connect(); 969 CheckKeys(); 970 } 971 972 // Offset is the position in the captured buffer where the signature sits. 973 static void CheckSigScheme(std::shared_ptr<TlsHandshakeRecorder>& capture, 974 size_t offset, std::shared_ptr<TlsAgent>& peer, 975 uint16_t expected_scheme, size_t expected_size) { 976 EXPECT_LT(offset + 2U, capture->buffer().len()); 977 978 uint32_t scheme = 0; 979 capture->buffer().Read(offset, 2, &scheme); 980 EXPECT_EQ(expected_scheme, static_cast<uint16_t>(scheme)); 981 982 ScopedCERTCertificate remote_cert(SSL_PeerCertificate(peer->ssl_fd())); 983 ASSERT_NE(nullptr, remote_cert.get()); 984 ScopedSECKEYPublicKey remote_key(CERT_ExtractPublicKey(remote_cert.get())); 985 ASSERT_NE(nullptr, remote_key.get()); 986 EXPECT_EQ(expected_size, SECKEY_PublicKeyStrengthInBits(remote_key.get())); 987 } 988 989 // The server should prefer SHA-256 by default, even for the small key size used 990 // in the default certificate. 991 TEST_P(TlsConnectTls12, ServerAuthCheckSigAlg) { 992 EnsureTlsSetup(); 993 auto capture_ske = MakeTlsFilter<TlsHandshakeRecorder>( 994 server_, kTlsHandshakeServerKeyExchange); 995 Connect(); 996 CheckKeys(); 997 998 const DataBuffer& buffer = capture_ske->buffer(); 999 EXPECT_LT(3U, buffer.len()); 1000 EXPECT_EQ(3U, buffer.data()[0]) << "curve_type == named_curve"; 1001 uint32_t tmp; 1002 EXPECT_TRUE(buffer.Read(1, 2, &tmp)) << "read NamedCurve"; 1003 EXPECT_EQ(ssl_grp_ec_curve25519, tmp); 1004 EXPECT_TRUE(buffer.Read(3, 1, &tmp)) << " read ECPoint"; 1005 CheckSigScheme(capture_ske, 4 + tmp, client_, ssl_sig_rsa_pss_rsae_sha256, 1006 1024); 1007 } 1008 1009 TEST_P(TlsConnectClientAuth12, ClientAuthCheckSigAlg) { 1010 EnsureTlsSetup(); 1011 auto capture_cert_verify = MakeTlsFilter<TlsHandshakeRecorder>( 1012 client_, kTlsHandshakeCertificateVerify); 1013 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1014 server_->RequestClientAuth(true); 1015 Connect(); 1016 CheckKeys(); 1017 1018 CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pkcs1_sha1, 1024); 1019 } 1020 1021 TEST_P(TlsConnectClientAuth12, ClientAuthBigRsaCheckSigAlg) { 1022 Reset(TlsAgent::kServerRsa, TlsAgent::kRsa2048); 1023 auto capture_cert_verify = MakeTlsFilter<TlsHandshakeRecorder>( 1024 client_, kTlsHandshakeCertificateVerify); 1025 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1026 server_->RequestClientAuth(true); 1027 Connect(); 1028 CheckKeys(); 1029 CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pss_rsae_sha256, 1030 2048); 1031 } 1032 1033 // Check if CertificateVerify signed with rsa_pss_rsae_* is properly 1034 // rejected when the certificate is RSA-PSS. 1035 // 1036 // This only works under TLS 1.2, because PSS doesn't work with TLS 1037 // 1.0 or TLS 1.1 and the TLS 1.3 1-RTT handshake is partially 1038 // successful at the client side. 1039 TEST_P(TlsConnectClientAuth12, ClientAuthInconsistentRsaeSignatureScheme) { 1040 static const SSLSignatureScheme kSignatureSchemePss[] = { 1041 ssl_sig_rsa_pss_pss_sha256, ssl_sig_rsa_pss_rsae_sha256}; 1042 1043 Reset(TlsAgent::kServerRsa, "rsa_pss"); 1044 client_->SetSignatureSchemes(kSignatureSchemePss, 1045 PR_ARRAY_SIZE(kSignatureSchemePss)); 1046 server_->SetSignatureSchemes(kSignatureSchemePss, 1047 PR_ARRAY_SIZE(kSignatureSchemePss)); 1048 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1049 server_->RequestClientAuth(true); 1050 1051 EnsureTlsSetup(); 1052 1053 MakeTlsFilter<TlsReplaceSignatureSchemeFilter>(client_, 1054 ssl_sig_rsa_pss_rsae_sha256); 1055 1056 ConnectExpectAlert(server_, kTlsAlertIllegalParameter); 1057 } 1058 1059 // Check if CertificateVerify signed with rsa_pss_pss_* is properly 1060 // rejected when the certificate is RSA. 1061 // 1062 // This only works under TLS 1.2, because PSS doesn't work with TLS 1063 // 1.0 or TLS 1.1 and the TLS 1.3 1-RTT handshake is partially 1064 // successful at the client side. 1065 TEST_P(TlsConnectClientAuth12, ClientAuthInconsistentPssSignatureScheme) { 1066 static const SSLSignatureScheme kSignatureSchemePss[] = { 1067 ssl_sig_rsa_pss_rsae_sha256, ssl_sig_rsa_pss_pss_sha256}; 1068 1069 Reset(TlsAgent::kServerRsa, "rsa"); 1070 client_->SetSignatureSchemes(kSignatureSchemePss, 1071 PR_ARRAY_SIZE(kSignatureSchemePss)); 1072 server_->SetSignatureSchemes(kSignatureSchemePss, 1073 PR_ARRAY_SIZE(kSignatureSchemePss)); 1074 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1075 server_->RequestClientAuth(true); 1076 1077 EnsureTlsSetup(); 1078 1079 MakeTlsFilter<TlsReplaceSignatureSchemeFilter>(client_, 1080 ssl_sig_rsa_pss_pss_sha256); 1081 1082 ConnectExpectAlert(server_, kTlsAlertIllegalParameter); 1083 } 1084 1085 TEST_P(TlsConnectClientAuth13, ClientAuthPkcs1SignatureScheme) { 1086 static const SSLSignatureScheme kSignatureScheme[] = { 1087 ssl_sig_rsa_pkcs1_sha256, ssl_sig_rsa_pss_rsae_sha256}; 1088 1089 Reset(TlsAgent::kServerRsa, "rsa"); 1090 client_->SetSignatureSchemes(kSignatureScheme, 1091 PR_ARRAY_SIZE(kSignatureScheme)); 1092 server_->SetSignatureSchemes(kSignatureScheme, 1093 PR_ARRAY_SIZE(kSignatureScheme)); 1094 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1095 server_->RequestClientAuth(true); 1096 1097 auto capture_cert_verify = MakeTlsFilter<TlsHandshakeRecorder>( 1098 client_, kTlsHandshakeCertificateVerify); 1099 capture_cert_verify->EnableDecryption(); 1100 1101 Connect(); 1102 CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pss_rsae_sha256, 1103 1024); 1104 } 1105 1106 // Client should refuse to connect without a usable signature scheme. 1107 TEST_P(TlsConnectClientAuth13, ClientAuthPkcs1SignatureSchemeOnly) { 1108 static const SSLSignatureScheme kSignatureScheme[] = { 1109 ssl_sig_rsa_pkcs1_sha256}; 1110 1111 Reset(TlsAgent::kServerRsa, "rsa"); 1112 client_->SetSignatureSchemes(kSignatureScheme, 1113 PR_ARRAY_SIZE(kSignatureScheme)); 1114 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1115 client_->StartConnect(); 1116 client_->Handshake(); 1117 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 1118 client_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1119 } 1120 1121 // Though the client has a usable signature scheme, when a certificate is 1122 // requested, it can't produce one. 1123 TEST_P(TlsConnectClientAuth13, ClientAuthPkcs1AndEcdsaScheme) { 1124 static const SSLSignatureScheme kSignatureScheme[] = { 1125 ssl_sig_rsa_pkcs1_sha256, ssl_sig_ecdsa_secp256r1_sha256}; 1126 1127 Reset(TlsAgent::kServerRsa, "rsa"); 1128 client_->SetSignatureSchemes(kSignatureScheme, 1129 PR_ARRAY_SIZE(kSignatureScheme)); 1130 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1131 server_->RequestClientAuth(true); 1132 1133 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1134 server_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 1135 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1136 } 1137 1138 class TlsZeroCertificateRequestSigAlgsFilter : public TlsHandshakeFilter { 1139 public: 1140 TlsZeroCertificateRequestSigAlgsFilter(const std::shared_ptr<TlsAgent>& a) 1141 : TlsHandshakeFilter(a, {kTlsHandshakeCertificateRequest}) {} 1142 virtual PacketFilter::Action FilterHandshake( 1143 const TlsHandshakeFilter::HandshakeHeader& header, 1144 const DataBuffer& input, DataBuffer* output) { 1145 TlsParser parser(input); 1146 std::cerr << "Zeroing CertReq.supported_signature_algorithms" << std::endl; 1147 1148 DataBuffer cert_types; 1149 if (!parser.ReadVariable(&cert_types, 1)) { 1150 ADD_FAILURE(); 1151 return KEEP; 1152 } 1153 1154 if (!parser.SkipVariable(2)) { 1155 ADD_FAILURE(); 1156 return KEEP; 1157 } 1158 1159 DataBuffer cas; 1160 if (!parser.ReadVariable(&cas, 2)) { 1161 ADD_FAILURE(); 1162 return KEEP; 1163 } 1164 1165 size_t idx = 0; 1166 1167 // Write certificate types. 1168 idx = output->Write(idx, cert_types.len(), 1); 1169 idx = output->Write(idx, cert_types); 1170 1171 // Write zero signature algorithms. 1172 idx = output->Write(idx, 0U, 2); 1173 1174 // Write certificate authorities. 1175 idx = output->Write(idx, cas.len(), 2); 1176 idx = output->Write(idx, cas); 1177 1178 return CHANGE; 1179 } 1180 }; 1181 1182 // Check that we send an alert when the server doesn't provide any 1183 // supported_signature_algorithms in the CertificateRequest message. 1184 TEST_P(TlsConnectClientAuth12, ClientAuthNoSigAlgs) { 1185 EnsureTlsSetup(); 1186 MakeTlsFilter<TlsZeroCertificateRequestSigAlgsFilter>(server_); 1187 auto capture_cert_verify = MakeTlsFilter<TlsHandshakeRecorder>( 1188 client_, kTlsHandshakeCertificateVerify); 1189 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1190 server_->RequestClientAuth(true); 1191 1192 ConnectExpectAlert(client_, kTlsAlertHandshakeFailure); 1193 1194 server_->CheckErrorCode(SSL_ERROR_HANDSHAKE_FAILURE_ALERT); 1195 client_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 1196 } 1197 1198 static SECStatus GetEcClientAuthDataHook(void* self, PRFileDesc* fd, 1199 CERTDistNames* caNames, 1200 CERTCertificate** clientCert, 1201 SECKEYPrivateKey** clientKey) { 1202 ScopedCERTCertificate cert; 1203 ScopedSECKEYPrivateKey priv; 1204 // use a different certificate than TlsAgent::kClient 1205 if (!TlsAgent::LoadCertificate(TlsAgent::kServerEcdsa256, &cert, &priv)) { 1206 return SECFailure; 1207 } 1208 1209 *clientCert = cert.release(); 1210 *clientKey = priv.release(); 1211 return SECSuccess; 1212 } 1213 1214 TEST_P(TlsConnectClientAuth12Plus, ClientAuthDisjointSchemes) { 1215 EnsureTlsSetup(); 1216 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1217 server_->RequestClientAuth(true); 1218 1219 SSLSignatureScheme server_scheme = ssl_sig_rsa_pss_rsae_sha256; 1220 std::vector<SSLSignatureScheme> client_schemes{ 1221 ssl_sig_rsa_pss_rsae_sha256, ssl_sig_ecdsa_secp256r1_sha256}; 1222 SECStatus rv = 1223 SSL_SignatureSchemePrefSet(server_->ssl_fd(), &server_scheme, 1); 1224 EXPECT_EQ(SECSuccess, rv); 1225 rv = SSL_SignatureSchemePrefSet( 1226 client_->ssl_fd(), client_schemes.data(), 1227 static_cast<unsigned int>(client_schemes.size())); 1228 EXPECT_EQ(SECSuccess, rv); 1229 1230 // Select an EC cert that's incompatible with server schemes. 1231 EXPECT_EQ(SECSuccess, 1232 SSL_GetClientAuthDataHook(client_->ssl_fd(), 1233 GetEcClientAuthDataHook, nullptr)); 1234 1235 StartConnect(); 1236 client_->Handshake(); // CH 1237 server_->Handshake(); // SH 1238 client_->Handshake(); 1239 if (version_ >= SSL_LIBRARY_VERSION_TLS_1_3) { 1240 ASSERT_EQ(TlsAgent::STATE_CONNECTED, client_->state()); 1241 ExpectAlert(server_, kTlsAlertCertificateRequired); 1242 server_->Handshake(); // Alert 1243 server_->CheckErrorCode(SSL_ERROR_NO_CERTIFICATE); 1244 client_->Handshake(); // Receive Alert 1245 client_->CheckErrorCode(SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT); 1246 } else { 1247 ASSERT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1248 ExpectAlert(server_, kTlsAlertBadCertificate); 1249 server_->Handshake(); // Alert 1250 server_->CheckErrorCode(SSL_ERROR_NO_CERTIFICATE); 1251 client_->Handshake(); // Receive Alert 1252 client_->CheckErrorCode(SSL_ERROR_BAD_CERT_ALERT); 1253 } 1254 } 1255 1256 TEST_P(TlsConnectClientAuthStream13, PostHandshakeAuthDisjointSchemes) { 1257 EnsureTlsSetup(); 1258 SSLSignatureScheme server_scheme = ssl_sig_rsa_pss_rsae_sha256; 1259 std::vector<SSLSignatureScheme> client_schemes{ 1260 ssl_sig_rsa_pss_rsae_sha256, ssl_sig_ecdsa_secp256r1_sha256}; 1261 SECStatus rv = 1262 SSL_SignatureSchemePrefSet(server_->ssl_fd(), &server_scheme, 1); 1263 EXPECT_EQ(SECSuccess, rv); 1264 rv = SSL_SignatureSchemePrefSet( 1265 client_->ssl_fd(), client_schemes.data(), 1266 static_cast<unsigned int>(client_schemes.size())); 1267 EXPECT_EQ(SECSuccess, rv); 1268 1269 client_->SetupClientAuth(std::get<2>(GetParam()), true); 1270 client_->SetOption(SSL_ENABLE_POST_HANDSHAKE_AUTH, PR_TRUE); 1271 1272 // Select an EC cert that's incompatible with server schemes. 1273 EXPECT_EQ(SECSuccess, 1274 SSL_GetClientAuthDataHook(client_->ssl_fd(), 1275 GetEcClientAuthDataHook, nullptr)); 1276 1277 Connect(); 1278 1279 // Send CertificateRequest. 1280 EXPECT_EQ(SECSuccess, SSL_SendCertificateRequest(server_->ssl_fd())) 1281 << "Unexpected error: " << PORT_ErrorToName(PORT_GetError()); 1282 1283 // Need to do a round-trip so that the post-handshake message is 1284 // handled on both client and server. 1285 server_->SendData(50); 1286 client_->ReadBytes(50); 1287 client_->SendData(50); 1288 server_->ReadBytes(50); 1289 1290 ScopedCERTCertificate cert1(SSL_PeerCertificate(server_->ssl_fd())); 1291 ASSERT_EQ(nullptr, cert1.get()); 1292 ScopedCERTCertificate cert2(SSL_LocalCertificate(client_->ssl_fd())); 1293 ASSERT_EQ(nullptr, cert2.get()); 1294 } 1295 1296 static const SSLSignatureScheme kSignatureSchemeEcdsaSha384[] = { 1297 ssl_sig_ecdsa_secp384r1_sha384}; 1298 static const SSLSignatureScheme kSignatureSchemeEcdsaSha256[] = { 1299 ssl_sig_ecdsa_secp256r1_sha256}; 1300 static const SSLSignatureScheme kSignatureSchemeRsaSha384[] = { 1301 ssl_sig_rsa_pkcs1_sha384}; 1302 static const SSLSignatureScheme kSignatureSchemeRsaSha256[] = { 1303 ssl_sig_rsa_pkcs1_sha256}; 1304 1305 static SSLNamedGroup NamedGroupForEcdsa384(const TlsConnectTestBase* ctbase) { 1306 // NSS tries to match the group size to the symmetric cipher. In TLS 1.1 and 1307 // 1.0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is the highest priority suite, so 1308 // we use P-384. With TLS 1.2 on we pick AES-128 GCM so use x25519. 1309 if (ctbase->GetVersion() <= SSL_LIBRARY_VERSION_TLS_1_1) { 1310 return ssl_grp_ec_secp384r1; 1311 } 1312 return ctbase->GetDefaultGroupFromKEA(ctbase->GetDefaultKEA()); 1313 } 1314 1315 // When signature algorithms match up, this should connect successfully; even 1316 // for TLS 1.1 and 1.0, where they should be ignored. 1317 TEST_P(TlsConnectGeneric, SignatureAlgorithmServerAuth) { 1318 Reset(TlsAgent::kServerEcdsa384); 1319 client_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1320 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1321 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1322 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1323 Connect(); 1324 CheckKeys(GetDefaultKEA(), NamedGroupForEcdsa384(this), ssl_auth_ecdsa, 1325 ssl_sig_ecdsa_secp384r1_sha384); 1326 } 1327 1328 // Here the client picks a single option, which should work in all versions. 1329 // Defaults on the server include the first option. 1330 TEST_P(TlsConnectGeneric, SignatureAlgorithmClientOnly) { 1331 const SSLSignatureAndHashAlg clientAlgorithms[] = { 1332 {ssl_hash_sha384, ssl_sign_ecdsa}, 1333 {ssl_hash_sha384, ssl_sign_rsa}, // supported but unusable 1334 {ssl_hash_md5, ssl_sign_ecdsa} // unsupported and ignored 1335 }; 1336 Reset(TlsAgent::kServerEcdsa384); 1337 EnsureTlsSetup(); 1338 // Use the old API for this function. 1339 EXPECT_EQ(SECSuccess, 1340 SSL_SignaturePrefSet(client_->ssl_fd(), clientAlgorithms, 1341 PR_ARRAY_SIZE(clientAlgorithms))); 1342 Connect(); 1343 CheckKeys(GetDefaultKEA(), NamedGroupForEcdsa384(this), ssl_auth_ecdsa, 1344 ssl_sig_ecdsa_secp384r1_sha384); 1345 } 1346 1347 // Here the server picks a single option, which should work in all versions. 1348 // Defaults on the client include the provided option. 1349 TEST_P(TlsConnectGeneric, SignatureAlgorithmServerOnly) { 1350 Reset(TlsAgent::kServerEcdsa384); 1351 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1352 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1353 Connect(); 1354 CheckKeys(GetDefaultKEA(), NamedGroupForEcdsa384(this), ssl_auth_ecdsa, 1355 ssl_sig_ecdsa_secp384r1_sha384); 1356 } 1357 1358 // In TLS 1.2, curve and hash aren't bound together. 1359 TEST_P(TlsConnectTls12, SignatureSchemeCurveMismatch) { 1360 Reset(TlsAgent::kServerEcdsa256); 1361 client_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1362 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1363 Connect(); 1364 } 1365 1366 // In TLS 1.3, curve and hash are coupled. 1367 TEST_P(TlsConnectTls13, SignatureSchemeCurveMismatch) { 1368 Reset(TlsAgent::kServerEcdsa256); 1369 client_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1370 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1371 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1372 server_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 1373 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1374 } 1375 1376 // Configuring a P-256 cert with only SHA-384 signatures is OK in TLS 1.2. 1377 TEST_P(TlsConnectTls12, SignatureSchemeBadConfig) { 1378 Reset(TlsAgent::kServerEcdsa256); // P-256 cert can't be used. 1379 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1380 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1381 Connect(); 1382 } 1383 1384 // A P-256 certificate in TLS 1.3 needs a SHA-256 signature scheme. 1385 TEST_P(TlsConnectTls13, SignatureSchemeBadConfig) { 1386 Reset(TlsAgent::kServerEcdsa256); // P-256 cert can't be used. 1387 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1388 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1389 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1390 server_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 1391 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1392 } 1393 1394 // Where there is no overlap on signature schemes, we still connect successfully 1395 // if we aren't going to use a signature. 1396 TEST_P(TlsConnectGenericPre13, SignatureAlgorithmNoOverlapStaticRsa) { 1397 client_->SetSignatureSchemes(kSignatureSchemeRsaSha384, 1398 PR_ARRAY_SIZE(kSignatureSchemeRsaSha384)); 1399 server_->SetSignatureSchemes(kSignatureSchemeRsaSha256, 1400 PR_ARRAY_SIZE(kSignatureSchemeRsaSha256)); 1401 EnableOnlyStaticRsaCiphers(); 1402 Connect(); 1403 CheckKeys(ssl_kea_rsa, ssl_auth_rsa_decrypt); 1404 } 1405 1406 TEST_P(TlsConnectTls12Plus, SignatureAlgorithmNoOverlapEcdsa) { 1407 Reset(TlsAgent::kServerEcdsa256); 1408 client_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1409 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1410 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha256, 1411 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha256)); 1412 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1413 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1414 server_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 1415 } 1416 1417 // Pre 1.2, a mismatch on signature algorithms shouldn't affect anything. 1418 TEST_P(TlsConnectPre12, SignatureAlgorithmNoOverlapEcdsa) { 1419 Reset(TlsAgent::kServerEcdsa256); 1420 client_->SetSignatureSchemes(kSignatureSchemeEcdsaSha384, 1421 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha384)); 1422 server_->SetSignatureSchemes(kSignatureSchemeEcdsaSha256, 1423 PR_ARRAY_SIZE(kSignatureSchemeEcdsaSha256)); 1424 Connect(); 1425 } 1426 1427 // The signature_algorithms extension is mandatory in TLS 1.3. 1428 TEST_P(TlsConnectTls13, SignatureAlgorithmDrop) { 1429 MakeTlsFilter<TlsExtensionDropper>(client_, ssl_signature_algorithms_xtn); 1430 ConnectExpectAlert(server_, kTlsAlertMissingExtension); 1431 client_->CheckErrorCode(SSL_ERROR_MISSING_EXTENSION_ALERT); 1432 server_->CheckErrorCode(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION); 1433 } 1434 1435 // TLS 1.2 has trouble detecting this sort of modification: it uses SHA1 and 1436 // only fails when the Finished is checked. 1437 TEST_P(TlsConnectTls12, SignatureAlgorithmDrop) { 1438 MakeTlsFilter<TlsExtensionDropper>(client_, ssl_signature_algorithms_xtn); 1439 ConnectExpectAlert(server_, kTlsAlertDecryptError); 1440 client_->CheckErrorCode(SSL_ERROR_DECRYPT_ERROR_ALERT); 1441 server_->CheckErrorCode(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1442 } 1443 1444 TEST_P(TlsConnectTls13, UnsupportedSignatureSchemeAlert) { 1445 EnsureTlsSetup(); 1446 auto filter = 1447 MakeTlsFilter<TlsReplaceSignatureSchemeFilter>(server_, ssl_sig_none); 1448 filter->EnableDecryption(); 1449 1450 ConnectExpectAlert(client_, kTlsAlertIllegalParameter); 1451 server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT); 1452 client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CERT_VERIFY); 1453 } 1454 1455 TEST_P(TlsConnectTls13, InconsistentSignatureSchemeAlert) { 1456 EnsureTlsSetup(); 1457 1458 // This won't work because we use an RSA cert by default. 1459 auto filter = MakeTlsFilter<TlsReplaceSignatureSchemeFilter>( 1460 server_, ssl_sig_ecdsa_secp256r1_sha256); 1461 filter->EnableDecryption(); 1462 1463 ConnectExpectAlert(client_, kTlsAlertIllegalParameter); 1464 server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT); 1465 client_->CheckErrorCode(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 1466 } 1467 1468 TEST_P(TlsConnectTls12, RequestClientAuthWithSha384) { 1469 server_->SetSignatureSchemes(kSignatureSchemeRsaSha384, 1470 PR_ARRAY_SIZE(kSignatureSchemeRsaSha384)); 1471 server_->RequestClientAuth(false); 1472 Connect(); 1473 } 1474 1475 class BeforeFinished : public TlsRecordFilter { 1476 private: 1477 enum HandshakeState { BEFORE_CCS, AFTER_CCS, DONE }; 1478 1479 public: 1480 BeforeFinished(const std::shared_ptr<TlsAgent>& server, 1481 const std::shared_ptr<TlsAgent>& client, 1482 VoidFunction before_ccs, VoidFunction before_finished) 1483 : TlsRecordFilter(server), 1484 client_(client), 1485 before_ccs_(before_ccs), 1486 before_finished_(before_finished), 1487 state_(BEFORE_CCS) {} 1488 1489 protected: 1490 virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header, 1491 const DataBuffer& body, 1492 DataBuffer* out) { 1493 switch (state_) { 1494 case BEFORE_CCS: 1495 // Awaken when we see the CCS. 1496 if (header.content_type() == ssl_ct_change_cipher_spec) { 1497 before_ccs_(); 1498 1499 // Write the CCS out as a separate write, so that we can make 1500 // progress. Ordinarily, libssl sends the CCS and Finished together, 1501 // but that means that they both get processed together. 1502 DataBuffer ccs; 1503 header.Write(&ccs, 0, body); 1504 agent()->SendDirect(ccs); 1505 client_.lock()->Handshake(); 1506 state_ = AFTER_CCS; 1507 // Request that the original record be dropped by the filter. 1508 return DROP; 1509 } 1510 break; 1511 1512 case AFTER_CCS: 1513 EXPECT_EQ(ssl_ct_handshake, header.content_type()); 1514 // This could check that data contains a Finished message, but it's 1515 // encrypted, so that's too much extra work. 1516 1517 before_finished_(); 1518 state_ = DONE; 1519 break; 1520 1521 case DONE: 1522 break; 1523 } 1524 return KEEP; 1525 } 1526 1527 private: 1528 std::weak_ptr<TlsAgent> client_; 1529 VoidFunction before_ccs_; 1530 VoidFunction before_finished_; 1531 HandshakeState state_; 1532 }; 1533 1534 // Running code after the client has started processing the encrypted part of 1535 // the server's first flight, but before the Finished is processed is very hard 1536 // in TLS 1.3. These encrypted messages are sent in a single encrypted blob. 1537 // The following test uses DTLS to make it possible to force the client to 1538 // process the handshake in pieces. 1539 // 1540 // The first encrypted message from the server is dropped, and the MTU is 1541 // reduced to just below the original message size so that the server sends two 1542 // messages. The Finished message is then processed separately. 1543 class BeforeFinished13 : public PacketFilter { 1544 private: 1545 enum HandshakeState { 1546 INIT, 1547 BEFORE_FIRST_FRAGMENT, 1548 BEFORE_SECOND_FRAGMENT, 1549 DONE 1550 }; 1551 1552 public: 1553 BeforeFinished13(const std::shared_ptr<TlsAgent>& server, 1554 const std::shared_ptr<TlsAgent>& client, 1555 VoidFunction before_finished) 1556 : server_(server), 1557 client_(client), 1558 before_finished_(before_finished), 1559 records_(0) {} 1560 1561 protected: 1562 virtual PacketFilter::Action Filter(const DataBuffer& input, 1563 DataBuffer* output) { 1564 switch (++records_) { 1565 case 1: 1566 // Packet 1 is the server's entire first flight. Drop it. 1567 EXPECT_EQ(SECSuccess, 1568 SSLInt_SetMTU(server_.lock()->ssl_fd(), input.len() - 1)); 1569 return DROP; 1570 1571 // Packet 2 is the first part of the server's retransmitted first 1572 // flight. Keep that. 1573 1574 case 3: 1575 // Packet 3 is the second part of the server's retransmitted first 1576 // flight. Before passing that on, make sure that the client processes 1577 // packet 2, then call the before_finished_() callback. 1578 client_.lock()->Handshake(); 1579 before_finished_(); 1580 break; 1581 1582 default: 1583 break; 1584 } 1585 return KEEP; 1586 } 1587 1588 private: 1589 std::weak_ptr<TlsAgent> server_; 1590 std::weak_ptr<TlsAgent> client_; 1591 VoidFunction before_finished_; 1592 size_t records_; 1593 }; 1594 1595 static SECStatus AuthCompleteBlock(TlsAgent*, PRBool, PRBool) { 1596 return SECWouldBlock; 1597 } 1598 1599 // This test uses an AuthCertificateCallback that blocks. A filter is used to 1600 // split the server's first flight into two pieces. Before the second piece is 1601 // processed by the client, SSL_AuthCertificateComplete() is called. 1602 TEST_F(TlsConnectDatagram13, AuthCompleteBeforeFinished) { 1603 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1604 MakeTlsFilter<BeforeFinished13>(server_, client_, [this]() { 1605 EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 0)); 1606 }); 1607 // filters only work with particular groups 1608 client_->ConfigNamedGroups(kNonPQDHEGroups); 1609 Connect(); 1610 } 1611 1612 // This test uses a simple AuthCertificateCallback. Due to the way that the 1613 // entire server flight is processed, the call to SSL_AuthCertificateComplete 1614 // will trigger after the Finished message is processed. 1615 TEST_P(TlsConnectTls13, AuthCompleteAfterFinished) { 1616 SetDeferredAuthCertificateCallback(client_, 0); // 0 = success. 1617 Connect(); 1618 } 1619 1620 TEST_P(TlsConnectGenericPre13, ClientWriteBetweenCCSAndFinishedWithFalseStart) { 1621 client_->EnableFalseStart(); 1622 MakeTlsFilter<BeforeFinished>( 1623 server_, client_, 1624 [this]() { EXPECT_TRUE(client_->can_falsestart_hook_called()); }, 1625 [this]() { 1626 // Write something, which used to fail: bug 1235366. 1627 client_->SendData(10); 1628 }); 1629 1630 Connect(); 1631 server_->SendData(10); 1632 Receive(10); 1633 } 1634 1635 TEST_P(TlsConnectGenericPre13, AuthCompleteBeforeFinishedWithFalseStart) { 1636 client_->EnableFalseStart(); 1637 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1638 MakeTlsFilter<BeforeFinished>( 1639 server_, client_, 1640 []() { 1641 // Do nothing before CCS 1642 }, 1643 [this]() { 1644 EXPECT_FALSE(client_->can_falsestart_hook_called()); 1645 // AuthComplete before Finished still enables false start. 1646 EXPECT_EQ(SECSuccess, 1647 SSL_AuthCertificateComplete(client_->ssl_fd(), 0)); 1648 EXPECT_TRUE(client_->can_falsestart_hook_called()); 1649 client_->SendData(10); 1650 }); 1651 1652 Connect(); 1653 server_->SendData(10); 1654 Receive(10); 1655 } 1656 1657 class EnforceNoActivity : public PacketFilter { 1658 protected: 1659 PacketFilter::Action Filter(const DataBuffer& input, 1660 DataBuffer* output) override { 1661 std::cerr << "Unexpected packet: " << input << std::endl; 1662 EXPECT_TRUE(false) << "should not send anything"; 1663 return KEEP; 1664 } 1665 }; 1666 1667 // In this test, we want to make sure that the server completes its handshake, 1668 // but the client does not. Because the AuthCertificate callback blocks and we 1669 // never call SSL_AuthCertificateComplete(), the client should never report that 1670 // it has completed the handshake. Manually call Handshake(), alternating sides 1671 // between client and server, until the desired state is reached. 1672 TEST_P(TlsConnectGenericPre13, AuthCompleteDelayed) { 1673 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1674 1675 StartConnect(); 1676 client_->Handshake(); // Send ClientHello 1677 server_->Handshake(); // Send ServerHello 1678 client_->Handshake(); // Send ClientKeyExchange and Finished 1679 server_->Handshake(); // Send Finished 1680 // The server should now report that it is connected 1681 EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state()); 1682 1683 // The client should send nothing from here on. 1684 client_->SetFilter(std::make_shared<EnforceNoActivity>()); 1685 client_->Handshake(); 1686 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1687 1688 // This should allow the handshake to complete now. 1689 EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 0)); 1690 client_->Handshake(); // Transition to connected 1691 EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state()); 1692 EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state()); 1693 1694 // Remove filter before closing or the close_notify alert will trigger it. 1695 client_->ClearFilter(); 1696 } 1697 1698 TEST_P(TlsConnectGenericPre13, AuthCompleteFailDelayed) { 1699 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1700 1701 StartConnect(); 1702 client_->Handshake(); // Send ClientHello 1703 server_->Handshake(); // Send ServerHello 1704 client_->Handshake(); // Send ClientKeyExchange and Finished 1705 server_->Handshake(); // Send Finished 1706 // The server should now report that it is connected 1707 EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state()); 1708 1709 // The client should send nothing from here on. 1710 client_->SetFilter(std::make_shared<EnforceNoActivity>()); 1711 client_->Handshake(); 1712 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1713 1714 // Report failure. 1715 client_->ClearFilter(); 1716 client_->ExpectSendAlert(kTlsAlertBadCertificate); 1717 EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 1718 SSL_ERROR_BAD_CERTIFICATE)); 1719 client_->Handshake(); // Fail 1720 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 1721 } 1722 1723 // TLS 1.3 handles a delayed AuthComplete callback differently since the 1724 // shape of the handshake is different. 1725 TEST_P(TlsConnectTls13, AuthCompleteDelayed) { 1726 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1727 1728 StartConnect(); 1729 client_->Handshake(); // Send ClientHello 1730 server_->Handshake(); // Send ServerHello 1731 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1732 EXPECT_EQ(TlsAgent::STATE_CONNECTING, server_->state()); 1733 1734 // The client will send nothing until AuthCertificateComplete is called. 1735 client_->SetFilter(std::make_shared<EnforceNoActivity>()); 1736 client_->Handshake(); 1737 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1738 1739 // This should allow the handshake to complete now. 1740 client_->ClearFilter(); 1741 EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 0)); 1742 client_->Handshake(); // Send Finished 1743 server_->Handshake(); // Transition to connected and send NewSessionTicket 1744 EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state()); 1745 EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state()); 1746 } 1747 1748 TEST_P(TlsConnectTls13, AuthCompleteFailDelayed) { 1749 client_->SetAuthCertificateCallback(AuthCompleteBlock); 1750 1751 StartConnect(); 1752 client_->Handshake(); // Send ClientHello 1753 server_->Handshake(); // Send ServerHello 1754 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1755 EXPECT_EQ(TlsAgent::STATE_CONNECTING, server_->state()); 1756 1757 // The client will send nothing until AuthCertificateComplete is called. 1758 client_->SetFilter(std::make_shared<EnforceNoActivity>()); 1759 client_->Handshake(); 1760 EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state()); 1761 1762 // Report failure. 1763 client_->ClearFilter(); 1764 ExpectAlert(client_, kTlsAlertBadCertificate); 1765 EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 1766 SSL_ERROR_BAD_CERTIFICATE)); 1767 client_->Handshake(); // This should now fail. 1768 server_->Handshake(); // Get the error. 1769 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 1770 EXPECT_EQ(TlsAgent::STATE_ERROR, server_->state()); 1771 } 1772 1773 static SECStatus AuthCompleteFail(TlsAgent*, PRBool, PRBool) { 1774 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); 1775 return SECFailure; 1776 } 1777 1778 TEST_P(TlsConnectGeneric, AuthFailImmediate) { 1779 client_->SetAuthCertificateCallback(AuthCompleteFail); 1780 1781 StartConnect(); 1782 ConnectExpectAlert(client_, kTlsAlertBadCertificate); 1783 client_->CheckErrorCode(SSL_ERROR_BAD_CERTIFICATE); 1784 } 1785 1786 static const SSLExtraServerCertData ServerCertDataRsaPkcs1Decrypt = { 1787 ssl_auth_rsa_decrypt, nullptr, nullptr, nullptr, nullptr, nullptr}; 1788 static const SSLExtraServerCertData ServerCertDataRsaPkcs1Sign = { 1789 ssl_auth_rsa_sign, nullptr, nullptr, nullptr, nullptr, nullptr}; 1790 static const SSLExtraServerCertData ServerCertDataRsaPss = { 1791 ssl_auth_rsa_pss, nullptr, nullptr, nullptr, nullptr, nullptr}; 1792 1793 // Test RSA cert with usage=[signature, encipherment]. 1794 TEST_F(TlsAgentStreamTestServer, ConfigureCertRsaPkcs1SignAndKEX) { 1795 Reset(TlsAgent::kServerRsa); 1796 1797 PRFileDesc* ssl_fd = agent_->ssl_fd(); 1798 EXPECT_TRUE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_decrypt)); 1799 EXPECT_TRUE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_sign)); 1800 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_pss)); 1801 1802 // Configuring for only rsa_sign or rsa_decrypt should work. 1803 EXPECT_TRUE(agent_->ConfigServerCert(TlsAgent::kServerRsa, false, 1804 &ServerCertDataRsaPkcs1Decrypt)); 1805 EXPECT_TRUE(agent_->ConfigServerCert(TlsAgent::kServerRsa, false, 1806 &ServerCertDataRsaPkcs1Sign)); 1807 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsa, false, 1808 &ServerCertDataRsaPss)); 1809 } 1810 1811 // Test RSA cert with usage=[signature]. 1812 TEST_F(TlsAgentStreamTestServer, ConfigureCertRsaPkcs1Sign) { 1813 Reset(TlsAgent::kServerRsaSign); 1814 1815 PRFileDesc* ssl_fd = agent_->ssl_fd(); 1816 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_decrypt)); 1817 EXPECT_TRUE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_sign)); 1818 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_pss)); 1819 1820 // Configuring for only rsa_decrypt should fail. 1821 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaSign, false, 1822 &ServerCertDataRsaPkcs1Decrypt)); 1823 1824 // Configuring for only rsa_sign should work. 1825 EXPECT_TRUE(agent_->ConfigServerCert(TlsAgent::kServerRsaSign, false, 1826 &ServerCertDataRsaPkcs1Sign)); 1827 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaSign, false, 1828 &ServerCertDataRsaPss)); 1829 } 1830 1831 // Test RSA cert with usage=[encipherment]. 1832 TEST_F(TlsAgentStreamTestServer, ConfigureCertRsaPkcs1KEX) { 1833 Reset(TlsAgent::kServerRsaDecrypt); 1834 1835 PRFileDesc* ssl_fd = agent_->ssl_fd(); 1836 EXPECT_TRUE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_decrypt)); 1837 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_sign)); 1838 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_pss)); 1839 1840 // Configuring for only rsa_sign or rsa_pss should fail. 1841 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaDecrypt, false, 1842 &ServerCertDataRsaPkcs1Sign)); 1843 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaDecrypt, false, 1844 &ServerCertDataRsaPss)); 1845 1846 // Configuring for only rsa_decrypt should work. 1847 EXPECT_TRUE(agent_->ConfigServerCert(TlsAgent::kServerRsaDecrypt, false, 1848 &ServerCertDataRsaPkcs1Decrypt)); 1849 } 1850 1851 // Test configuring an RSA-PSS cert. 1852 TEST_F(TlsAgentStreamTestServer, ConfigureCertRsaPss) { 1853 Reset(TlsAgent::kServerRsaPss); 1854 1855 PRFileDesc* ssl_fd = agent_->ssl_fd(); 1856 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_decrypt)); 1857 EXPECT_FALSE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_sign)); 1858 EXPECT_TRUE(SSLInt_HasCertWithAuthType(ssl_fd, ssl_auth_rsa_pss)); 1859 1860 // Configuring for only rsa_sign or rsa_decrypt should fail. 1861 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaPss, false, 1862 &ServerCertDataRsaPkcs1Sign)); 1863 EXPECT_FALSE(agent_->ConfigServerCert(TlsAgent::kServerRsaPss, false, 1864 &ServerCertDataRsaPkcs1Decrypt)); 1865 1866 // Configuring for only rsa_pss should work. 1867 EXPECT_TRUE(agent_->ConfigServerCert(TlsAgent::kServerRsaPss, false, 1868 &ServerCertDataRsaPss)); 1869 } 1870 1871 // A server should refuse to even start a handshake with 1872 // misconfigured certificate and signature scheme. 1873 TEST_P(TlsConnectTls12Plus, MisconfiguredCertScheme) { 1874 Reset(TlsAgent::kServerRsaSign); 1875 static const SSLSignatureScheme kScheme[] = {ssl_sig_ecdsa_secp256r1_sha256}; 1876 server_->SetSignatureSchemes(kScheme, PR_ARRAY_SIZE(kScheme)); 1877 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1878 if (version_ < SSL_LIBRARY_VERSION_TLS_1_3) { 1879 // TLS 1.2 disables cipher suites, which leads to a different error. 1880 server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1881 } else { 1882 server_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1883 } 1884 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1885 } 1886 1887 // In TLS 1.2, disabling an EC group causes ECDSA to be invalid. 1888 TEST_P(TlsConnectTls12, Tls12CertDisabledGroup) { 1889 Reset(TlsAgent::kServerEcdsa256); 1890 static const std::vector<SSLNamedGroup> k25519 = {ssl_grp_ec_curve25519}; 1891 server_->ConfigNamedGroups(k25519); 1892 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1893 server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1894 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1895 } 1896 1897 // In TLS 1.3, ECDSA configuration only depends on the signature scheme. 1898 TEST_P(TlsConnectTls13, Tls13CertDisabledGroup) { 1899 Reset(TlsAgent::kServerEcdsa256); 1900 static const std::vector<SSLNamedGroup> k25519 = {ssl_grp_ec_curve25519}; 1901 server_->ConfigNamedGroups(k25519); 1902 Connect(); 1903 } 1904 1905 // A client should refuse to even start a handshake with only DSA. 1906 TEST_P(TlsConnectTls13, Tls13DsaOnlyClient) { 1907 static const SSLSignatureScheme kDsa[] = {ssl_sig_dsa_sha256}; 1908 client_->SetSignatureSchemes(kDsa, PR_ARRAY_SIZE(kDsa)); 1909 client_->StartConnect(); 1910 client_->Handshake(); 1911 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 1912 client_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1913 } 1914 1915 #ifndef NSS_DISABLE_DSA 1916 // can't test a dsa only server becasue we can't generate a server 1917 // DSA certificate 1918 TEST_P(TlsConnectTls13, Tls13DsaOnlyServer) { 1919 Reset(TlsAgent::kServerDsa); 1920 static const SSLSignatureScheme kDsa[] = {ssl_sig_dsa_sha256}; 1921 server_->SetSignatureSchemes(kDsa, PR_ARRAY_SIZE(kDsa)); 1922 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1923 server_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1924 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1925 } 1926 #endif 1927 1928 TEST_P(TlsConnectTls13, Tls13Pkcs1OnlyClient) { 1929 static const SSLSignatureScheme kPkcs1[] = {ssl_sig_rsa_pkcs1_sha256}; 1930 client_->SetSignatureSchemes(kPkcs1, PR_ARRAY_SIZE(kPkcs1)); 1931 client_->StartConnect(); 1932 client_->Handshake(); 1933 EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state()); 1934 client_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1935 } 1936 1937 TEST_P(TlsConnectTls13, Tls13Pkcs1OnlyServer) { 1938 static const SSLSignatureScheme kPkcs1[] = {ssl_sig_rsa_pkcs1_sha256}; 1939 server_->SetSignatureSchemes(kPkcs1, PR_ARRAY_SIZE(kPkcs1)); 1940 ConnectExpectAlert(server_, kTlsAlertHandshakeFailure); 1941 server_->CheckErrorCode(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1942 client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP); 1943 } 1944 1945 TEST_P(TlsConnectTls13, Tls13DsaIsNotAdvertisedClient) { 1946 EnsureTlsSetup(); 1947 static const SSLSignatureScheme kSchemes[] = {ssl_sig_dsa_sha256, 1948 ssl_sig_rsa_pss_rsae_sha256}; 1949 client_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 1950 auto capture = 1951 MakeTlsFilter<TlsExtensionCapture>(client_, ssl_signature_algorithms_xtn); 1952 Connect(); 1953 // We should only have the one signature algorithm advertised. 1954 static const uint8_t kExpectedExt[] = {0, 2, ssl_sig_rsa_pss_rsae_sha256 >> 8, 1955 ssl_sig_rsa_pss_rsae_sha256 & 0xff}; 1956 ASSERT_EQ(DataBuffer(kExpectedExt, sizeof(kExpectedExt)), 1957 capture->extension()); 1958 } 1959 1960 TEST_P(TlsConnectTls13, Tls13DsaIsNotAdvertisedServer) { 1961 EnsureTlsSetup(); 1962 static const SSLSignatureScheme kSchemes[] = {ssl_sig_dsa_sha256, 1963 ssl_sig_rsa_pss_rsae_sha256}; 1964 server_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 1965 auto capture = MakeTlsFilter<TlsExtensionCapture>( 1966 server_, ssl_signature_algorithms_xtn, true); 1967 capture->SetHandshakeTypes({kTlsHandshakeCertificateRequest}); 1968 capture->EnableDecryption(); 1969 server_->RequestClientAuth(false); // So we get a CertificateRequest. 1970 Connect(); 1971 // We should only have the one signature algorithm advertised. 1972 static const uint8_t kExpectedExt[] = {0, 2, ssl_sig_rsa_pss_rsae_sha256 >> 8, 1973 ssl_sig_rsa_pss_rsae_sha256 & 0xff}; 1974 ASSERT_EQ(DataBuffer(kExpectedExt, sizeof(kExpectedExt)), 1975 capture->extension()); 1976 } 1977 1978 TEST_P(TlsConnectTls13, Tls13RsaPkcs1IsAdvertisedClient) { 1979 EnsureTlsSetup(); 1980 static const SSLSignatureScheme kSchemes[] = {ssl_sig_rsa_pkcs1_sha256, 1981 ssl_sig_rsa_pss_rsae_sha256}; 1982 client_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 1983 auto capture = 1984 MakeTlsFilter<TlsExtensionCapture>(client_, ssl_signature_algorithms_xtn); 1985 Connect(); 1986 // We should only have the one signature algorithm advertised. 1987 static const uint8_t kExpectedExt[] = {0, 1988 4, 1989 ssl_sig_rsa_pss_rsae_sha256 >> 8, 1990 ssl_sig_rsa_pss_rsae_sha256 & 0xff, 1991 ssl_sig_rsa_pkcs1_sha256 >> 8, 1992 ssl_sig_rsa_pkcs1_sha256 & 0xff}; 1993 ASSERT_EQ(DataBuffer(kExpectedExt, sizeof(kExpectedExt)), 1994 capture->extension()); 1995 } 1996 1997 TEST_P(TlsConnectTls13, Tls13RsaPkcs1IsAdvertisedServer) { 1998 EnsureTlsSetup(); 1999 static const SSLSignatureScheme kSchemes[] = {ssl_sig_rsa_pkcs1_sha256, 2000 ssl_sig_rsa_pss_rsae_sha256}; 2001 server_->SetSignatureSchemes(kSchemes, PR_ARRAY_SIZE(kSchemes)); 2002 auto capture = MakeTlsFilter<TlsExtensionCapture>( 2003 server_, ssl_signature_algorithms_xtn, true); 2004 capture->SetHandshakeTypes({kTlsHandshakeCertificateRequest}); 2005 capture->EnableDecryption(); 2006 server_->RequestClientAuth(false); // So we get a CertificateRequest. 2007 Connect(); 2008 // We should only have the one signature algorithm advertised. 2009 static const uint8_t kExpectedExt[] = {0, 2010 4, 2011 ssl_sig_rsa_pss_rsae_sha256 >> 8, 2012 ssl_sig_rsa_pss_rsae_sha256 & 0xff, 2013 ssl_sig_rsa_pkcs1_sha256 >> 8, 2014 ssl_sig_rsa_pkcs1_sha256 & 0xff}; 2015 ASSERT_EQ(DataBuffer(kExpectedExt, sizeof(kExpectedExt)), 2016 capture->extension()); 2017 } 2018 2019 // variant, version, certificate, auth type, signature scheme 2020 typedef std::tuple<SSLProtocolVariant, uint16_t, std::string, SSLAuthType, 2021 SSLSignatureScheme> 2022 SignatureSchemeProfile; 2023 2024 class TlsSignatureSchemeConfiguration 2025 : public TlsConnectTestBase, 2026 public ::testing::WithParamInterface<SignatureSchemeProfile> { 2027 public: 2028 TlsSignatureSchemeConfiguration() 2029 : TlsConnectTestBase(std::get<0>(GetParam()), std::get<1>(GetParam())), 2030 certificate_(std::get<2>(GetParam())), 2031 auth_type_(std::get<3>(GetParam())), 2032 signature_scheme_(std::get<4>(GetParam())) {} 2033 2034 protected: 2035 void TestSignatureSchemeConfig(std::shared_ptr<TlsAgent>& configPeer) { 2036 EnsureTlsSetup(); 2037 configPeer->SetSignatureSchemes(&signature_scheme_, 1); 2038 Connect(); 2039 CheckKeys(auth_type_, signature_scheme_); 2040 } 2041 2042 std::string certificate_; 2043 SSLAuthType auth_type_; 2044 SSLSignatureScheme signature_scheme_; 2045 }; 2046 2047 TEST_P(TlsSignatureSchemeConfiguration, SignatureSchemeConfigServer) { 2048 Reset(certificate_); 2049 TestSignatureSchemeConfig(server_); 2050 } 2051 2052 TEST_P(TlsSignatureSchemeConfiguration, SignatureSchemeConfigClient) { 2053 Reset(certificate_); 2054 auto capture = 2055 MakeTlsFilter<TlsExtensionCapture>(client_, ssl_signature_algorithms_xtn); 2056 TestSignatureSchemeConfig(client_); 2057 2058 const DataBuffer& ext = capture->extension(); 2059 ASSERT_EQ(2U + 2U, ext.len()); 2060 uint32_t v = 0; 2061 ASSERT_TRUE(ext.Read(0, 2, &v)); 2062 EXPECT_EQ(2U, v); 2063 ASSERT_TRUE(ext.Read(2, 2, &v)); 2064 EXPECT_EQ(signature_scheme_, static_cast<SSLSignatureScheme>(v)); 2065 } 2066 2067 TEST_P(TlsSignatureSchemeConfiguration, SignatureSchemeConfigBoth) { 2068 Reset(certificate_); 2069 EnsureTlsSetup(); 2070 client_->SetSignatureSchemes(&signature_scheme_, 1); 2071 server_->SetSignatureSchemes(&signature_scheme_, 1); 2072 Connect(); 2073 CheckKeys(auth_type_, signature_scheme_); 2074 } 2075 2076 class Tls12CertificateRequestReplacer : public TlsHandshakeFilter { 2077 public: 2078 Tls12CertificateRequestReplacer(const std::shared_ptr<TlsAgent>& a, 2079 SSLSignatureScheme scheme) 2080 : TlsHandshakeFilter(a, {kTlsHandshakeCertificateRequest}), 2081 scheme_(scheme) {} 2082 2083 virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header, 2084 const DataBuffer& input, 2085 DataBuffer* output) { 2086 uint32_t offset = 0; 2087 2088 if (header.handshake_type() != ssl_hs_certificate_request) { 2089 return KEEP; 2090 } 2091 2092 *output = input; 2093 2094 uint32_t types_len = 0; 2095 if (!output->Read(offset, 1, &types_len)) { 2096 ADD_FAILURE(); 2097 return KEEP; 2098 } 2099 offset += 1 + types_len; 2100 uint32_t scheme_len = 0; 2101 if (!output->Read(offset, 2, &scheme_len)) { 2102 ADD_FAILURE(); 2103 return KEEP; 2104 } 2105 DataBuffer schemes; 2106 schemes.Write(0, 2, 2); 2107 schemes.Write(2, scheme_, 2); 2108 output->Write(offset, 2, schemes.len()); 2109 output->Splice(schemes, offset + 2, scheme_len); 2110 2111 return CHANGE; 2112 } 2113 2114 private: 2115 SSLSignatureScheme scheme_; 2116 }; 2117 2118 // 2119 // Test how policy interacts with client auth connections 2120 // 2121 2122 // TLS/DTLS version algorithm policy 2123 typedef std::tuple<SSLProtocolVariant, uint16_t, SECOidTag, PRUint32> 2124 PolicySignatureSchemeProfile; 2125 2126 // Only TLS 1.2 handles client auth schemes inside 2127 // the certificate request packet, so our failure tests for 2128 // those kinds of connections only occur here. 2129 class TlsConnectAuthWithPolicyTls12 2130 : public TlsConnectTestBase, 2131 public ::testing::WithParamInterface<PolicySignatureSchemeProfile> { 2132 public: 2133 TlsConnectAuthWithPolicyTls12() 2134 : TlsConnectTestBase(std::get<0>(GetParam()), std::get<1>(GetParam())) { 2135 alg_ = std::get<2>(GetParam()); 2136 policy_ = std::get<3>(GetParam()); 2137 // use the algorithm to select which single scheme to deploy 2138 // We use these schemes to force servers sending schemes the client 2139 // didn't advertise to make sure the client will still filter these 2140 // by policy and detect that no valid schemes were presented, rather 2141 // than sending an empty client auth message. 2142 switch (alg_) { 2143 case SEC_OID_SHA256: 2144 case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: 2145 scheme_ = ssl_sig_rsa_pss_pss_sha256; 2146 break; 2147 case SEC_OID_PKCS1_RSA_ENCRYPTION: 2148 scheme_ = ssl_sig_rsa_pkcs1_sha256; 2149 break; 2150 case SEC_OID_ANSIX962_EC_PUBLIC_KEY: 2151 scheme_ = ssl_sig_ecdsa_secp256r1_sha256; 2152 break; 2153 default: 2154 ADD_FAILURE() << "need to update algorithm table in " 2155 "TlsConnectAuthWithPolicyTls12"; 2156 scheme_ = ssl_sig_none; 2157 break; 2158 } 2159 } 2160 2161 protected: 2162 SECOidTag alg_; 2163 PRUint32 policy_; 2164 SSLSignatureScheme scheme_; 2165 }; 2166 2167 // Only TLS 1.2 and greater looks at schemes extensions on client auth 2168 class TlsConnectAuthWithPolicyTls12Plus 2169 : public TlsConnectTestBase, 2170 public ::testing::WithParamInterface<PolicySignatureSchemeProfile> { 2171 public: 2172 TlsConnectAuthWithPolicyTls12Plus() 2173 : TlsConnectTestBase(std::get<0>(GetParam()), std::get<1>(GetParam())) { 2174 alg_ = std::get<2>(GetParam()); 2175 policy_ = std::get<3>(GetParam()); 2176 } 2177 2178 protected: 2179 SECOidTag alg_; 2180 PRUint32 policy_; 2181 }; 2182 2183 // make sure we can turn single algorithms off by policy an still connect 2184 // this is basically testing that we are properly filtering our schemes 2185 // by policy before communicating them to the server, and that the 2186 // server is respecting our choices 2187 TEST_P(TlsConnectAuthWithPolicyTls12Plus, PolicySuccessTest) { 2188 // in TLS 1.3, RSA PKCS1 is restricted. If we are also 2189 // restricting RSA PSS by policy, we can't use the default 2190 // RSA certificate as the server cert, switch to ECDSA 2191 if ((version_ >= SSL_LIBRARY_VERSION_TLS_1_3) && 2192 (alg_ == SEC_OID_PKCS1_RSA_PSS_SIGNATURE)) { 2193 Reset(TlsAgent::kServerEcdsa256); 2194 } 2195 client_->SetPolicy(alg_, 0, policy_); // Disable policy for client 2196 client_->SetupClientAuth(); 2197 server_->RequestClientAuth(false); 2198 Connect(); 2199 } 2200 2201 // make sure we fail if the server ignores our policy preference and 2202 // requests client auth with a scheme we don't support 2203 TEST_P(TlsConnectAuthWithPolicyTls12, PolicyFailureTest) { 2204 client_->SetPolicy(alg_, 0, policy_); 2205 client_->SetupClientAuth(); 2206 server_->RequestClientAuth(false); 2207 MakeTlsFilter<Tls12CertificateRequestReplacer>(server_, scheme_); 2208 ConnectExpectAlert(client_, kTlsAlertHandshakeFailure); 2209 client_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 2210 server_->CheckErrorCode(SSL_ERROR_HANDSHAKE_FAILURE_ALERT); 2211 } 2212 2213 INSTANTIATE_TEST_SUITE_P( 2214 SignaturesWithPolicyFail, TlsConnectAuthWithPolicyTls12, 2215 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2216 TlsConnectTestBase::kTlsV12, 2217 ::testing::Values(SEC_OID_SHA256, 2218 SEC_OID_PKCS1_RSA_PSS_SIGNATURE, 2219 SEC_OID_PKCS1_RSA_ENCRYPTION, 2220 SEC_OID_ANSIX962_EC_PUBLIC_KEY), 2221 ::testing::Values(NSS_USE_ALG_IN_SSL_KX, 2222 NSS_USE_ALG_IN_ANY_SIGNATURE))); 2223 2224 INSTANTIATE_TEST_SUITE_P( 2225 SignaturesWithPolicySuccess, TlsConnectAuthWithPolicyTls12Plus, 2226 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2227 TlsConnectTestBase::kTlsV12Plus, 2228 ::testing::Values(SEC_OID_SHA256, 2229 SEC_OID_PKCS1_RSA_PSS_SIGNATURE, 2230 SEC_OID_PKCS1_RSA_ENCRYPTION, 2231 SEC_OID_ANSIX962_EC_PUBLIC_KEY), 2232 ::testing::Values(NSS_USE_ALG_IN_SSL_KX, 2233 NSS_USE_ALG_IN_ANY_SIGNATURE))); 2234 2235 INSTANTIATE_TEST_SUITE_P( 2236 SignatureSchemeRsa, TlsSignatureSchemeConfiguration, 2237 ::testing::Combine( 2238 TlsConnectTestBase::kTlsVariantsAll, TlsConnectTestBase::kTlsV12, 2239 ::testing::Values(TlsAgent::kServerRsaSign), 2240 ::testing::Values(ssl_auth_rsa_sign), 2241 ::testing::Values(ssl_sig_rsa_pkcs1_sha256, ssl_sig_rsa_pkcs1_sha384, 2242 ssl_sig_rsa_pkcs1_sha512, ssl_sig_rsa_pss_rsae_sha256, 2243 ssl_sig_rsa_pss_rsae_sha384))); 2244 // RSASSA-PKCS1-v1_5 is not allowed to be used in TLS 1.3 2245 INSTANTIATE_TEST_SUITE_P( 2246 SignatureSchemeRsaTls13, TlsSignatureSchemeConfiguration, 2247 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2248 TlsConnectTestBase::kTlsV13, 2249 ::testing::Values(TlsAgent::kServerRsaSign), 2250 ::testing::Values(ssl_auth_rsa_sign), 2251 ::testing::Values(ssl_sig_rsa_pss_rsae_sha256, 2252 ssl_sig_rsa_pss_rsae_sha384))); 2253 // PSS with SHA-512 needs a bigger key to work. 2254 INSTANTIATE_TEST_SUITE_P( 2255 SignatureSchemeBigRsa, TlsSignatureSchemeConfiguration, 2256 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2257 TlsConnectTestBase::kTlsV12Plus, 2258 ::testing::Values(TlsAgent::kRsa2048), 2259 ::testing::Values(ssl_auth_rsa_sign), 2260 ::testing::Values(ssl_sig_rsa_pss_rsae_sha512))); 2261 INSTANTIATE_TEST_SUITE_P( 2262 SignatureSchemeRsaSha1, TlsSignatureSchemeConfiguration, 2263 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2264 TlsConnectTestBase::kTlsV12, 2265 ::testing::Values(TlsAgent::kServerRsa), 2266 ::testing::Values(ssl_auth_rsa_sign), 2267 ::testing::Values(ssl_sig_rsa_pkcs1_sha1))); 2268 INSTANTIATE_TEST_SUITE_P( 2269 SignatureSchemeEcdsaP256, TlsSignatureSchemeConfiguration, 2270 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2271 TlsConnectTestBase::kTlsV12Plus, 2272 ::testing::Values(TlsAgent::kServerEcdsa256), 2273 ::testing::Values(ssl_auth_ecdsa), 2274 ::testing::Values(ssl_sig_ecdsa_secp256r1_sha256))); 2275 INSTANTIATE_TEST_SUITE_P( 2276 SignatureSchemeEcdsaP384, TlsSignatureSchemeConfiguration, 2277 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2278 TlsConnectTestBase::kTlsV12Plus, 2279 ::testing::Values(TlsAgent::kServerEcdsa384), 2280 ::testing::Values(ssl_auth_ecdsa), 2281 ::testing::Values(ssl_sig_ecdsa_secp384r1_sha384))); 2282 INSTANTIATE_TEST_SUITE_P( 2283 SignatureSchemeEcdsaP521, TlsSignatureSchemeConfiguration, 2284 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2285 TlsConnectTestBase::kTlsV12Plus, 2286 ::testing::Values(TlsAgent::kServerEcdsa521), 2287 ::testing::Values(ssl_auth_ecdsa), 2288 ::testing::Values(ssl_sig_ecdsa_secp521r1_sha512))); 2289 INSTANTIATE_TEST_SUITE_P( 2290 SignatureSchemeEcdsaSha1, TlsSignatureSchemeConfiguration, 2291 ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll, 2292 TlsConnectTestBase::kTlsV12, 2293 ::testing::Values(TlsAgent::kServerEcdsa256, 2294 TlsAgent::kServerEcdsa384), 2295 ::testing::Values(ssl_auth_ecdsa), 2296 ::testing::Values(ssl_sig_ecdsa_sha1))); 2297 } // namespace nss_test