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 <functional>
8 #include <memory>
9 #include <vector>
10 #include "secerr.h"
11 #include "ssl.h"
12 #include "sslerr.h"
13 #include "sslproto.h"
14 
15 extern "C" {
16 // This is not something that should make you happy.
17 #include "libssl_internals.h"
18 }
19 
20 #include "gtest_utils.h"
21 #include "nss_scoped_ptrs.h"
22 #include "tls_connect.h"
23 #include "tls_filter.h"
24 #include "tls_parser.h"
25 
26 namespace nss_test {
27 
TEST_P(TlsConnectGeneric,SetupOnly)28 TEST_P(TlsConnectGeneric, SetupOnly) {}
29 
TEST_P(TlsConnectGeneric,Connect)30 TEST_P(TlsConnectGeneric, Connect) {
31   SetExpectedVersion(std::get<1>(GetParam()));
32   Connect();
33   CheckKeys();
34 }
35 
TEST_P(TlsConnectGeneric,ConnectEcdsa)36 TEST_P(TlsConnectGeneric, ConnectEcdsa) {
37   SetExpectedVersion(std::get<1>(GetParam()));
38   Reset(TlsAgent::kServerEcdsa256);
39   Connect();
40   CheckKeys(ssl_kea_ecdh, ssl_auth_ecdsa);
41 }
42 
TEST_P(TlsConnectGeneric,CipherSuiteMismatch)43 TEST_P(TlsConnectGeneric, CipherSuiteMismatch) {
44   EnsureTlsSetup();
45   if (version_ >= SSL_LIBRARY_VERSION_TLS_1_3) {
46     client_->EnableSingleCipher(TLS_AES_128_GCM_SHA256);
47     server_->EnableSingleCipher(TLS_AES_256_GCM_SHA384);
48   } else {
49     client_->EnableSingleCipher(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
50     server_->EnableSingleCipher(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
51   }
52   ConnectExpectAlert(server_, kTlsAlertHandshakeFailure);
53   client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
54   server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
55 }
56 
57 class TlsAlertRecorder : public TlsRecordFilter {
58  public:
TlsAlertRecorder(const std::shared_ptr<TlsAgent> & a)59   TlsAlertRecorder(const std::shared_ptr<TlsAgent>& a)
60       : TlsRecordFilter(a), level_(255), description_(255) {}
61 
FilterRecord(const TlsRecordHeader & header,const DataBuffer & input,DataBuffer * output)62   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
63                                     const DataBuffer& input,
64                                     DataBuffer* output) override {
65     if (level_ != 255) {  // Already captured.
66       return KEEP;
67     }
68     if (header.content_type() != ssl_ct_alert) {
69       return KEEP;
70     }
71 
72     std::cerr << "Alert: " << input << std::endl;
73 
74     TlsParser parser(input);
75     EXPECT_TRUE(parser.Read(&level_));
76     EXPECT_TRUE(parser.Read(&description_));
77     return KEEP;
78   }
79 
level() const80   uint8_t level() const { return level_; }
description() const81   uint8_t description() const { return description_; }
82 
83  private:
84   uint8_t level_;
85   uint8_t description_;
86 };
87 
88 class HelloTruncator : public TlsHandshakeFilter {
89  public:
HelloTruncator(const std::shared_ptr<TlsAgent> & a)90   HelloTruncator(const std::shared_ptr<TlsAgent>& a)
91       : TlsHandshakeFilter(
92             a, {kTlsHandshakeClientHello, kTlsHandshakeServerHello}) {}
FilterHandshake(const HandshakeHeader & header,const DataBuffer & input,DataBuffer * output)93   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
94                                        const DataBuffer& input,
95                                        DataBuffer* output) override {
96     output->Assign(input.data(), input.len() - 1);
97     return CHANGE;
98   }
99 };
100 
101 // Verify that when NSS reports that an alert is sent, it is actually sent.
TEST_P(TlsConnectGeneric,CaptureAlertServer)102 TEST_P(TlsConnectGeneric, CaptureAlertServer) {
103   MakeTlsFilter<HelloTruncator>(client_);
104   auto alert_recorder = MakeTlsFilter<TlsAlertRecorder>(server_);
105 
106   ConnectExpectAlert(server_, kTlsAlertDecodeError);
107   EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
108   EXPECT_EQ(kTlsAlertDecodeError, alert_recorder->description());
109 }
110 
TEST_P(TlsConnectGenericPre13,CaptureAlertClient)111 TEST_P(TlsConnectGenericPre13, CaptureAlertClient) {
112   MakeTlsFilter<HelloTruncator>(server_);
113   auto alert_recorder = MakeTlsFilter<TlsAlertRecorder>(client_);
114 
115   ConnectExpectAlert(client_, kTlsAlertDecodeError);
116   EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
117   EXPECT_EQ(kTlsAlertDecodeError, alert_recorder->description());
118 }
119 
120 // In TLS 1.3, the server can't read the client alert.
TEST_P(TlsConnectTls13,CaptureAlertClient)121 TEST_P(TlsConnectTls13, CaptureAlertClient) {
122   MakeTlsFilter<HelloTruncator>(server_);
123   auto alert_recorder = MakeTlsFilter<TlsAlertRecorder>(client_);
124 
125   StartConnect();
126 
127   client_->Handshake();
128   client_->ExpectSendAlert(kTlsAlertDecodeError);
129   server_->Handshake();
130   client_->Handshake();
131   if (variant_ == ssl_variant_stream) {
132     // DTLS just drops the alert it can't decrypt.
133     server_->ExpectSendAlert(kTlsAlertUnexpectedMessage);
134   }
135   server_->Handshake();
136   EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
137   EXPECT_EQ(kTlsAlertDecodeError, alert_recorder->description());
138 }
139 
TEST_P(TlsConnectGenericPre13,ConnectFalseStart)140 TEST_P(TlsConnectGenericPre13, ConnectFalseStart) {
141   client_->EnableFalseStart();
142   Connect();
143   SendReceive();
144 }
145 
TEST_P(TlsConnectGeneric,ConnectAlpn)146 TEST_P(TlsConnectGeneric, ConnectAlpn) {
147   EnableAlpn();
148   Connect();
149   CheckAlpn("a");
150 }
151 
TEST_P(TlsConnectGeneric,ConnectAlpnPriorityA)152 TEST_P(TlsConnectGeneric, ConnectAlpnPriorityA) {
153   // "alpn" "npn"
154   // alpn is the fallback here. npn has the highest priority and should be
155   // picked.
156   const std::vector<uint8_t> alpn = {0x04, 0x61, 0x6c, 0x70, 0x6e,
157                                      0x03, 0x6e, 0x70, 0x6e};
158   EnableAlpn(alpn);
159   Connect();
160   CheckAlpn("npn");
161 }
162 
TEST_P(TlsConnectGeneric,ConnectAlpnPriorityB)163 TEST_P(TlsConnectGeneric, ConnectAlpnPriorityB) {
164   // "alpn" "npn" "http"
165   // npn has the highest priority and should be picked.
166   const std::vector<uint8_t> alpn = {0x04, 0x61, 0x6c, 0x70, 0x6e, 0x03, 0x6e,
167                                      0x70, 0x6e, 0x04, 0x68, 0x74, 0x74, 0x70};
168   EnableAlpn(alpn);
169   Connect();
170   CheckAlpn("npn");
171 }
172 
TEST_P(TlsConnectGeneric,ConnectAlpnClone)173 TEST_P(TlsConnectGeneric, ConnectAlpnClone) {
174   EnsureModelSockets();
175   client_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
176   server_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
177   Connect();
178   CheckAlpn("a");
179 }
180 
TEST_P(TlsConnectGeneric,ConnectAlpnWithCustomCallbackA)181 TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackA) {
182   // "ab" "alpn"
183   const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
184                                             0x61, 0x6c, 0x70, 0x6e};
185   EnableAlpnWithCallback(client_alpn, "alpn");
186   Connect();
187   CheckAlpn("alpn");
188 }
189 
TEST_P(TlsConnectGeneric,ConnectAlpnWithCustomCallbackB)190 TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackB) {
191   // "ab" "alpn"
192   const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
193                                             0x61, 0x6c, 0x70, 0x6e};
194   EnableAlpnWithCallback(client_alpn, "ab");
195   Connect();
196   CheckAlpn("ab");
197 }
198 
TEST_P(TlsConnectGeneric,ConnectAlpnWithCustomCallbackC)199 TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackC) {
200   // "cd" "npn" "alpn"
201   const std::vector<uint8_t> client_alpn = {0x02, 0x63, 0x64, 0x03, 0x6e, 0x70,
202                                             0x6e, 0x04, 0x61, 0x6c, 0x70, 0x6e};
203   EnableAlpnWithCallback(client_alpn, "npn");
204   Connect();
205   CheckAlpn("npn");
206 }
207 
TEST_P(TlsConnectDatagram,ConnectSrtp)208 TEST_P(TlsConnectDatagram, ConnectSrtp) {
209   EnableSrtp();
210   Connect();
211   CheckSrtp();
212   SendReceive();
213 }
214 
TEST_P(TlsConnectGeneric,ConnectSendReceive)215 TEST_P(TlsConnectGeneric, ConnectSendReceive) {
216   Connect();
217   SendReceive();
218 }
219 
220 class SaveTlsRecord : public TlsRecordFilter {
221  public:
SaveTlsRecord(const std::shared_ptr<TlsAgent> & a,size_t index)222   SaveTlsRecord(const std::shared_ptr<TlsAgent>& a, size_t index)
223       : TlsRecordFilter(a), index_(index), count_(0), contents_() {}
224 
contents() const225   const DataBuffer& contents() const { return contents_; }
226 
227  protected:
FilterRecord(const TlsRecordHeader & header,const DataBuffer & data,DataBuffer * changed)228   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
229                                     const DataBuffer& data,
230                                     DataBuffer* changed) override {
231     if (count_++ == index_) {
232       contents_ = data;
233     }
234     return KEEP;
235   }
236 
237  private:
238   const size_t index_;
239   size_t count_;
240   DataBuffer contents_;
241 };
242 
243 // Check that decrypting filters work and can read any record.
244 // This test (currently) only works in TLS 1.3 where we can decrypt.
TEST_F(TlsConnectStreamTls13,DecryptRecordClient)245 TEST_F(TlsConnectStreamTls13, DecryptRecordClient) {
246   EnsureTlsSetup();
247   // 0 = ClientHello, 1 = Finished, 2 = SendReceive, 3 = SendBuffer
248   auto saved = MakeTlsFilter<SaveTlsRecord>(client_, 3);
249   saved->EnableDecryption();
250   Connect();
251   SendReceive();
252 
253   static const uint8_t data[] = {0xde, 0xad, 0xdc};
254   DataBuffer buf(data, sizeof(data));
255   client_->SendBuffer(buf);
256   EXPECT_EQ(buf, saved->contents());
257 }
258 
TEST_F(TlsConnectStreamTls13,DecryptRecordServer)259 TEST_F(TlsConnectStreamTls13, DecryptRecordServer) {
260   EnsureTlsSetup();
261   // Disable tickets so that we are sure to not get NewSessionTicket.
262   EXPECT_EQ(SECSuccess, SSL_OptionSet(server_->ssl_fd(),
263                                       SSL_ENABLE_SESSION_TICKETS, PR_FALSE));
264   // 0 = ServerHello, 1 = other handshake, 2 = SendReceive, 3 = SendBuffer
265   auto saved = MakeTlsFilter<SaveTlsRecord>(server_, 3);
266   saved->EnableDecryption();
267   Connect();
268   SendReceive();
269 
270   static const uint8_t data[] = {0xde, 0xad, 0xd5};
271   DataBuffer buf(data, sizeof(data));
272   server_->SendBuffer(buf);
273   EXPECT_EQ(buf, saved->contents());
274 }
275 
276 class DropTlsRecord : public TlsRecordFilter {
277  public:
DropTlsRecord(const std::shared_ptr<TlsAgent> & a,size_t index)278   DropTlsRecord(const std::shared_ptr<TlsAgent>& a, size_t index)
279       : TlsRecordFilter(a), index_(index), count_(0) {}
280 
281  protected:
FilterRecord(const TlsRecordHeader & header,const DataBuffer & data,DataBuffer * changed)282   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
283                                     const DataBuffer& data,
284                                     DataBuffer* changed) override {
285     if (count_++ == index_) {
286       return DROP;
287     }
288     return KEEP;
289   }
290 
291  private:
292   const size_t index_;
293   size_t count_;
294 };
295 
296 // Test that decrypting filters work correctly and are able to drop records.
TEST_F(TlsConnectStreamTls13,DropRecordServer)297 TEST_F(TlsConnectStreamTls13, DropRecordServer) {
298   EnsureTlsSetup();
299   // Disable session tickets so that the server doesn't send an extra record.
300   EXPECT_EQ(SECSuccess, SSL_OptionSet(server_->ssl_fd(),
301                                       SSL_ENABLE_SESSION_TICKETS, PR_FALSE));
302 
303   // 0 = ServerHello, 1 = other handshake, 2 = first write
304   auto filter = MakeTlsFilter<DropTlsRecord>(server_, 2);
305   filter->EnableDecryption();
306   Connect();
307   server_->SendData(23, 23);  // This should be dropped, so it won't be counted.
308   server_->ResetSentBytes();
309   SendReceive();
310 }
311 
TEST_F(TlsConnectStreamTls13,DropRecordClient)312 TEST_F(TlsConnectStreamTls13, DropRecordClient) {
313   EnsureTlsSetup();
314   // 0 = ClientHello, 1 = Finished, 2 = first write
315   auto filter = MakeTlsFilter<DropTlsRecord>(client_, 2);
316   filter->EnableDecryption();
317   Connect();
318   client_->SendData(26, 26);  // This should be dropped, so it won't be counted.
319   client_->ResetSentBytes();
320   SendReceive();
321 }
322 
323 // Check that a server can use 0.5 RTT if client authentication isn't enabled.
TEST_P(TlsConnectTls13,WriteBeforeClientFinished)324 TEST_P(TlsConnectTls13, WriteBeforeClientFinished) {
325   EnsureTlsSetup();
326   StartConnect();
327   client_->Handshake();  // ClientHello
328   server_->Handshake();  // ServerHello
329 
330   server_->SendData(10);
331   client_->ReadBytes(10);  // Client should emit the Finished as a side-effect.
332   server_->Handshake();    // Server consumes the Finished.
333   CheckConnected();
334 }
335 
336 // We don't allow 0.5 RTT if client authentication is requested.
TEST_P(TlsConnectTls13,WriteBeforeClientFinishedClientAuth)337 TEST_P(TlsConnectTls13, WriteBeforeClientFinishedClientAuth) {
338   client_->SetupClientAuth();
339   server_->RequestClientAuth(false);
340   StartConnect();
341   client_->Handshake();  // ClientHello
342   server_->Handshake();  // ServerHello
343 
344   static const uint8_t data[] = {1, 2, 3};
345   EXPECT_GT(0, PR_Write(server_->ssl_fd(), data, sizeof(data)));
346   EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError());
347 
348   Handshake();
349   CheckConnected();
350   SendReceive();
351 }
352 
353 // 0.5 RTT should fail with client authentication required.
TEST_P(TlsConnectTls13,WriteBeforeClientFinishedClientAuthRequired)354 TEST_P(TlsConnectTls13, WriteBeforeClientFinishedClientAuthRequired) {
355   client_->SetupClientAuth();
356   server_->RequestClientAuth(true);
357   StartConnect();
358   client_->Handshake();  // ClientHello
359   server_->Handshake();  // ServerHello
360 
361   static const uint8_t data[] = {1, 2, 3};
362   EXPECT_GT(0, PR_Write(server_->ssl_fd(), data, sizeof(data)));
363   EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError());
364 
365   Handshake();
366   CheckConnected();
367   SendReceive();
368 }
369 
370 // The next two tests takes advantage of the fact that we
371 // automatically read the first 1024 bytes, so if
372 // we provide 1200 bytes, they overrun the read buffer
373 // provided by the calling test.
374 
375 // DTLS should return an error.
TEST_P(TlsConnectDatagram,ShortRead)376 TEST_P(TlsConnectDatagram, ShortRead) {
377   Connect();
378   client_->ExpectReadWriteError();
379   server_->SendData(50, 50);
380   client_->ReadBytes(20);
381   EXPECT_EQ(0U, client_->received_bytes());
382   EXPECT_EQ(SSL_ERROR_RX_SHORT_DTLS_READ, PORT_GetError());
383 
384   // Now send and receive another packet.
385   server_->ResetSentBytes();  // Reset the counter.
386   SendReceive();
387 }
388 
389 // TLS should get the write in two chunks.
TEST_P(TlsConnectStream,ShortRead)390 TEST_P(TlsConnectStream, ShortRead) {
391   // This test behaves oddly with TLS 1.0 because of 1/n+1 splitting,
392   // so skip in that case.
393   if (version_ < SSL_LIBRARY_VERSION_TLS_1_1) GTEST_SKIP();
394 
395   Connect();
396   server_->SendData(50, 50);
397   // Read the first tranche.
398   client_->ReadBytes(20);
399   ASSERT_EQ(20U, client_->received_bytes());
400   // The second tranche should now immediately be available.
401   client_->ReadBytes();
402   ASSERT_EQ(50U, client_->received_bytes());
403 }
404 
405 // We enable compression via the API but it's disabled internally,
406 // so we should never get it.
TEST_P(TlsConnectGeneric,ConnectWithCompressionEnabled)407 TEST_P(TlsConnectGeneric, ConnectWithCompressionEnabled) {
408   EnsureTlsSetup();
409   client_->SetOption(SSL_ENABLE_DEFLATE, PR_TRUE);
410   server_->SetOption(SSL_ENABLE_DEFLATE, PR_TRUE);
411   Connect();
412   EXPECT_FALSE(client_->is_compressed());
413   SendReceive();
414 }
415 
416 class TlsHolddownTest : public TlsConnectDatagram {
417  protected:
418   // This causes all timers to run to completion.  It advances the clock and
419   // handshakes on both peers until both peers have no more timers pending,
420   // which should happen at the end of a handshake.  This is necessary to ensure
421   // that the relatively long holddown timer expires, but that any other timers
422   // also expire and run correctly.
RunAllTimersDown()423   void RunAllTimersDown() {
424     while (true) {
425       PRIntervalTime time;
426       SECStatus rv = DTLS_GetHandshakeTimeout(client_->ssl_fd(), &time);
427       if (rv != SECSuccess) {
428         rv = DTLS_GetHandshakeTimeout(server_->ssl_fd(), &time);
429         if (rv != SECSuccess) {
430           break;  // Neither peer has an outstanding timer.
431         }
432       }
433 
434       if (g_ssl_gtest_verbose) {
435         std::cerr << "Shifting timers" << std::endl;
436       }
437       ShiftDtlsTimers();
438       Handshake();
439     }
440   }
441 };
442 
TEST_P(TlsHolddownTest,TestDtlsHolddownExpiry)443 TEST_P(TlsHolddownTest, TestDtlsHolddownExpiry) {
444   Connect();
445   std::cerr << "Expiring holddown timer" << std::endl;
446   RunAllTimersDown();
447   SendReceive();
448   if (version_ >= SSL_LIBRARY_VERSION_TLS_1_3) {
449     // One for send, one for receive.
450     EXPECT_EQ(2, SSLInt_CountCipherSpecs(client_->ssl_fd()));
451   }
452 }
453 
TEST_P(TlsHolddownTest,TestDtlsHolddownExpiryResumption)454 TEST_P(TlsHolddownTest, TestDtlsHolddownExpiryResumption) {
455   ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
456   Connect();
457   SendReceive();
458 
459   Reset();
460   ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
461   ExpectResumption(RESUME_TICKET);
462   Connect();
463   RunAllTimersDown();
464   SendReceive();
465   // One for send, one for receive.
466   EXPECT_EQ(2, SSLInt_CountCipherSpecs(client_->ssl_fd()));
467 }
468 
469 class TlsPreCCSHeaderInjector : public TlsRecordFilter {
470  public:
TlsPreCCSHeaderInjector(const std::shared_ptr<TlsAgent> & a)471   TlsPreCCSHeaderInjector(const std::shared_ptr<TlsAgent>& a)
472       : TlsRecordFilter(a) {}
FilterRecord(const TlsRecordHeader & record_header,const DataBuffer & input,size_t * offset,DataBuffer * output)473   virtual PacketFilter::Action FilterRecord(
474       const TlsRecordHeader& record_header, const DataBuffer& input,
475       size_t* offset, DataBuffer* output) override {
476     if (record_header.content_type() != ssl_ct_change_cipher_spec) {
477       return KEEP;
478     }
479 
480     std::cerr << "Injecting Finished header before CCS\n";
481     const uint8_t hhdr[] = {kTlsHandshakeFinished, 0x00, 0x00, 0x0c};
482     DataBuffer hhdr_buf(hhdr, sizeof(hhdr));
483     TlsRecordHeader nhdr(record_header.variant(), record_header.version(),
484                          ssl_ct_handshake, 0);
485     *offset = nhdr.Write(output, *offset, hhdr_buf);
486     *offset = record_header.Write(output, *offset, input);
487     return CHANGE;
488   }
489 };
490 
TEST_P(TlsConnectStreamPre13,ClientFinishedHeaderBeforeCCS)491 TEST_P(TlsConnectStreamPre13, ClientFinishedHeaderBeforeCCS) {
492   MakeTlsFilter<TlsPreCCSHeaderInjector>(client_);
493   ConnectExpectAlert(server_, kTlsAlertUnexpectedMessage);
494   client_->CheckErrorCode(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT);
495   server_->CheckErrorCode(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
496 }
497 
TEST_P(TlsConnectStreamPre13,ServerFinishedHeaderBeforeCCS)498 TEST_P(TlsConnectStreamPre13, ServerFinishedHeaderBeforeCCS) {
499   MakeTlsFilter<TlsPreCCSHeaderInjector>(server_);
500   StartConnect();
501   ExpectAlert(client_, kTlsAlertUnexpectedMessage);
502   Handshake();
503   EXPECT_EQ(TlsAgent::STATE_ERROR, client_->state());
504   client_->CheckErrorCode(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
505   EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state());
506   server_->Handshake();  // Make sure alert is consumed.
507 }
508 
TEST_P(TlsConnectTls13,UnknownAlert)509 TEST_P(TlsConnectTls13, UnknownAlert) {
510   Connect();
511   server_->ExpectSendAlert(0xff, kTlsAlertWarning);
512   client_->ExpectReceiveAlert(0xff, kTlsAlertWarning);
513   SSLInt_SendAlert(server_->ssl_fd(), kTlsAlertWarning,
514                    0xff);  // Unknown value.
515   client_->ExpectReadWriteError();
516   client_->WaitForErrorCode(SSL_ERROR_RX_UNKNOWN_ALERT, 2000);
517 }
518 
TEST_P(TlsConnectTls13,AlertWrongLevel)519 TEST_P(TlsConnectTls13, AlertWrongLevel) {
520   Connect();
521   server_->ExpectSendAlert(kTlsAlertUnexpectedMessage, kTlsAlertWarning);
522   client_->ExpectReceiveAlert(kTlsAlertUnexpectedMessage, kTlsAlertWarning);
523   SSLInt_SendAlert(server_->ssl_fd(), kTlsAlertWarning,
524                    kTlsAlertUnexpectedMessage);
525   client_->ExpectReadWriteError();
526   client_->WaitForErrorCode(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT, 2000);
527 }
528 
TEST_P(TlsConnectTls13,UnknownRecord)529 TEST_P(TlsConnectTls13, UnknownRecord) {
530   static const uint8_t kUknownRecord[] = {
531       0xff, SSL_LIBRARY_VERSION_TLS_1_2 >> 8,
532       SSL_LIBRARY_VERSION_TLS_1_2 & 0xff, 0, 0};
533 
534   Connect();
535   if (variant_ == ssl_variant_stream) {
536     // DTLS just drops the record with an invalid type.
537     server_->ExpectSendAlert(kTlsAlertUnexpectedMessage);
538   }
539   client_->SendDirect(DataBuffer(kUknownRecord, sizeof(kUknownRecord)));
540   server_->ExpectReadWriteError();
541   server_->ReadBytes();
542   if (variant_ == ssl_variant_stream) {
543     EXPECT_EQ(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE, server_->error_code());
544   } else {
545     EXPECT_EQ(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, server_->error_code());
546   }
547 }
548 
TEST_F(TlsConnectStreamTls13,Tls13FailedWriteSecondFlight)549 TEST_F(TlsConnectStreamTls13, Tls13FailedWriteSecondFlight) {
550   EnsureTlsSetup();
551   StartConnect();
552   client_->Handshake();
553   server_->Handshake();  // Send first flight.
554   client_->adapter()->SetWriteError(PR_IO_ERROR);
555   client_->Handshake();  // This will get an error, but shouldn't crash.
556   client_->CheckErrorCode(SSL_ERROR_SOCKET_WRITE_FAILURE);
557 }
558 
TEST_P(TlsConnectDatagram,BlockedWrite)559 TEST_P(TlsConnectDatagram, BlockedWrite) {
560   Connect();
561 
562   // Mark the socket as blocked.
563   client_->adapter()->SetWriteError(PR_WOULD_BLOCK_ERROR);
564   static const uint8_t data[] = {1, 2, 3};
565   int32_t rv = PR_Write(client_->ssl_fd(), data, sizeof(data));
566   EXPECT_GT(0, rv);
567   EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError());
568 
569   // Remove the write error and though the previous write failed, future reads
570   // and writes should just work as if it never happened.
571   client_->adapter()->SetWriteError(0);
572   SendReceive();
573 }
574 
TEST_F(TlsConnectTest,ConnectSSLv3)575 TEST_F(TlsConnectTest, ConnectSSLv3) {
576   ConfigureVersion(SSL_LIBRARY_VERSION_3_0);
577   EnableOnlyStaticRsaCiphers();
578   Connect();
579   CheckKeys(ssl_kea_rsa, ssl_grp_none, ssl_auth_rsa_decrypt, ssl_sig_none);
580 }
581 
TEST_F(TlsConnectTest,ConnectSSLv3ClientAuth)582 TEST_F(TlsConnectTest, ConnectSSLv3ClientAuth) {
583   ConfigureVersion(SSL_LIBRARY_VERSION_3_0);
584   EnableOnlyStaticRsaCiphers();
585   client_->SetupClientAuth();
586   server_->RequestClientAuth(true);
587   Connect();
588   CheckKeys(ssl_kea_rsa, ssl_grp_none, ssl_auth_rsa_decrypt, ssl_sig_none);
589 }
590 
ExpectedCbcLen(size_t in,size_t hmac=20,size_t block=16)591 static size_t ExpectedCbcLen(size_t in, size_t hmac = 20, size_t block = 16) {
592   // MAC-then-Encrypt expansion formula:
593   return ((in + hmac + (block - 1)) / block) * block;
594 }
595 
TEST_F(TlsConnectTest,OneNRecordSplitting)596 TEST_F(TlsConnectTest, OneNRecordSplitting) {
597   ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_0);
598   EnsureTlsSetup();
599   ConnectWithCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA);
600   auto records = MakeTlsFilter<TlsRecordRecorder>(server_);
601   // This should be split into 1, 16384 and 20.
602   DataBuffer big_buffer;
603   big_buffer.Allocate(1 + 16384 + 20);
604   server_->SendBuffer(big_buffer);
605   ASSERT_EQ(3U, records->count());
606   EXPECT_EQ(ExpectedCbcLen(1), records->record(0).buffer.len());
607   EXPECT_EQ(ExpectedCbcLen(16384), records->record(1).buffer.len());
608   EXPECT_EQ(ExpectedCbcLen(20), records->record(2).buffer.len());
609 }
610 
611 // We can't test for randomness easily here, but we can test that we don't
612 // produce a zero value, or produce the same value twice.  There are 5 values
613 // here: two ClientHello.random, two ServerHello.random, and one zero value.
614 // Matrix them and fail if any are the same.
TEST_P(TlsConnectGeneric,CheckRandoms)615 TEST_P(TlsConnectGeneric, CheckRandoms) {
616   ConfigureSessionCache(RESUME_NONE, RESUME_NONE);
617 
618   static const size_t random_len = 32;
619   uint8_t crandom1[random_len], srandom1[random_len];
620   uint8_t z[random_len] = {0};
621 
622   auto ch = MakeTlsFilter<TlsHandshakeRecorder>(client_, ssl_hs_client_hello);
623   auto sh = MakeTlsFilter<TlsHandshakeRecorder>(server_, ssl_hs_server_hello);
624   Connect();
625   ASSERT_TRUE(ch->buffer().len() > (random_len + 2));
626   ASSERT_TRUE(sh->buffer().len() > (random_len + 2));
627   memcpy(crandom1, ch->buffer().data() + 2, random_len);
628   memcpy(srandom1, sh->buffer().data() + 2, random_len);
629   EXPECT_NE(0, memcmp(crandom1, srandom1, random_len));
630   EXPECT_NE(0, memcmp(crandom1, z, random_len));
631   EXPECT_NE(0, memcmp(srandom1, z, random_len));
632 
633   Reset();
634   ch = MakeTlsFilter<TlsHandshakeRecorder>(client_, ssl_hs_client_hello);
635   sh = MakeTlsFilter<TlsHandshakeRecorder>(server_, ssl_hs_server_hello);
636   Connect();
637   ASSERT_TRUE(ch->buffer().len() > (random_len + 2));
638   ASSERT_TRUE(sh->buffer().len() > (random_len + 2));
639   const uint8_t* crandom2 = ch->buffer().data() + 2;
640   const uint8_t* srandom2 = sh->buffer().data() + 2;
641 
642   EXPECT_NE(0, memcmp(crandom2, srandom2, random_len));
643   EXPECT_NE(0, memcmp(crandom2, z, random_len));
644   EXPECT_NE(0, memcmp(srandom2, z, random_len));
645 
646   EXPECT_NE(0, memcmp(crandom1, crandom2, random_len));
647   EXPECT_NE(0, memcmp(crandom1, srandom2, random_len));
648   EXPECT_NE(0, memcmp(srandom1, crandom2, random_len));
649   EXPECT_NE(0, memcmp(srandom1, srandom2, random_len));
650 }
651 
FailOnCloseNotify(const PRFileDesc * fd,void * arg,const SSLAlert * alert)652 void FailOnCloseNotify(const PRFileDesc* fd, void* arg, const SSLAlert* alert) {
653   ADD_FAILURE() << "received alert " << alert->description;
654 }
655 
CheckCloseNotify(const PRFileDesc * fd,void * arg,const SSLAlert * alert)656 void CheckCloseNotify(const PRFileDesc* fd, void* arg, const SSLAlert* alert) {
657   *reinterpret_cast<bool*>(arg) = true;
658   EXPECT_EQ(close_notify, alert->description);
659   EXPECT_EQ(alert_warning, alert->level);
660 }
661 
TEST_P(TlsConnectGeneric,ShutdownOneSide)662 TEST_P(TlsConnectGeneric, ShutdownOneSide) {
663   Connect();
664 
665   // Setup to check alerts.
666   EXPECT_EQ(SECSuccess, SSL_AlertSentCallback(server_->ssl_fd(),
667                                               FailOnCloseNotify, nullptr));
668   EXPECT_EQ(SECSuccess, SSL_AlertReceivedCallback(client_->ssl_fd(),
669                                                   FailOnCloseNotify, nullptr));
670 
671   bool client_sent = false;
672   EXPECT_EQ(SECSuccess, SSL_AlertSentCallback(client_->ssl_fd(),
673                                               CheckCloseNotify, &client_sent));
674   bool server_received = false;
675   EXPECT_EQ(SECSuccess,
676             SSL_AlertReceivedCallback(server_->ssl_fd(), CheckCloseNotify,
677                                       &server_received));
678   EXPECT_EQ(PR_SUCCESS, PR_Shutdown(client_->ssl_fd(), PR_SHUTDOWN_SEND));
679 
680   // Make sure that the server reads out the close_notify.
681   uint8_t buf[10];
682   EXPECT_EQ(0, PR_Read(server_->ssl_fd(), buf, sizeof(buf)));
683 
684   // Reading and writing should still work in the one open direction.
685   EXPECT_TRUE(client_sent);
686   EXPECT_TRUE(server_received);
687   server_->SendData(10, 10);
688   client_->ReadBytes(10);
689 
690   // Now close the other side and do the same checks.
691   bool server_sent = false;
692   EXPECT_EQ(SECSuccess, SSL_AlertSentCallback(server_->ssl_fd(),
693                                               CheckCloseNotify, &server_sent));
694   bool client_received = false;
695   EXPECT_EQ(SECSuccess,
696             SSL_AlertReceivedCallback(client_->ssl_fd(), CheckCloseNotify,
697                                       &client_received));
698   EXPECT_EQ(PR_SUCCESS, PR_Shutdown(server_->ssl_fd(), PR_SHUTDOWN_SEND));
699 
700   EXPECT_EQ(0, PR_Read(client_->ssl_fd(), buf, sizeof(buf)));
701   EXPECT_TRUE(server_sent);
702   EXPECT_TRUE(client_received);
703 }
704 
TEST_P(TlsConnectGeneric,ShutdownOneSideThenCloseTcp)705 TEST_P(TlsConnectGeneric, ShutdownOneSideThenCloseTcp) {
706   Connect();
707 
708   bool client_sent = false;
709   EXPECT_EQ(SECSuccess, SSL_AlertSentCallback(client_->ssl_fd(),
710                                               CheckCloseNotify, &client_sent));
711   bool server_received = false;
712   EXPECT_EQ(SECSuccess,
713             SSL_AlertReceivedCallback(server_->ssl_fd(), CheckCloseNotify,
714                                       &server_received));
715   EXPECT_EQ(PR_SUCCESS, PR_Shutdown(client_->ssl_fd(), PR_SHUTDOWN_SEND));
716 
717   // Make sure that the server reads out the close_notify.
718   uint8_t buf[10];
719   EXPECT_EQ(0, PR_Read(server_->ssl_fd(), buf, sizeof(buf)));
720 
721   // Now simulate the underlying connection closing.
722   client_->adapter()->Reset();
723 
724   // Now close the other side and see that things don't explode.
725   EXPECT_EQ(PR_SUCCESS, PR_Shutdown(server_->ssl_fd(), PR_SHUTDOWN_SEND));
726 
727   EXPECT_GT(0, PR_Read(client_->ssl_fd(), buf, sizeof(buf)));
728   EXPECT_EQ(PR_NOT_CONNECTED_ERROR, PR_GetError());
729 }
730 
731 INSTANTIATE_TEST_SUITE_P(
732     GenericStream, TlsConnectGeneric,
733     ::testing::Combine(TlsConnectTestBase::kTlsVariantsStream,
734                        TlsConnectTestBase::kTlsVAll));
735 INSTANTIATE_TEST_SUITE_P(
736     GenericDatagram, TlsConnectGeneric,
737     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
738                        TlsConnectTestBase::kTlsV11Plus));
739 
740 INSTANTIATE_TEST_SUITE_P(StreamOnly, TlsConnectStream,
741                          TlsConnectTestBase::kTlsVAll);
742 INSTANTIATE_TEST_SUITE_P(DatagramOnly, TlsConnectDatagram,
743                          TlsConnectTestBase::kTlsV11Plus);
744 INSTANTIATE_TEST_SUITE_P(DatagramHolddown, TlsHolddownTest,
745                          TlsConnectTestBase::kTlsV11Plus);
746 
747 INSTANTIATE_TEST_SUITE_P(
748     Pre12Stream, TlsConnectPre12,
749     ::testing::Combine(TlsConnectTestBase::kTlsVariantsStream,
750                        TlsConnectTestBase::kTlsV10V11));
751 INSTANTIATE_TEST_SUITE_P(
752     Pre12Datagram, TlsConnectPre12,
753     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
754                        TlsConnectTestBase::kTlsV11));
755 
756 INSTANTIATE_TEST_SUITE_P(Version12Only, TlsConnectTls12,
757                          TlsConnectTestBase::kTlsVariantsAll);
758 #ifndef NSS_DISABLE_TLS_1_3
759 INSTANTIATE_TEST_SUITE_P(Version13Only, TlsConnectTls13,
760                          TlsConnectTestBase::kTlsVariantsAll);
761 #endif
762 
763 INSTANTIATE_TEST_SUITE_P(
764     Pre13Stream, TlsConnectGenericPre13,
765     ::testing::Combine(TlsConnectTestBase::kTlsVariantsStream,
766                        TlsConnectTestBase::kTlsV10ToV12));
767 INSTANTIATE_TEST_SUITE_P(
768     Pre13Datagram, TlsConnectGenericPre13,
769     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
770                        TlsConnectTestBase::kTlsV11V12));
771 INSTANTIATE_TEST_SUITE_P(Pre13StreamOnly, TlsConnectStreamPre13,
772                          TlsConnectTestBase::kTlsV10ToV12);
773 
774 INSTANTIATE_TEST_SUITE_P(Version12Plus, TlsConnectTls12Plus,
775                          ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
776                                             TlsConnectTestBase::kTlsV12Plus));
777 
778 INSTANTIATE_TEST_SUITE_P(
779     GenericStream, TlsConnectGenericResumption,
780     ::testing::Combine(TlsConnectTestBase::kTlsVariantsStream,
781                        TlsConnectTestBase::kTlsVAll,
782                        ::testing::Values(true, false)));
783 INSTANTIATE_TEST_SUITE_P(
784     GenericDatagram, TlsConnectGenericResumption,
785     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
786                        TlsConnectTestBase::kTlsV11Plus,
787                        ::testing::Values(true, false)));
788 
789 INSTANTIATE_TEST_SUITE_P(
790     GenericStream, TlsConnectGenericResumptionToken,
791     ::testing::Combine(TlsConnectTestBase::kTlsVariantsStream,
792                        TlsConnectTestBase::kTlsVAll));
793 INSTANTIATE_TEST_SUITE_P(
794     GenericDatagram, TlsConnectGenericResumptionToken,
795     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
796                        TlsConnectTestBase::kTlsV11Plus));
797 
798 INSTANTIATE_TEST_SUITE_P(GenericDatagram, TlsConnectTls13ResumptionToken,
799                          TlsConnectTestBase::kTlsVariantsAll);
800 
801 }  // namespace nss_test
802