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