forked from crosswalk-project/chromium-crosswalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssl_client_socket_unittest.cc
3451 lines (2906 loc) · 132 KB
/
ssl_client_socket_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/ssl_client_socket.h"
#include "base/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_data_directory.h"
#include "net/cert/asn1_util.h"
#include "net/cert/ct_verifier.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/test_root_certs.h"
#include "net/dns/host_resolver.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_entry.h"
#include "net/log/test_net_log_util.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/tcp_client_socket.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#if !defined(USE_OPENSSL)
#include <pk11pub.h>
#include "crypto/nss_util.h"
#if !defined(CKM_AES_GCM)
#define CKM_AES_GCM 0x00001087
#endif
#if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
#define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
#endif
#endif
//-----------------------------------------------------------------------------
using testing::_;
using testing::Return;
using testing::Truly;
namespace net {
namespace {
// WrappedStreamSocket is a base class that wraps an existing StreamSocket,
// forwarding the Socket and StreamSocket interfaces to the underlying
// transport.
// This is to provide a common base class for subclasses to override specific
// StreamSocket methods for testing, while still communicating with a 'real'
// StreamSocket.
class WrappedStreamSocket : public StreamSocket {
public:
explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
: transport_(transport.Pass()) {}
~WrappedStreamSocket() override {}
// StreamSocket implementation:
int Connect(const CompletionCallback& callback) override {
return transport_->Connect(callback);
}
void Disconnect() override { transport_->Disconnect(); }
bool IsConnected() const override { return transport_->IsConnected(); }
bool IsConnectedAndIdle() const override {
return transport_->IsConnectedAndIdle();
}
int GetPeerAddress(IPEndPoint* address) const override {
return transport_->GetPeerAddress(address);
}
int GetLocalAddress(IPEndPoint* address) const override {
return transport_->GetLocalAddress(address);
}
const BoundNetLog& NetLog() const override { return transport_->NetLog(); }
void SetSubresourceSpeculation() override {
transport_->SetSubresourceSpeculation();
}
void SetOmniboxSpeculation() override { transport_->SetOmniboxSpeculation(); }
bool WasEverUsed() const override { return transport_->WasEverUsed(); }
bool UsingTCPFastOpen() const override {
return transport_->UsingTCPFastOpen();
}
bool WasNpnNegotiated() const override {
return transport_->WasNpnNegotiated();
}
NextProto GetNegotiatedProtocol() const override {
return transport_->GetNegotiatedProtocol();
}
bool GetSSLInfo(SSLInfo* ssl_info) override {
return transport_->GetSSLInfo(ssl_info);
}
void GetConnectionAttempts(ConnectionAttempts* out) const override {
transport_->GetConnectionAttempts(out);
}
void ClearConnectionAttempts() override {
transport_->ClearConnectionAttempts();
}
void AddConnectionAttempts(const ConnectionAttempts& attempts) override {
transport_->AddConnectionAttempts(attempts);
}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
return transport_->Read(buf, buf_len, callback);
}
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
return transport_->Write(buf, buf_len, callback);
}
int SetReceiveBufferSize(int32 size) override {
return transport_->SetReceiveBufferSize(size);
}
int SetSendBufferSize(int32 size) override {
return transport_->SetSendBufferSize(size);
}
protected:
scoped_ptr<StreamSocket> transport_;
};
// ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
// will ensure a certain amount of data is internally buffered before
// satisfying a Read() request. It exists to mimic OS-level internal
// buffering, but in a way to guarantee that X number of bytes will be
// returned to callers of Read(), regardless of how quickly the OS receives
// them from the TestServer.
class ReadBufferingStreamSocket : public WrappedStreamSocket {
public:
explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
~ReadBufferingStreamSocket() override {}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
// Sets the internal buffer to |size|. This must not be greater than
// the largest value supplied to Read() - that is, it does not handle
// having "leftovers" at the end of Read().
// Each call to Read() will be prevented from completion until at least
// |size| data has been read.
// Set to 0 to turn off buffering, causing Read() to transparently
// read via the underlying transport.
void SetBufferSize(int size);
private:
enum State {
STATE_NONE,
STATE_READ,
STATE_READ_COMPLETE,
};
int DoLoop(int result);
int DoRead();
int DoReadComplete(int result);
void OnReadCompleted(int result);
State state_;
scoped_refptr<GrowableIOBuffer> read_buffer_;
int buffer_size_;
scoped_refptr<IOBuffer> user_read_buf_;
CompletionCallback user_read_callback_;
};
ReadBufferingStreamSocket::ReadBufferingStreamSocket(
scoped_ptr<StreamSocket> transport)
: WrappedStreamSocket(transport.Pass()),
read_buffer_(new GrowableIOBuffer()),
buffer_size_(0) {}
void ReadBufferingStreamSocket::SetBufferSize(int size) {
DCHECK(!user_read_buf_.get());
buffer_size_ = size;
read_buffer_->SetCapacity(size);
}
int ReadBufferingStreamSocket::Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
if (buffer_size_ == 0)
return transport_->Read(buf, buf_len, callback);
if (buf_len < buffer_size_)
return ERR_UNEXPECTED;
state_ = STATE_READ;
user_read_buf_ = buf;
int result = DoLoop(OK);
if (result == ERR_IO_PENDING)
user_read_callback_ = callback;
else
user_read_buf_ = NULL;
return result;
}
int ReadBufferingStreamSocket::DoLoop(int result) {
int rv = result;
do {
State current_state = state_;
state_ = STATE_NONE;
switch (current_state) {
case STATE_READ:
rv = DoRead();
break;
case STATE_READ_COMPLETE:
rv = DoReadComplete(rv);
break;
case STATE_NONE:
default:
NOTREACHED() << "Unexpected state: " << current_state;
rv = ERR_UNEXPECTED;
break;
}
} while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
return rv;
}
int ReadBufferingStreamSocket::DoRead() {
state_ = STATE_READ_COMPLETE;
int rv =
transport_->Read(read_buffer_.get(),
read_buffer_->RemainingCapacity(),
base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
base::Unretained(this)));
return rv;
}
int ReadBufferingStreamSocket::DoReadComplete(int result) {
state_ = STATE_NONE;
if (result <= 0)
return result;
read_buffer_->set_offset(read_buffer_->offset() + result);
if (read_buffer_->RemainingCapacity() > 0) {
state_ = STATE_READ;
return OK;
}
memcpy(user_read_buf_->data(),
read_buffer_->StartOfBuffer(),
read_buffer_->capacity());
read_buffer_->set_offset(0);
return read_buffer_->capacity();
}
void ReadBufferingStreamSocket::OnReadCompleted(int result) {
result = DoLoop(result);
if (result == ERR_IO_PENDING)
return;
user_read_buf_ = NULL;
base::ResetAndReturn(&user_read_callback_).Run(result);
}
// Simulates synchronously receiving an error during Read() or Write()
class SynchronousErrorStreamSocket : public WrappedStreamSocket {
public:
explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
~SynchronousErrorStreamSocket() override {}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
// Sets the next Read() call and all future calls to return |error|.
// If there is already a pending asynchronous read, the configured error
// will not be returned until that asynchronous read has completed and Read()
// is called again.
void SetNextReadError(int error) {
DCHECK_GE(0, error);
have_read_error_ = true;
pending_read_error_ = error;
}
// Sets the next Write() call and all future calls to return |error|.
// If there is already a pending asynchronous write, the configured error
// will not be returned until that asynchronous write has completed and
// Write() is called again.
void SetNextWriteError(int error) {
DCHECK_GE(0, error);
have_write_error_ = true;
pending_write_error_ = error;
}
private:
bool have_read_error_;
int pending_read_error_;
bool have_write_error_;
int pending_write_error_;
DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
};
SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
scoped_ptr<StreamSocket> transport)
: WrappedStreamSocket(transport.Pass()),
have_read_error_(false),
pending_read_error_(OK),
have_write_error_(false),
pending_write_error_(OK) {}
int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
if (have_read_error_)
return pending_read_error_;
return transport_->Read(buf, buf_len, callback);
}
int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
if (have_write_error_)
return pending_write_error_;
return transport_->Write(buf, buf_len, callback);
}
// FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
// underlying transport needing to complete things asynchronously in a
// deterministic manner (e.g.: independent of the TestServer and the OS's
// semantics).
class FakeBlockingStreamSocket : public WrappedStreamSocket {
public:
explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
~FakeBlockingStreamSocket() override {}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int pending_read_result() const { return pending_read_result_; }
IOBuffer* pending_read_buf() const { return pending_read_buf_.get(); }
// Blocks read results on the socket. Reads will not complete until
// UnblockReadResult() has been called and a result is ready from the
// underlying transport. Note: if BlockReadResult() is called while there is a
// hanging asynchronous Read(), that Read is blocked.
void BlockReadResult();
void UnblockReadResult();
// Waits for the blocked Read() call to be complete at the underlying
// transport.
void WaitForReadResult();
// Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
// underlying transport until UnblockWrite() has been called. Note: if there
// is a pending asynchronous write, it is NOT blocked. For purposes of
// blocking writes, data is considered to have reached the underlying
// transport as soon as Write() is called.
void BlockWrite();
void UnblockWrite();
// Waits for the blocked Write() call to be scheduled.
void WaitForWrite();
private:
// Handles completion from the underlying transport read.
void OnReadCompleted(int result);
// True if read callbacks are blocked.
bool should_block_read_;
// The buffer for the pending read, or NULL if not consumed.
scoped_refptr<IOBuffer> pending_read_buf_;
// The user callback for the pending read call.
CompletionCallback pending_read_callback_;
// The result for the blocked read callback, or ERR_IO_PENDING if not
// completed.
int pending_read_result_;
// WaitForReadResult() wait loop.
scoped_ptr<base::RunLoop> read_loop_;
// True if write calls are blocked.
bool should_block_write_;
// The buffer for the pending write, or NULL if not scheduled.
scoped_refptr<IOBuffer> pending_write_buf_;
// The callback for the pending write call.
CompletionCallback pending_write_callback_;
// The length for the pending write, or -1 if not scheduled.
int pending_write_len_;
// WaitForWrite() wait loop.
scoped_ptr<base::RunLoop> write_loop_;
};
FakeBlockingStreamSocket::FakeBlockingStreamSocket(
scoped_ptr<StreamSocket> transport)
: WrappedStreamSocket(transport.Pass()),
should_block_read_(false),
pending_read_result_(ERR_IO_PENDING),
should_block_write_(false),
pending_write_len_(-1) {}
int FakeBlockingStreamSocket::Read(IOBuffer* buf,
int len,
const CompletionCallback& callback) {
DCHECK(!pending_read_buf_);
DCHECK(pending_read_callback_.is_null());
DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
DCHECK(!callback.is_null());
int rv = transport_->Read(buf, len, base::Bind(
&FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
if (rv == ERR_IO_PENDING) {
// Save the callback to be called later.
pending_read_buf_ = buf;
pending_read_callback_ = callback;
} else if (should_block_read_) {
// Save the callback and read result to be called later.
pending_read_buf_ = buf;
pending_read_callback_ = callback;
OnReadCompleted(rv);
rv = ERR_IO_PENDING;
}
return rv;
}
int FakeBlockingStreamSocket::Write(IOBuffer* buf,
int len,
const CompletionCallback& callback) {
DCHECK(buf);
DCHECK_LE(0, len);
if (!should_block_write_)
return transport_->Write(buf, len, callback);
// Schedule the write, but do nothing.
DCHECK(!pending_write_buf_.get());
DCHECK_EQ(-1, pending_write_len_);
DCHECK(pending_write_callback_.is_null());
DCHECK(!callback.is_null());
pending_write_buf_ = buf;
pending_write_len_ = len;
pending_write_callback_ = callback;
// Stop the write loop, if any.
if (write_loop_)
write_loop_->Quit();
return ERR_IO_PENDING;
}
void FakeBlockingStreamSocket::BlockReadResult() {
DCHECK(!should_block_read_);
should_block_read_ = true;
}
void FakeBlockingStreamSocket::UnblockReadResult() {
DCHECK(should_block_read_);
should_block_read_ = false;
// If the operation is still pending in the underlying transport, immediately
// return - OnReadCompleted() will handle invoking the callback once the
// transport has completed.
if (pending_read_result_ == ERR_IO_PENDING)
return;
int result = pending_read_result_;
pending_read_buf_ = nullptr;
pending_read_result_ = ERR_IO_PENDING;
base::ResetAndReturn(&pending_read_callback_).Run(result);
}
void FakeBlockingStreamSocket::WaitForReadResult() {
DCHECK(should_block_read_);
DCHECK(!read_loop_);
if (pending_read_result_ != ERR_IO_PENDING)
return;
read_loop_.reset(new base::RunLoop);
read_loop_->Run();
read_loop_.reset();
DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
}
void FakeBlockingStreamSocket::BlockWrite() {
DCHECK(!should_block_write_);
should_block_write_ = true;
}
void FakeBlockingStreamSocket::UnblockWrite() {
DCHECK(should_block_write_);
should_block_write_ = false;
// Do nothing if UnblockWrite() was called after BlockWrite(),
// without a Write() in between.
if (!pending_write_buf_.get())
return;
int rv = transport_->Write(
pending_write_buf_.get(), pending_write_len_, pending_write_callback_);
pending_write_buf_ = NULL;
pending_write_len_ = -1;
if (rv == ERR_IO_PENDING) {
pending_write_callback_.Reset();
} else {
base::ResetAndReturn(&pending_write_callback_).Run(rv);
}
}
void FakeBlockingStreamSocket::WaitForWrite() {
DCHECK(should_block_write_);
DCHECK(!write_loop_);
if (pending_write_buf_.get())
return;
write_loop_.reset(new base::RunLoop);
write_loop_->Run();
write_loop_.reset();
DCHECK(pending_write_buf_.get());
}
void FakeBlockingStreamSocket::OnReadCompleted(int result) {
DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
DCHECK(!pending_read_callback_.is_null());
if (should_block_read_) {
// Store the result so that the callback can be invoked once Unblock() is
// called.
pending_read_result_ = result;
// Stop the WaitForReadResult() call if any.
if (read_loop_)
read_loop_->Quit();
} else {
// Either the Read() was never blocked or UnblockReadResult() was called
// before the Read() completed. Either way, return the result to the caller.
pending_read_buf_ = nullptr;
base::ResetAndReturn(&pending_read_callback_).Run(result);
}
}
// CountingStreamSocket wraps an existing StreamSocket and maintains a count of
// reads and writes on the socket.
class CountingStreamSocket : public WrappedStreamSocket {
public:
explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
: WrappedStreamSocket(transport.Pass()),
read_count_(0),
write_count_(0) {}
~CountingStreamSocket() override {}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
read_count_++;
return transport_->Read(buf, buf_len, callback);
}
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
write_count_++;
return transport_->Write(buf, buf_len, callback);
}
int read_count() const { return read_count_; }
int write_count() const { return write_count_; }
private:
int read_count_;
int write_count_;
};
// CompletionCallback that will delete the associated StreamSocket when
// the callback is invoked.
class DeleteSocketCallback : public TestCompletionCallbackBase {
public:
explicit DeleteSocketCallback(StreamSocket* socket)
: socket_(socket),
callback_(base::Bind(&DeleteSocketCallback::OnComplete,
base::Unretained(this))) {}
~DeleteSocketCallback() override {}
const CompletionCallback& callback() const { return callback_; }
private:
void OnComplete(int result) {
if (socket_) {
delete socket_;
socket_ = NULL;
} else {
ADD_FAILURE() << "Deleting socket twice";
}
SetResult(result);
}
StreamSocket* socket_;
CompletionCallback callback_;
DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
};
// A ChannelIDStore that always returns an error when asked for a
// channel id.
class FailingChannelIDStore : public ChannelIDStore {
int GetChannelID(const std::string& server_identifier,
base::Time* expiration_time,
std::string* private_key_result,
std::string* cert_result,
const GetChannelIDCallback& callback) override {
return ERR_UNEXPECTED;
}
void SetChannelID(const std::string& server_identifier,
base::Time creation_time,
base::Time expiration_time,
const std::string& private_key,
const std::string& cert) override {}
void DeleteChannelID(const std::string& server_identifier,
const base::Closure& completion_callback) override {}
void DeleteAllCreatedBetween(
base::Time delete_begin,
base::Time delete_end,
const base::Closure& completion_callback) override {}
void DeleteAll(const base::Closure& completion_callback) override {}
void GetAllChannelIDs(const GetChannelIDListCallback& callback) override {}
int GetChannelIDCount() override { return 0; }
void SetForceKeepSessionState() override {}
};
// A ChannelIDStore that asynchronously returns an error when asked for a
// channel id.
class AsyncFailingChannelIDStore : public ChannelIDStore {
int GetChannelID(const std::string& server_identifier,
base::Time* expiration_time,
std::string* private_key_result,
std::string* cert_result,
const GetChannelIDCallback& callback) override {
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
server_identifier, base::Time(), "", ""));
return ERR_IO_PENDING;
}
void SetChannelID(const std::string& server_identifier,
base::Time creation_time,
base::Time expiration_time,
const std::string& private_key,
const std::string& cert) override {}
void DeleteChannelID(const std::string& server_identifier,
const base::Closure& completion_callback) override {}
void DeleteAllCreatedBetween(
base::Time delete_begin,
base::Time delete_end,
const base::Closure& completion_callback) override {}
void DeleteAll(const base::Closure& completion_callback) override {}
void GetAllChannelIDs(const GetChannelIDListCallback& callback) override {}
int GetChannelIDCount() override { return 0; }
void SetForceKeepSessionState() override {}
};
// A mock CTVerifier that records every call to Verify but doesn't verify
// anything.
class MockCTVerifier : public CTVerifier {
public:
MOCK_METHOD5(Verify, int(X509Certificate*,
const std::string&,
const std::string&,
ct::CTVerifyResult*,
const BoundNetLog&));
};
class SSLClientSocketTest : public PlatformTest {
public:
SSLClientSocketTest()
: socket_factory_(ClientSocketFactory::GetDefaultFactory()),
cert_verifier_(new MockCertVerifier),
transport_security_state_(new TransportSecurityState) {
cert_verifier_->set_default_result(OK);
context_.cert_verifier = cert_verifier_.get();
context_.transport_security_state = transport_security_state_.get();
}
protected:
// The address of the spawned test server, after calling StartTestServer().
const AddressList& addr() const { return addr_; }
// The SpawnedTestServer object, after calling StartTestServer().
const SpawnedTestServer* test_server() const { return test_server_.get(); }
void SetCTVerifier(CTVerifier* ct_verifier) {
context_.cert_transparency_verifier = ct_verifier;
}
// Starts the test server with SSL configuration |ssl_options|. Returns true
// on success.
bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
test_server_.reset(new SpawnedTestServer(
SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
if (!test_server_->Start()) {
LOG(ERROR) << "Could not start SpawnedTestServer";
return false;
}
if (!test_server_->GetAddressList(&addr_)) {
LOG(ERROR) << "Could not get SpawnedTestServer address list";
return false;
}
return true;
}
// Sets up a TCP connection to a HTTPS server. To actually do the SSL
// handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
if (!StartTestServer(ssl_options))
return false;
transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
if (rv != OK) {
LOG(ERROR) << "Could not connect to SpawnedTestServer";
return false;
}
return true;
}
scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
scoped_ptr<StreamSocket> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config) {
scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
connection->SetSocket(transport_socket.Pass());
return socket_factory_->CreateSSLClientSocket(
connection.Pass(), host_and_port, ssl_config, context_);
}
// Create an SSLClientSocket object and use it to connect to a test
// server, then wait for connection results. This must be called after
// a successful ConnectToTestServer() call.
// |ssl_config| the SSL configuration to use.
// |result| will retrieve the ::Connect() result value.
// Returns true on success, false otherwise. Success means that the socket
// could be created and its Connect() was called, not that the connection
// itself was a success.
bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
sock_ = CreateSSLClientSocket(
transport_.Pass(), test_server_->host_port_pair(), ssl_config);
if (sock_->IsConnected()) {
LOG(ERROR) << "SSL Socket prematurely connected";
return false;
}
*result = callback_.GetResult(sock_->Connect(callback_.callback()));
return true;
}
ClientSocketFactory* socket_factory_;
scoped_ptr<MockCertVerifier> cert_verifier_;
scoped_ptr<TransportSecurityState> transport_security_state_;
SSLClientSocketContext context_;
scoped_ptr<SSLClientSocket> sock_;
TestNetLog log_;
private:
scoped_ptr<StreamSocket> transport_;
scoped_ptr<SpawnedTestServer> test_server_;
TestCompletionCallback callback_;
AddressList addr_;
};
// Verifies the correctness of GetSSLCertRequestInfo.
class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
protected:
// Creates a test server with the given SSLOptions, connects to it and returns
// the SSLCertRequestInfo reported by the socket.
scoped_refptr<SSLCertRequestInfo> GetCertRequest(
SpawnedTestServer::SSLOptions ssl_options) {
SpawnedTestServer test_server(
SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
if (!test_server.Start())
return NULL;
AddressList addr;
if (!test_server.GetAddressList(&addr))
return NULL;
TestCompletionCallback callback;
TestNetLog log;
scoped_ptr<StreamSocket> transport(
new TCPClientSocket(addr, &log, NetLog::Source()));
int rv = transport->Connect(callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_EQ(OK, rv);
scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
transport.Pass(), test_server.host_port_pair(), SSLConfig()));
EXPECT_FALSE(sock->IsConnected());
rv = sock->Connect(callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
sock->GetSSLCertRequestInfo(request_info.get());
sock->Disconnect();
EXPECT_FALSE(sock->IsConnected());
EXPECT_TRUE(
test_server.host_port_pair().Equals(request_info->host_and_port));
return request_info;
}
};
class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
protected:
// Creates an SSLClientSocket with |client_config| attached to a
// FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
// |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
// so |*out_raw_transport| is a raw pointer.
//
// The client socket will begin a connect using |callback| but stop before the
// server's finished message is received. The finished message will be blocked
// in |*out_raw_transport|. To complete the handshake and successfully read
// data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
// the client successfully false started, |callback.WaitForResult()| will
// return OK without unblocking transport reads. But Read() will still block.)
//
// Must be called after StartTestServer is called.
void CreateAndConnectUntilServerFinishedReceived(
const SSLConfig& client_config,
TestCompletionCallback* callback,
FakeBlockingStreamSocket** out_raw_transport,
scoped_ptr<SSLClientSocket>* out_sock) {
CHECK(test_server());
scoped_ptr<StreamSocket> real_transport(
new TCPClientSocket(addr(), NULL, NetLog::Source()));
scoped_ptr<FakeBlockingStreamSocket> transport(
new FakeBlockingStreamSocket(real_transport.Pass()));
int rv = callback->GetResult(transport->Connect(callback->callback()));
EXPECT_EQ(OK, rv);
FakeBlockingStreamSocket* raw_transport = transport.get();
scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
transport.Pass(), test_server()->host_port_pair(), client_config);
// Connect. Stop before the client processes the first server leg
// (ServerHello, etc.)
raw_transport->BlockReadResult();
rv = sock->Connect(callback->callback());
EXPECT_EQ(ERR_IO_PENDING, rv);
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write
// ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
// server's leg to complete, since it may span multiple reads.)
EXPECT_FALSE(callback->have_result());
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// And, finally, release that and block the next server leg
// (ChangeCipherSpec, Finished).
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
*out_raw_transport = raw_transport;
*out_sock = sock.Pass();
}
void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
const SSLConfig& client_config,
bool expect_false_start) {
ASSERT_TRUE(StartTestServer(server_options));
TestCompletionCallback callback;
FakeBlockingStreamSocket* raw_transport = NULL;
scoped_ptr<SSLClientSocket> sock;
ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
client_config, &callback, &raw_transport, &sock));
if (expect_false_start) {
// When False Starting, the handshake should complete before receiving the
// Change Cipher Spec and Finished messages.
//
// Note: callback.have_result() may not be true without waiting. The NSS
// state machine sometimes lives on a separate thread, so this thread may
// not yet have processed the signal that the handshake has completed.
int rv = callback.WaitForResult();
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock->IsConnected());
const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
static const int kRequestTextSize =
static_cast<int>(arraysize(request_text) - 1);
scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
memcpy(request_buffer->data(), request_text, kRequestTextSize);
// Write the request.
rv = callback.GetResult(sock->Write(request_buffer.get(),
kRequestTextSize,
callback.callback()));
EXPECT_EQ(kRequestTextSize, rv);
// The read will hang; it's waiting for the peer to complete the
// handshake, and the handshake is still blocked.
scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
rv = sock->Read(buf.get(), 4096, callback.callback());
// After releasing reads, the connection proceeds.
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_LT(0, rv);
} else {
// False Start is not enabled, so the handshake will not complete because
// the server second leg is blocked.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
}
}
};
class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
protected:
void EnableChannelID() {
channel_id_service_.reset(new ChannelIDService(
new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
context_.channel_id_service = channel_id_service_.get();
}
void EnableFailingChannelID() {
channel_id_service_.reset(new ChannelIDService(
new FailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
context_.channel_id_service = channel_id_service_.get();
}
void EnableAsyncFailingChannelID() {
channel_id_service_.reset(new ChannelIDService(
new AsyncFailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
context_.channel_id_service = channel_id_service_.get();
}
private:
scoped_ptr<ChannelIDService> channel_id_service_;
};
//-----------------------------------------------------------------------------
// LogContainsSSLConnectEndEvent returns true if the given index in the given
// log is an SSL connect end event. The NSS sockets will cork in an attempt to
// merge the first application data record with the Finished message when false
// starting. However, in order to avoid the server timing out the handshake,
// they'll give up waiting for application data and send the Finished after a
// timeout. This means that an SSL connect end event may appear as a socket
// write.
static bool LogContainsSSLConnectEndEvent(const TestNetLogEntry::List& log,
int i) {
return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
LogContainsEvent(
log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
}
bool SupportsAESGCM() {
#if defined(USE_OPENSSL)
return true;
#else
crypto::EnsureNSSInit();
return PK11_TokenExists(CKM_AES_GCM) &&
PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
#endif
}
} // namespace