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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
|
// Copyright (c) 2010 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.
// This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
// from AuthCertificateCallback() in
// mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
* Javier Delgadillo <javi@netscape.com>
* Kai Engert <kengert@redhat.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "net/socket/ssl_client_socket_nss.h"
#if defined(USE_SYSTEM_SSL)
#include <dlfcn.h>
#endif
#include <certdb.h>
#include <keyhi.h>
#include <nspr.h>
#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>
#include <pk11pub.h>
#include "base/compiler_specific.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/nss_util.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "net/base/address_list.h"
#include "net/base/cert_verifier.h"
#include "net/base/io_buffer.h"
#include "net/base/net_log.h"
#include "net/base/net_errors.h"
#include "net/base/ssl_cert_request_info.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/ssl_info.h"
#include "net/base/sys_addrinfo.h"
#include "net/ocsp/nss_ocsp.h"
#include "net/socket/client_socket_handle.h"
static const int kRecvBufferSize = 4096;
namespace net {
// State machines are easier to debug if you log state transitions.
// Enable these if you want to see what's going on.
#if 1
#define EnterFunction(x)
#define LeaveFunction(x)
#define GotoState(s) next_handshake_state_ = s
#define LogData(s, len)
#else
#define EnterFunction(x) LOG(INFO) << (void *)this << " " << __FUNCTION__ << \
" enter " << x << \
"; next_handshake_state " << next_handshake_state_
#define LeaveFunction(x) LOG(INFO) << (void *)this << " " << __FUNCTION__ << \
" leave " << x << \
"; next_handshake_state " << next_handshake_state_
#define GotoState(s) do { LOG(INFO) << (void *)this << " " << __FUNCTION__ << \
" jump to state " << s; \
next_handshake_state_ = s; } while (0)
#define LogData(s, len) LOG(INFO) << (void *)this << " " << __FUNCTION__ << \
" data [" << std::string(s, len) << "]";
#endif
namespace {
class NSSSSLInitSingleton {
public:
NSSSSLInitSingleton() {
base::EnsureNSSInit();
NSS_SetDomesticPolicy();
#if defined(USE_SYSTEM_SSL)
// Use late binding to avoid scary but benign warning
// "Symbol `SSL_ImplementedCiphers' has different size in shared object,
// consider re-linking"
// TODO(wtc): Use the new SSL_GetImplementedCiphers and
// SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
if (pSSL_ImplementedCiphers == NULL) {
NOTREACHED() << "Can't get list of supported ciphers";
return;
}
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif
// Explicitly enable exactly those ciphers with keys of at least 80 bits
for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
SSLCipherSuiteInfo info;
if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
sizeof(info)) == SECSuccess) {
SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
(info.effectiveKeyBits >= 80));
}
}
// Enable SSL.
SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
// All other SSL options are set per-session by SSLClientSocket.
}
~NSSSSLInitSingleton() {
// Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
SSL_ClearSessionCache();
}
};
// Initialize the NSS SSL library if it isn't already initialized. This must
// be called before any other NSS SSL functions. This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
Singleton<NSSSSLInitSingleton>::get();
}
// The default error mapping function.
// Maps an NSPR error code to a network error code.
int MapNSPRError(PRErrorCode err) {
// TODO(port): fill this out as we learn what's important
switch (err) {
case PR_WOULD_BLOCK_ERROR:
return ERR_IO_PENDING;
case PR_ADDRESS_NOT_SUPPORTED_ERROR: // For connect.
case PR_NO_ACCESS_RIGHTS_ERROR:
return ERR_ACCESS_DENIED;
case PR_IO_TIMEOUT_ERROR:
return ERR_TIMED_OUT;
case PR_CONNECT_RESET_ERROR:
return ERR_CONNECTION_RESET;
case PR_CONNECT_ABORTED_ERROR:
return ERR_CONNECTION_ABORTED;
case PR_CONNECT_REFUSED_ERROR:
return ERR_CONNECTION_REFUSED;
case PR_HOST_UNREACHABLE_ERROR:
case PR_NETWORK_UNREACHABLE_ERROR:
return ERR_ADDRESS_UNREACHABLE;
case PR_ADDRESS_NOT_AVAILABLE_ERROR:
return ERR_ADDRESS_INVALID;
case SSL_ERROR_SSL_DISABLED:
return ERR_NO_SSL_VERSIONS_ENABLED;
case SSL_ERROR_NO_CYPHER_OVERLAP:
case SSL_ERROR_UNSUPPORTED_VERSION:
return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
return ERR_SSL_PROTOCOL_ERROR;
case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
case SSL_ERROR_BAD_MAC_ALERT:
return ERR_SSL_BAD_RECORD_MAC_ALERT;
case SSL_ERROR_UNSAFE_NEGOTIATION:
return ERR_SSL_UNSAFE_NEGOTIATION;
default: {
if (IS_SSL_ERROR(err)) {
LOG(WARNING) << "Unknown SSL error " << err <<
" mapped to net::ERR_SSL_PROTOCOL_ERROR";
return ERR_SSL_PROTOCOL_ERROR;
}
LOG(WARNING) << "Unknown error " << err <<
" mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
}
// Context-sensitive error mapping functions.
int MapHandshakeError(PRErrorCode err) {
switch (err) {
// If the server closed on us, it is a protocol error.
// Some TLS-intolerant servers do this when we request TLS.
case PR_END_OF_FILE_ERROR:
// The handshake may fail because some signature (for example, the
// signature in the ServerKeyExchange message for an ephemeral
// Diffie-Hellman cipher suite) is invalid.
case SEC_ERROR_BAD_SIGNATURE:
return ERR_SSL_PROTOCOL_ERROR;
default:
return MapNSPRError(err);
}
}
#if defined(OS_WIN)
// A certificate for COMODO EV SGC CA, issued by AddTrust External CA Root,
// causes CertGetCertificateChain to report CERT_TRUST_IS_NOT_VALID_FOR_USAGE.
// It seems to be caused by the szOID_APPLICATION_CERT_POLICIES extension in
// that certificate.
//
// This function is used in the workaround for http://crbug.com/43538
bool IsProblematicComodoEVCACert(const CERTCertificate& cert) {
// Issuer:
// CN = AddTrust External CA Root
// OU = AddTrust External TTP Network
// O = AddTrust AB
// C = SE
static const uint8 kIssuer[] = {
0x30, 0x6f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04,
0x06, 0x13, 0x02, 0x53, 0x45, 0x31, 0x14, 0x30, 0x12, 0x06,
0x03, 0x55, 0x04, 0x0a, 0x13, 0x0b, 0x41, 0x64, 0x64, 0x54,
0x72, 0x75, 0x73, 0x74, 0x20, 0x41, 0x42, 0x31, 0x26, 0x30,
0x24, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x1d, 0x41, 0x64,
0x64, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x45, 0x78, 0x74,
0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x54, 0x54, 0x50, 0x20,
0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x31, 0x22, 0x30,
0x20, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x19, 0x41, 0x64,
0x64, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x45, 0x78, 0x74,
0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x43, 0x41, 0x20, 0x52,
0x6f, 0x6f, 0x74
};
// Serial number: 79:0A:83:4D:48:40:6B:AB:6C:35:2A:D5:1F:42:83:FE.
static const uint8 kSerialNumber[] = {
0x79, 0x0a, 0x83, 0x4d, 0x48, 0x40, 0x6b, 0xab, 0x6c, 0x35,
0x2a, 0xd5, 0x1f, 0x42, 0x83, 0xfe
};
return cert.derIssuer.len == sizeof(kIssuer) &&
memcmp(cert.derIssuer.data, kIssuer, cert.derIssuer.len) == 0 &&
cert.serialNumber.len == sizeof(kSerialNumber) &&
memcmp(cert.serialNumber.data, kSerialNumber,
cert.serialNumber.len) == 0;
}
#endif
} // namespace
#if defined(OS_WIN)
// static
HCERTSTORE SSLClientSocketNSS::cert_store_ = NULL;
#endif
SSLClientSocketNSS::SSLClientSocketNSS(ClientSocketHandle* transport_socket,
const std::string& hostname,
const SSLConfig& ssl_config)
: ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
this, &SSLClientSocketNSS::BufferSendComplete)),
ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
this, &SSLClientSocketNSS::BufferRecvComplete)),
transport_send_busy_(false),
transport_recv_busy_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
this, &SSLClientSocketNSS::OnHandshakeIOComplete)),
transport_(transport_socket),
hostname_(hostname),
ssl_config_(ssl_config),
user_connect_callback_(NULL),
user_read_callback_(NULL),
user_write_callback_(NULL),
user_read_buf_len_(0),
user_write_buf_len_(0),
server_cert_nss_(NULL),
client_auth_cert_needed_(false),
handshake_callback_called_(false),
completed_handshake_(false),
next_handshake_state_(STATE_NONE),
nss_fd_(NULL),
nss_bufs_(NULL),
net_log_(transport_socket->socket()->NetLog()) {
EnterFunction("");
}
SSLClientSocketNSS::~SSLClientSocketNSS() {
EnterFunction("");
Disconnect();
LeaveFunction("");
}
int SSLClientSocketNSS::Init() {
EnterFunction("");
// Initialize the NSS SSL library in a threadsafe way. This also
// initializes the NSS base library.
EnsureNSSSSLInit();
if (!NSS_IsInitialized())
return ERR_UNEXPECTED;
#if !defined(OS_MACOSX) && !defined(OS_WIN)
// We must call EnsureOCSPInit() here, on the IO thread, to get the IO loop
// by MessageLoopForIO::current().
// X509Certificate::Verify() runs on a worker thread of CertVerifier.
EnsureOCSPInit();
#endif
LeaveFunction("");
return OK;
}
int SSLClientSocketNSS::Connect(CompletionCallback* callback) {
EnterFunction("");
DCHECK(transport_.get());
DCHECK(next_handshake_state_ == STATE_NONE);
DCHECK(!user_read_callback_);
DCHECK(!user_write_callback_);
DCHECK(!user_connect_callback_);
DCHECK(!user_read_buf_);
DCHECK(!user_write_buf_);
net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
int rv = Init();
if (rv != OK) {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
return rv;
}
rv = InitializeSSLOptions();
if (rv != OK) {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
return rv;
}
GotoState(STATE_HANDSHAKE);
rv = DoHandshakeLoop(OK);
if (rv == ERR_IO_PENDING) {
user_connect_callback_ = callback;
} else {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
}
LeaveFunction("");
return rv > OK ? OK : rv;
}
int SSLClientSocketNSS::InitializeSSLOptions() {
// Transport connected, now hook it up to nss
// TODO(port): specify rx and tx buffer sizes separately
nss_fd_ = memio_CreateIOLayer(kRecvBufferSize);
if (nss_fd_ == NULL) {
return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
}
// Tell NSS who we're connected to
AddressList peer_address;
int err = transport_->socket()->GetPeerAddress(&peer_address);
if (err != OK)
return err;
const struct addrinfo* ai = peer_address.head();
PRNetAddr peername;
memset(&peername, 0, sizeof(peername));
DCHECK_LE(ai->ai_addrlen, sizeof(peername));
size_t len = std::min(static_cast<size_t>(ai->ai_addrlen), sizeof(peername));
memcpy(&peername, ai->ai_addr, len);
// Adjust the address family field for BSD, whose sockaddr
// structure has a one-byte length and one-byte address family
// field at the beginning. PRNetAddr has a two-byte address
// family field at the beginning.
peername.raw.family = ai->ai_addr->sa_family;
memio_SetPeerName(nss_fd_, &peername);
// Grab pointer to buffers
nss_bufs_ = memio_GetSecret(nss_fd_);
/* Create SSL state machine */
/* Push SSL onto our fake I/O socket */
nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
if (nss_fd_ == NULL) {
return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
}
// TODO(port): set more ssl options! Check errors!
int rv;
rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, ssl_config_.ssl2_enabled);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
// SNI is enabled automatically if TLS is enabled -- as long as
// SSL_V2_COMPATIBLE_HELLO isn't.
// So don't do V2 compatible hellos unless we're really using SSL2,
// to avoid errors like
// "common name `mail.google.com' != requested host name `gmail.com'"
rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO,
ssl_config_.ssl2_enabled);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL3, ssl_config_.ssl3_enabled);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_TLS, ssl_config_.tls1_enabled);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
#ifdef SSL_ENABLE_SESSION_TICKETS
// Support RFC 5077
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
if (rv != SECSuccess)
LOG(INFO) << "SSL_ENABLE_SESSION_TICKETS failed. Old system nss?";
#else
#error "You need to install NSS-3.12 or later to build chromium"
#endif
#ifdef SSL_ENABLE_DEFLATE
// Some web servers have been found to break if TLS is used *or* if DEFLATE
// is advertised. Thus, if TLS is disabled (probably because we are doing
// SSLv3 fallback), we disable DEFLATE also.
// See http://crbug.com/31628
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_DEFLATE, ssl_config_.tls1_enabled);
if (rv != SECSuccess)
LOG(INFO) << "SSL_ENABLE_DEFLATE failed. Old system nss?";
#endif
#ifdef SSL_ENABLE_FALSE_START
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, PR_TRUE);
if (rv != SECSuccess)
LOG(INFO) << "SSL_ENABLE_FALSE_START failed. Old system nss?";
#endif
#ifdef SSL_ENABLE_RENEGOTIATION
if (SSLConfigService::IsKnownStrictTLSServer(hostname_)) {
rv = SSL_OptionSet(nss_fd_, SSL_REQUIRE_SAFE_NEGOTIATION, PR_TRUE);
if (rv != SECSuccess)
LOG(INFO) << "SSL_REQUIRE_SAFE_NEGOTIATION failed.";
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
SSL_RENEGOTIATE_REQUIRES_XTN);
} else {
// We allow servers to request renegotiation. Since we're a client,
// prohibiting this is rather a waste of time. Only servers are in a
// position to prevent renegotiation attacks.
// http://extendedsubset.com/?p=8
rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
SSL_RENEGOTIATE_UNRESTRICTED);
}
if (rv != SECSuccess)
LOG(INFO) << "SSL_ENABLE_RENEGOTIATION failed.";
#endif // SSL_ENABLE_RENEGOTIATION
#ifdef SSL_NEXT_PROTO_NEGOTIATED
if (!ssl_config_.next_protos.empty()) {
rv = SSL_SetNextProtoNego(
nss_fd_,
reinterpret_cast<const unsigned char *>(ssl_config_.next_protos.data()),
ssl_config_.next_protos.size());
if (rv != SECSuccess)
LOG(INFO) << "SSL_SetNextProtoNego failed.";
}
#endif
rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_AuthCertificateHook(nss_fd_, OwnAuthCertHandler, this);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_GetClientAuthDataHook(nss_fd_, ClientAuthHandler, this);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
rv = SSL_HandshakeCallback(nss_fd_, HandshakeCallback, this);
if (rv != SECSuccess)
return ERR_UNEXPECTED;
// Tell SSL the hostname we're trying to connect to.
SSL_SetURL(nss_fd_, hostname_.c_str());
// Set the peer ID for session reuse. This is necessary when we create an
// SSL tunnel through a proxy -- GetPeerName returns the proxy's address
// rather than the destination server's address in that case.
// TODO(wtc): port in |peer_address| is not the server's port when a proxy is
// used.
std::string peer_id = StringPrintf("%s:%d", hostname_.c_str(),
peer_address.GetPort());
rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
if (rv != SECSuccess)
LOG(INFO) << "SSL_SetSockPeerID failed: peer_id=" << peer_id;
// Tell SSL we're a client; needed if not letting NSPR do socket I/O
SSL_ResetHandshake(nss_fd_, 0);
return OK;
}
void SSLClientSocketNSS::InvalidateSessionIfBadCertificate() {
if (UpdateServerCert() != NULL &&
ssl_config_.IsAllowedBadCert(server_cert_)) {
SSL_InvalidateSession(nss_fd_);
}
}
void SSLClientSocketNSS::Disconnect() {
EnterFunction("");
// TODO(wtc): Send SSL close_notify alert.
if (nss_fd_ != NULL) {
InvalidateSessionIfBadCertificate();
PR_Close(nss_fd_);
nss_fd_ = NULL;
}
// Shut down anything that may call us back (through buffer_send_callback_,
// buffer_recv_callback, or handshake_io_callback_).
verifier_.reset();
transport_->socket()->Disconnect();
// Reset object state
transport_send_busy_ = false;
transport_recv_busy_ = false;
user_connect_callback_ = NULL;
user_read_callback_ = NULL;
user_write_callback_ = NULL;
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
server_cert_ = NULL;
if (server_cert_nss_) {
CERT_DestroyCertificate(server_cert_nss_);
server_cert_nss_ = NULL;
}
server_cert_verify_result_.Reset();
completed_handshake_ = false;
nss_bufs_ = NULL;
client_certs_.clear();
client_auth_cert_needed_ = false;
LeaveFunction("");
}
bool SSLClientSocketNSS::IsConnected() const {
// Ideally, we should also check if we have received the close_notify alert
// message from the server, and return false in that case. We're not doing
// that, so this function may return a false positive. Since the upper
// layer (HttpNetworkTransaction) needs to handle a persistent connection
// closed by the server when we send a request anyway, a false positive in
// exchange for simpler code is a good trade-off.
EnterFunction("");
bool ret = completed_handshake_ && transport_->socket()->IsConnected();
LeaveFunction("");
return ret;
}
bool SSLClientSocketNSS::IsConnectedAndIdle() const {
// Unlike IsConnected, this method doesn't return a false positive.
//
// Strictly speaking, we should check if we have received the close_notify
// alert message from the server, and return false in that case. Although
// the close_notify alert message means EOF in the SSL layer, it is just
// bytes to the transport layer below, so
// transport_->socket()->IsConnectedAndIdle() returns the desired false
// when we receive close_notify.
EnterFunction("");
bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
LeaveFunction("");
return ret;
}
int SSLClientSocketNSS::GetPeerAddress(AddressList* address) const {
return transport_->socket()->GetPeerAddress(address);
}
int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
CompletionCallback* callback) {
EnterFunction(buf_len);
DCHECK(completed_handshake_);
DCHECK(next_handshake_state_ == STATE_NONE);
DCHECK(!user_read_callback_);
DCHECK(!user_connect_callback_);
DCHECK(!user_read_buf_);
DCHECK(nss_bufs_);
user_read_buf_ = buf;
user_read_buf_len_ = buf_len;
int rv = DoReadLoop(OK);
if (rv == ERR_IO_PENDING) {
user_read_callback_ = callback;
} else {
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
}
LeaveFunction(rv);
return rv;
}
int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
CompletionCallback* callback) {
EnterFunction(buf_len);
DCHECK(completed_handshake_);
DCHECK(next_handshake_state_ == STATE_NONE);
DCHECK(!user_write_callback_);
DCHECK(!user_connect_callback_);
DCHECK(!user_write_buf_);
DCHECK(nss_bufs_);
user_write_buf_ = buf;
user_write_buf_len_ = buf_len;
int rv = DoWriteLoop(OK);
if (rv == ERR_IO_PENDING) {
user_write_callback_ = callback;
} else {
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
}
LeaveFunction(rv);
return rv;
}
bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
return transport_->socket()->SetReceiveBufferSize(size);
}
bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
return transport_->socket()->SetSendBufferSize(size);
}
#if defined(OS_WIN)
// static
X509Certificate::OSCertHandle SSLClientSocketNSS::CreateOSCert(
const SECItem& der_cert) {
// TODO(wtc): close cert_store_ at shutdown.
if (!cert_store_)
cert_store_ = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, 0, NULL);
X509Certificate::OSCertHandle cert_handle = NULL;
BOOL ok = CertAddEncodedCertificateToStore(
cert_store_, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
der_cert.data, der_cert.len, CERT_STORE_ADD_USE_EXISTING, &cert_handle);
return ok ? cert_handle : NULL;
}
#elif defined(OS_MACOSX)
// static
X509Certificate::OSCertHandle SSLClientSocketNSS::CreateOSCert(
const SECItem& der_cert) {
return X509Certificate::CreateOSCertHandleFromBytes(
reinterpret_cast<char*>(der_cert.data), der_cert.len);
}
#endif
X509Certificate *SSLClientSocketNSS::UpdateServerCert() {
// We set the server_cert_ from OwnAuthCertHandler(), but this handler
// does not necessarily get called if we are continuing a cached SSL
// session.
if (server_cert_ == NULL) {
server_cert_nss_ = SSL_PeerCertificate(nss_fd_);
if (server_cert_nss_) {
#if defined(OS_MACOSX) || defined(OS_WIN)
// Get each of the intermediate certificates in the server's chain.
// These will be added to the server's X509Certificate object, making
// them available to X509Certificate::Verify() for chain building.
X509Certificate::OSCertHandles intermediate_ca_certs;
X509Certificate::OSCertHandle cert_handle = NULL;
CERTCertList* cert_list = CERT_GetCertChainFromCert(
server_cert_nss_, PR_Now(), certUsageSSLCA);
if (cert_list) {
for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
!CERT_LIST_END(node, cert_list);
node = CERT_LIST_NEXT(node)) {
if (node->cert == server_cert_nss_)
continue;
#if defined(OS_WIN)
// Work around http://crbug.com/43538 by not importing the
// problematic COMODO EV SGC CA certificate. CryptoAPI will
// download a good certificate for that CA, issued by COMODO
// Certification Authority, using the AIA extension in the server
// certificate.
if (IsProblematicComodoEVCACert(*node->cert))
continue;
#endif
cert_handle = CreateOSCert(node->cert->derCert);
DCHECK(cert_handle);
intermediate_ca_certs.push_back(cert_handle);
}
CERT_DestroyCertList(cert_list);
}
// Finally create the X509Certificate object.
cert_handle = CreateOSCert(server_cert_nss_->derCert);
DCHECK(cert_handle);
server_cert_ = X509Certificate::CreateFromHandle(
cert_handle,
X509Certificate::SOURCE_FROM_NETWORK,
intermediate_ca_certs);
X509Certificate::FreeOSCertHandle(cert_handle);
for (size_t i = 0; i < intermediate_ca_certs.size(); ++i)
X509Certificate::FreeOSCertHandle(intermediate_ca_certs[i]);
#else
server_cert_ = X509Certificate::CreateFromHandle(
server_cert_nss_,
X509Certificate::SOURCE_FROM_NETWORK,
X509Certificate::OSCertHandles());
#endif
}
}
return server_cert_;
}
// Log an informational message if the server does not support secure
// renegotiation (RFC 5746).
void SSLClientSocketNSS::CheckSecureRenegotiation() const {
// SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6.
// Since SSL_MAX_EXTENSIONS was added at the same time, we can test
// SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension.
#if defined(SSL_MAX_EXTENSIONS)
PRBool received_renego_info;
if (SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
&received_renego_info) == SECSuccess &&
!received_renego_info) {
LOG(INFO) << "The server " << hostname_
<< " does not support the TLS renegotiation_info extension.";
}
#endif
}
void SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
EnterFunction("");
ssl_info->Reset();
if (!server_cert_)
return;
SSLChannelInfo channel_info;
SECStatus ok = SSL_GetChannelInfo(nss_fd_,
&channel_info, sizeof(channel_info));
if (ok == SECSuccess &&
channel_info.length == sizeof(channel_info) &&
channel_info.cipherSuite) {
SSLCipherSuiteInfo cipher_info;
ok = SSL_GetCipherSuiteInfo(channel_info.cipherSuite,
&cipher_info, sizeof(cipher_info));
if (ok == SECSuccess) {
ssl_info->security_bits = cipher_info.effectiveKeyBits;
} else {
ssl_info->security_bits = -1;
LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
<< " for cipherSuite " << channel_info.cipherSuite;
}
ssl_info->connection_status |=
(((int)channel_info.cipherSuite) & SSL_CONNECTION_CIPHERSUITE_MASK) <<
SSL_CONNECTION_CIPHERSUITE_SHIFT;
ssl_info->connection_status |=
(((int)channel_info.compressionMethod) &
SSL_CONNECTION_COMPRESSION_MASK) <<
SSL_CONNECTION_COMPRESSION_SHIFT;
UpdateServerCert();
}
ssl_info->cert_status = server_cert_verify_result_.cert_status;
DCHECK(server_cert_ != NULL);
ssl_info->cert = server_cert_;
PRBool peer_supports_renego_ext;
ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
&peer_supports_renego_ext);
if (ok == SECSuccess) {
if (!peer_supports_renego_ext)
ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
(int)peer_supports_renego_ext, 2);
}
if (ssl_config_.ssl3_fallback)
ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
LeaveFunction("");
}
void SSLClientSocketNSS::GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) {
EnterFunction("");
cert_request_info->host_and_port = hostname_; // TODO(wtc): no port!
cert_request_info->client_certs = client_certs_;
LeaveFunction(cert_request_info->client_certs.size());
}
SSLClientSocket::NextProtoStatus
SSLClientSocketNSS::GetNextProto(std::string* proto) {
#if defined(SSL_NEXT_PROTO_NEGOTIATED)
unsigned char buf[255];
int state;
unsigned len;
SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &len, sizeof(buf));
if (rv != SECSuccess) {
NOTREACHED() << "Error return from SSL_GetNextProto: " << rv;
proto->clear();
return kNextProtoUnsupported;
}
// We don't check for truncation because sizeof(buf) is large enough to hold
// the maximum protocol size.
switch (state) {
case SSL_NEXT_PROTO_NO_SUPPORT:
proto->clear();
return kNextProtoUnsupported;
case SSL_NEXT_PROTO_NEGOTIATED:
*proto = std::string(reinterpret_cast<char*>(buf), len);
return kNextProtoNegotiated;
case SSL_NEXT_PROTO_NO_OVERLAP:
*proto = std::string(reinterpret_cast<char*>(buf), len);
return kNextProtoNoOverlap;
default:
NOTREACHED() << "Unknown status from SSL_GetNextProto: " << state;
proto->clear();
return kNextProtoUnsupported;
}
#else
// No NPN support in the libssl that we are building with.
proto->clear();
return kNextProtoUnsupported;
#endif
}
void SSLClientSocketNSS::DoReadCallback(int rv) {
EnterFunction(rv);
DCHECK(rv != ERR_IO_PENDING);
DCHECK(user_read_callback_);
// Since Run may result in Read being called, clear |user_read_callback_|
// up front.
CompletionCallback* c = user_read_callback_;
user_read_callback_ = NULL;
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
c->Run(rv);
LeaveFunction("");
}
void SSLClientSocketNSS::DoWriteCallback(int rv) {
EnterFunction(rv);
DCHECK(rv != ERR_IO_PENDING);
DCHECK(user_write_callback_);
// Since Run may result in Write being called, clear |user_write_callback_|
// up front.
CompletionCallback* c = user_write_callback_;
user_write_callback_ = NULL;
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
c->Run(rv);
LeaveFunction("");
}
// As part of Connect(), the SSLClientSocketNSS object performs an SSL
// handshake. This requires network IO, which in turn calls
// BufferRecvComplete() with a non-zero byte count. This byte count eventually
// winds its way through the state machine and ends up being passed to the
// callback. For Read() and Write(), that's what we want. But for Connect(),
// the caller expects OK (i.e. 0) for success.
//
void SSLClientSocketNSS::DoConnectCallback(int rv) {
EnterFunction(rv);
DCHECK_NE(rv, ERR_IO_PENDING);
DCHECK(user_connect_callback_);
CompletionCallback* c = user_connect_callback_;
user_connect_callback_ = NULL;
c->Run(rv > OK ? OK : rv);
LeaveFunction("");
}
void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
EnterFunction(result);
int rv = DoHandshakeLoop(result);
if (rv != ERR_IO_PENDING) {
net_log_.EndEvent(net::NetLog::TYPE_SSL_CONNECT, NULL);
DoConnectCallback(rv);
}
LeaveFunction("");
}
void SSLClientSocketNSS::OnSendComplete(int result) {
EnterFunction(result);
if (next_handshake_state_ == STATE_HANDSHAKE) {
// In handshake phase.
OnHandshakeIOComplete(result);
LeaveFunction("");
return;
}
// OnSendComplete may need to call DoPayloadRead while the renegotiation
// handshake is in progress.
int rv_read = ERR_IO_PENDING;
int rv_write = ERR_IO_PENDING;
bool network_moved;
do {
if (user_read_buf_)
rv_read = DoPayloadRead();
if (user_write_buf_)
rv_write = DoPayloadWrite();
network_moved = DoTransportIO();
} while (rv_read == ERR_IO_PENDING &&
rv_write == ERR_IO_PENDING &&
network_moved);
if (user_read_buf_ && rv_read != ERR_IO_PENDING)
DoReadCallback(rv_read);
if (user_write_buf_ && rv_write != ERR_IO_PENDING)
DoWriteCallback(rv_write);
LeaveFunction("");
}
void SSLClientSocketNSS::OnRecvComplete(int result) {
EnterFunction(result);
if (next_handshake_state_ == STATE_HANDSHAKE) {
// In handshake phase.
OnHandshakeIOComplete(result);
LeaveFunction("");
return;
}
// Network layer received some data, check if client requested to read
// decrypted data.
if (!user_read_buf_) {
LeaveFunction("");
return;
}
int rv = DoReadLoop(result);
if (rv != ERR_IO_PENDING)
DoReadCallback(rv);
LeaveFunction("");
}
// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
static PRErrorCode MapErrorToNSS(int result) {
if (result >=0)
return result;
switch (result) {
case ERR_IO_PENDING:
return PR_WOULD_BLOCK_ERROR;
case ERR_ACCESS_DENIED:
// For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
return PR_NO_ACCESS_RIGHTS_ERROR;
case ERR_INTERNET_DISCONNECTED: // Equivalent to ENETDOWN.
return PR_NETWORK_UNREACHABLE_ERROR; // Best approximation.
case ERR_CONNECTION_TIMED_OUT:
case ERR_TIMED_OUT:
return PR_IO_TIMEOUT_ERROR;
case ERR_CONNECTION_RESET:
return PR_CONNECT_RESET_ERROR;
case ERR_CONNECTION_ABORTED:
return PR_CONNECT_ABORTED_ERROR;
case ERR_CONNECTION_REFUSED:
return PR_CONNECT_REFUSED_ERROR;
case ERR_ADDRESS_UNREACHABLE:
return PR_HOST_UNREACHABLE_ERROR; // Also PR_NETWORK_UNREACHABLE_ERROR.
case ERR_ADDRESS_INVALID:
return PR_ADDRESS_NOT_AVAILABLE_ERROR;
case ERR_NAME_NOT_RESOLVED:
return PR_DIRECTORY_LOOKUP_ERROR;
default:
LOG(WARNING) << "MapErrorToNSS " << result
<< " mapped to PR_UNKNOWN_ERROR";
return PR_UNKNOWN_ERROR;
}
}
// Do network I/O between the given buffer and the given socket.
// Return true if some I/O performed, false otherwise (error or ERR_IO_PENDING)
bool SSLClientSocketNSS::DoTransportIO() {
EnterFunction("");
bool network_moved = false;
if (nss_bufs_ != NULL) {
int nsent = BufferSend();
int nreceived = BufferRecv();
network_moved = (nsent > 0 || nreceived >= 0);
}
LeaveFunction(network_moved);
return network_moved;
}
// Return 0 for EOF,
// > 0 for bytes transferred immediately,
// < 0 for error (or the non-error ERR_IO_PENDING).
int SSLClientSocketNSS::BufferSend(void) {
if (transport_send_busy_) return ERR_IO_PENDING;
int nsent = 0;
EnterFunction("");
// nss_bufs_ is a circular buffer. It may have two contiguous parts
// (before and after the wrap). So this for loop needs two iterations.
for (int i = 0; i < 2; ++i) {
const char* buf;
int nb = memio_GetWriteParams(nss_bufs_, &buf);
if (!nb)
break;
scoped_refptr<IOBuffer> send_buffer = new IOBuffer(nb);
memcpy(send_buffer->data(), buf, nb);
int rv = transport_->socket()->Write(send_buffer, nb,
&buffer_send_callback_);
if (rv == ERR_IO_PENDING) {
transport_send_busy_ = true;
break;
} else {
memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
if (rv < 0) {
// Return the error even if the previous Write succeeded.
nsent = rv;
break;
}
nsent += rv;
}
}
LeaveFunction(nsent);
return nsent;
}
void SSLClientSocketNSS::BufferSendComplete(int result) {
EnterFunction(result);
memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
transport_send_busy_ = false;
OnSendComplete(result);
LeaveFunction("");
}
int SSLClientSocketNSS::BufferRecv(void) {
if (transport_recv_busy_) return ERR_IO_PENDING;
char *buf;
int nb = memio_GetReadParams(nss_bufs_, &buf);
EnterFunction(nb);
int rv;
if (!nb) {
// buffer too full to read into, so no I/O possible at moment
rv = ERR_IO_PENDING;
} else {
recv_buffer_ = new IOBuffer(nb);
rv = transport_->socket()->Read(recv_buffer_, nb, &buffer_recv_callback_);
if (rv == ERR_IO_PENDING) {
transport_recv_busy_ = true;
} else {
if (rv > 0)
memcpy(buf, recv_buffer_->data(), rv);
memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
recv_buffer_ = NULL;
}
}
LeaveFunction(rv);
return rv;
}
void SSLClientSocketNSS::BufferRecvComplete(int result) {
EnterFunction(result);
if (result > 0) {
char *buf;
memio_GetReadParams(nss_bufs_, &buf);
memcpy(buf, recv_buffer_->data(), result);
}
recv_buffer_ = NULL;
memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
transport_recv_busy_ = false;
OnRecvComplete(result);
LeaveFunction("");
}
int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
EnterFunction(last_io_result);
bool network_moved;
int rv = last_io_result;
do {
// Default to STATE_NONE for next state.
// (This is a quirk carried over from the windows
// implementation. It makes reading the logs a bit harder.)
// State handlers can and often do call GotoState just
// to stay in the current state.
State state = next_handshake_state_;
GotoState(STATE_NONE);
switch (state) {
case STATE_NONE:
// we're just pumping data between the buffer and the network
break;
case STATE_HANDSHAKE:
rv = DoHandshake();
break;
case STATE_VERIFY_CERT:
DCHECK(rv == OK);
rv = DoVerifyCert(rv);
break;
case STATE_VERIFY_CERT_COMPLETE:
rv = DoVerifyCertComplete(rv);
break;
default:
rv = ERR_UNEXPECTED;
NOTREACHED() << "unexpected state";
break;
}
// Do the actual network I/O
network_moved = DoTransportIO();
} while ((rv != ERR_IO_PENDING || network_moved) &&
next_handshake_state_ != STATE_NONE);
LeaveFunction("");
return rv;
}
int SSLClientSocketNSS::DoReadLoop(int result) {
EnterFunction("");
DCHECK(completed_handshake_);
DCHECK(next_handshake_state_ == STATE_NONE);
if (result < 0)
return result;
if (!nss_bufs_)
return ERR_UNEXPECTED;
bool network_moved;
int rv;
do {
rv = DoPayloadRead();
network_moved = DoTransportIO();
} while (rv == ERR_IO_PENDING && network_moved);
LeaveFunction("");
return rv;
}
int SSLClientSocketNSS::DoWriteLoop(int result) {
EnterFunction("");
DCHECK(completed_handshake_);
DCHECK(next_handshake_state_ == STATE_NONE);
if (result < 0)
return result;
if (!nss_bufs_)
return ERR_UNEXPECTED;
bool network_moved;
int rv;
do {
rv = DoPayloadWrite();
network_moved = DoTransportIO();
} while (rv == ERR_IO_PENDING && network_moved);
LeaveFunction("");
return rv;
}
// static
// NSS calls this if an incoming certificate needs to be verified.
// Do nothing but return SECSuccess.
// This is called only in full handshake mode.
// Peer certificate is retrieved in HandshakeCallback() later, which is called
// in full handshake mode or in resumption handshake mode.
SECStatus SSLClientSocketNSS::OwnAuthCertHandler(void* arg,
PRFileDesc* socket,
PRBool checksig,
PRBool is_server) {
// Tell NSS to not verify the certificate.
return SECSuccess;
}
// static
// NSS calls this if a client certificate is needed.
// Based on Mozilla's NSS_GetClientAuthData.
SECStatus SSLClientSocketNSS::ClientAuthHandler(
void* arg,
PRFileDesc* socket,
CERTDistNames* ca_names,
CERTCertificate** result_certificate,
SECKEYPrivateKey** result_private_key) {
SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg);
that->client_auth_cert_needed_ = !that->ssl_config_.send_client_cert;
#if defined(OS_WIN)
if (that->ssl_config_.send_client_cert) {
// TODO(wtc): SSLClientSocketNSS can't do SSL client authentication using
// CryptoAPI yet (http://crbug.com/37560), so client_cert must be NULL.
DCHECK(!that->ssl_config_.client_cert);
// Send no client certificate.
return SECFailure;
}
that->client_certs_.clear();
std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
for (int i = 0; i < ca_names->nnames; ++i) {
issuer_list[i].cbData = ca_names->names[i].len;
issuer_list[i].pbData = ca_names->names[i].data;
}
// Client certificates of the user are in the "MY" system certificate store.
HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY");
if (!my_cert_store) {
LOG(ERROR) << "Could not open the \"MY\" system certificate store: "
<< GetLastError();
return SECFailure;
}
// Enumerate the client certificates.
CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para;
memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para));
find_by_issuer_para.cbSize = sizeof(find_by_issuer_para);
find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH;
find_by_issuer_para.cIssuer = ca_names->nnames;
find_by_issuer_para.rgIssuer = ca_names->nnames ? &issuer_list[0] : NULL;
PCCERT_CHAIN_CONTEXT chain_context = NULL;
// TODO(wtc): close cert_store_ at shutdown.
if (!cert_store_)
cert_store_ = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, 0, NULL);
for (;;) {
// Find a certificate chain.
chain_context = CertFindChainInStore(my_cert_store,
X509_ASN_ENCODING,
0,
CERT_CHAIN_FIND_BY_ISSUER,
&find_by_issuer_para,
chain_context);
if (!chain_context) {
DWORD err = GetLastError();
if (err != CRYPT_E_NOT_FOUND)
DLOG(ERROR) << "CertFindChainInStore failed: " << err;
break;
}
// Get the leaf certificate.
PCCERT_CONTEXT cert_context =
chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
// Copy it to our own certificate store, so that we can close the "MY"
// certificate store before returning from this function.
PCCERT_CONTEXT cert_context2;
BOOL ok = CertAddCertificateContextToStore(cert_store_, cert_context,
CERT_STORE_ADD_USE_EXISTING,
&cert_context2);
if (!ok) {
NOTREACHED();
continue;
}
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
cert_context2, X509Certificate::SOURCE_LONE_CERT_IMPORT,
X509Certificate::OSCertHandles());
X509Certificate::FreeOSCertHandle(cert_context2);
that->client_certs_.push_back(cert);
}
BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG);
DCHECK(ok);
// Tell NSS to suspend the client authentication. We will then abort the
// handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
return SECWouldBlock;
#elif defined(OS_MACOSX)
if (that->ssl_config_.send_client_cert) {
// TODO(wtc): SSLClientSocketNSS can't do SSL client authentication using
// CDSA/CSSM yet (http://crbug.com/45369), so client_cert must be NULL.
DCHECK(!that->ssl_config_.client_cert);
// Send no client certificate.
return SECFailure;
}
that->client_certs_.clear();
// First, get the cert issuer names allowed by the server.
std::vector<CertPrincipal> valid_issuers;
int n = ca_names->nnames;
for (int i = 0; i < n; i++) {
// Parse each name into a CertPrincipal object.
CertPrincipal p;
if (p.ParseDistinguishedName(ca_names->names[i].data,
ca_names->names[i].len)) {
valid_issuers.push_back(p);
}
}
// Now get the available client certs whose issuers are allowed by the server.
X509Certificate::GetSSLClientCertificates(that->hostname_,
valid_issuers,
&that->client_certs_);
// Tell NSS to suspend the client authentication. We will then abort the
// handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
return SECWouldBlock;
#else
CERTCertificate* cert = NULL;
SECKEYPrivateKey* privkey = NULL;
void* wincx = SSL_RevealPinArg(socket);
// Second pass: a client certificate should have been selected.
if (that->ssl_config_.send_client_cert) {
if (that->ssl_config_.client_cert) {
cert = CERT_DupCertificate(
that->ssl_config_.client_cert->os_cert_handle());
privkey = PK11_FindKeyByAnyCert(cert, wincx);
if (privkey) {
// TODO(jsorianopastor): We should wait for server certificate
// verification before sending our credentials. See
// http://crbug.com/13934.
*result_certificate = cert;
*result_private_key = privkey;
return SECSuccess;
}
LOG(WARNING) << "Client cert found without private key";
}
// Send no client certificate.
return SECFailure;
}
CERTCertNicknames* names = CERT_GetCertNicknames(
CERT_GetDefaultCertDB(), SEC_CERT_NICKNAMES_USER, wincx);
if (names) {
for (int i = 0; i < names->numnicknames; ++i) {
cert = CERT_FindUserCertByUsage(
CERT_GetDefaultCertDB(), names->nicknames[i],
certUsageSSLClient, PR_FALSE, wincx);
if (!cert)
continue;
// Only check unexpired certs.
if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_TRUE) ==
secCertTimeValid && (!ca_names->nnames ||
NSS_CmpCertChainWCANames(cert, ca_names) == SECSuccess)) {
privkey = PK11_FindKeyByAnyCert(cert, wincx);
if (privkey) {
X509Certificate* x509_cert = X509Certificate::CreateFromHandle(
cert, X509Certificate::SOURCE_LONE_CERT_IMPORT,
net::X509Certificate::OSCertHandles());
that->client_certs_.push_back(x509_cert);
CERT_DestroyCertificate(cert);
SECKEY_DestroyPrivateKey(privkey);
continue;
}
}
CERT_DestroyCertificate(cert);
}
CERT_FreeNicknames(names);
}
// Tell NSS to suspend the client authentication. We will then abort the
// handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
return SECWouldBlock;
#endif
}
// static
// NSS calls this when handshake is completed.
// After the SSL handshake is finished, use CertVerifier to verify
// the saved server certificate.
void SSLClientSocketNSS::HandshakeCallback(PRFileDesc* socket,
void* arg) {
SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg);
that->set_handshake_callback_called();
that->UpdateServerCert();
that->CheckSecureRenegotiation();
}
int SSLClientSocketNSS::DoHandshake() {
EnterFunction("");
int net_error = net::OK;
SECStatus rv = SSL_ForceHandshake(nss_fd_);
if (client_auth_cert_needed_) {
net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
// If the handshake already succeeded (because the server requests but
// doesn't require a client cert), we need to invalidate the SSL session
// so that we won't try to resume the non-client-authenticated session in
// the next handshake. This will cause the server to ask for a client
// cert again.
if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess) {
LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
}
} else if (rv == SECSuccess) {
if (handshake_callback_called_) {
// SSL handshake is completed. Let's verify the certificate.
GotoState(STATE_VERIFY_CERT);
// Done!
} else {
// SSL_ForceHandshake returned SECSuccess prematurely.
rv = SECFailure;
net_error = ERR_SSL_PROTOCOL_ERROR;
}
} else {
PRErrorCode prerr = PR_GetError();
net_error = MapHandshakeError(prerr);
// If not done, stay in this state
if (net_error == ERR_IO_PENDING) {
GotoState(STATE_HANDSHAKE);
} else {
LOG(ERROR) << "handshake failed; NSS error code " << prerr
<< ", net_error " << net_error;
}
}
LeaveFunction("");
return net_error;
}
int SSLClientSocketNSS::DoVerifyCert(int result) {
DCHECK(server_cert_);
GotoState(STATE_VERIFY_CERT_COMPLETE);
int flags = 0;
/* Disable revocation checking for SPDY. This is a hack, but we ignore
* certificate errors for SPDY anyway so it's no loss in security. This lets
* us benchmark as if we had OCSP stapling.
*
* http://crbug.com/32020
*/
unsigned char buf[255];
int state;
unsigned int len;
SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &len, sizeof(buf));
bool spdy = (rv == SECSuccess && state == SSL_NEXT_PROTO_NEGOTIATED &&
len == 4 && memcmp(buf, "spdy", 4) == 0);
if (ssl_config_.rev_checking_enabled && !spdy)
flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
if (ssl_config_.verify_ev_cert)
flags |= X509Certificate::VERIFY_EV_CERT;
verifier_.reset(new CertVerifier);
return verifier_->Verify(server_cert_, hostname_, flags,
&server_cert_verify_result_,
&handshake_io_callback_);
}
// Derived from AuthCertificateCallback() in
// mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
DCHECK(verifier_.get());
verifier_.reset();
if (result == OK) {
// Remember the intermediate CA certs if the server sends them to us.
//
// We used to remember the intermediate CA certs in the NSS database
// persistently. However, NSS opens a connection to the SQLite database
// during NSS initialization and doesn't close the connection until NSS
// shuts down. If the file system where the database resides is gone,
// the database connection goes bad. What's worse, the connection won't
// recover when the file system comes back. Until this NSS or SQLite bug
// is fixed, we need to avoid using the NSS database for non-essential
// purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
// http://crbug.com/15630 for more info.
CERTCertList* cert_list = CERT_GetCertChainFromCert(
server_cert_nss_, PR_Now(), certUsageSSLCA);
if (cert_list) {
for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
!CERT_LIST_END(node, cert_list);
node = CERT_LIST_NEXT(node)) {
if (node->cert->slot || node->cert->isRoot || node->cert->isperm ||
node->cert == server_cert_nss_) {
// Some certs we don't want to remember are:
// - found on a token.
// - the root cert.
// - already stored in perm db.
// - the server cert itself.
continue;
}
// We have found a CA cert that we want to remember.
// TODO(wtc): Remember the intermediate CA certs in a std::set
// temporarily (http://crbug.com/15630).
}
CERT_DestroyCertList(cert_list);
}
}
// If we have been explicitly told to accept this certificate, override the
// result of verifier_.Verify.
// Eventually, we should cache the cert verification results so that we don't
// need to call verifier_.Verify repeatedly. But for now we need to do this.
// Alternatively, we could use the cert's status that we stored along with
// the cert in the allowed_bad_certs vector.
if (IsCertificateError(result) &&
ssl_config_.IsAllowedBadCert(server_cert_)) {
LOG(INFO) << "accepting bad SSL certificate, as user told us to";
result = OK;
}
completed_handshake_ = true;
// TODO(ukai): we may not need this call because it is now harmless to have a
// session with a bad cert.
InvalidateSessionIfBadCertificate();
// Exit DoHandshakeLoop and return the result to the caller to Connect.
DCHECK(next_handshake_state_ == STATE_NONE);
return result;
}
int SSLClientSocketNSS::DoPayloadRead() {
EnterFunction(user_read_buf_len_);
DCHECK(user_read_buf_);
DCHECK_GT(user_read_buf_len_, 0);
int rv = PR_Read(nss_fd_, user_read_buf_->data(), user_read_buf_len_);
if (client_auth_cert_needed_) {
// We don't need to invalidate the non-client-authenticated SSL session
// because the server will renegotiate anyway.
LeaveFunction("");
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
if (rv >= 0) {
LogData(user_read_buf_->data(), rv);
LeaveFunction("");
return rv;
}
PRErrorCode prerr = PR_GetError();
if (prerr == PR_WOULD_BLOCK_ERROR) {
LeaveFunction("");
return ERR_IO_PENDING;
}
LeaveFunction("");
return MapNSPRError(prerr);
}
int SSLClientSocketNSS::DoPayloadWrite() {
EnterFunction(user_write_buf_len_);
DCHECK(user_write_buf_);
int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
if (rv >= 0) {
LogData(user_write_buf_->data(), rv);
LeaveFunction("");
return rv;
}
PRErrorCode prerr = PR_GetError();
if (prerr == PR_WOULD_BLOCK_ERROR) {
LeaveFunction("");
return ERR_IO_PENDING;
}
LeaveFunction("");
return MapNSPRError(prerr);
}
} // namespace net
|