summaryrefslogtreecommitdiff
path: root/src/mongo/util/net/ssl_manager.cpp
blob: 4b80ad3cfabd40ad96b95f6161395f15c8a6f2a6 (plain)
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
/*    Copyright 2009 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kNetwork

#include "mongo/platform/basic.h"

#include "mongo/util/net/ssl_manager.h"

#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/tss.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include "mongo/base/init.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/config.h"
#include "mongo/db/server_parameters.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/stdx/memory.h"
#include "mongo/transport/session.h"
#include "mongo/util/concurrency/mutex.h"
#include "mongo/util/debug_util.h"
#include "mongo/util/exit.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/sock.h"
#include "mongo/util/net/socket_exception.h"
#include "mongo/util/net/ssl_expiration.h"
#include "mongo/util/net/ssl_options.h"
#include "mongo/util/net/ssl_types.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/text.h"

#ifdef MONGO_CONFIG_SSL
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/evp.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
#if defined(_WIN32)
#include <wincrypt.h>
#elif defined(__APPLE__)
#include <Security/Security.h>
#endif
#endif

namespace mongo {

namespace {

const transport::Session::Decoration<SSLPeerInfo> peerInfoForSession =
    transport::Session::declareDecoration<SSLPeerInfo>();

}  // namespace

SSLPeerInfo& SSLPeerInfo::forSession(const transport::SessionHandle& session) {
    return peerInfoForSession(session.get());
}

SSLParams sslGlobalParams;

const SSLParams& getSSLGlobalParams() {
    return sslGlobalParams;
}

/**
 * Configurable via --setParameter disableNonSSLConnectionLogging=true. If false (default)
 * if the sslMode is set to preferSSL, we will log connections that are not using SSL.
 * If true, such log messages will be suppressed.
 */
ExportedServerParameter<bool, ServerParameterType::kStartupOnly>
    disableNonSSLConnectionLoggingParameter(ServerParameterSet::getGlobal(),
                                            "disableNonSSLConnectionLogging",
                                            &sslGlobalParams.disableNonSSLConnectionLogging);

#ifdef MONGO_CONFIG_SSL
// Old copies of OpenSSL will not have constants to disable protocols they don't support.
// Define them to values we can OR together safely to generically disable these protocols across
// all versions of OpenSSL.
#ifndef SSL_OP_NO_TLSv1_1
#define SSL_OP_NO_TLSv1_1 0
#endif
#ifndef SSL_OP_NO_TLSv1_2
#define SSL_OP_NO_TLSv1_2 0
#endif

namespace {

// clang-format off
#ifndef MONGO_CONFIG_HAVE_ASN1_ANY_DEFINITIONS
// Copies of OpenSSL before 1.0.0 do not have ASN1_SEQUENCE_ANY, ASN1_SET_ANY, or the helper
// functions which let us deserialize these objects. We must polyfill the definitions to interact
// with ASN1 objects so stored.
typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;

ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) =
    ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY)

ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) =
    ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, ASN1_SET_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SET_ANY)

IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY,
                                            ASN1_SEQUENCE_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY, ASN1_SET_ANY)
; // clang format needs to see a semicolon or it will start formatting unrelated code
#endif // MONGO_CONFIG_NEEDS_ASN1_ANY_DEFINITIONS
// clang-format on

#if OPENSSL_VERSION_NUMBER < 0x10100000L
// Copies of OpenSSL after 1.1.0 define new functions for interaction with
// X509 structure. We must polyfill used definitions to interact with older
// OpenSSL versions.
const STACK_OF(X509_EXTENSION) * X509_get0_extensions(const X509* peerCert) {
    return peerCert->cert_info->extensions;
}
#endif

/**
 * Multithreaded Support for SSL.
 *
 * In order to allow OpenSSL to work in a multithreaded environment, you
 * must provide some callbacks for it to use for locking.  The following code
 * sets up a vector of mutexes and uses thread-local storage to assign an id
 * to each thread.
 * The so-called SSLThreadInfo class encapsulates most of the logic required for
 * OpenSSL multithreaded support.
 */

unsigned long _ssl_id_callback();
void _ssl_locking_callback(int mode, int type, const char* file, int line);

class SSLThreadInfo {
public:
    SSLThreadInfo() {
        _id = _next.fetchAndAdd(1);
    }

    ~SSLThreadInfo() {
        ERR_remove_state(0);
    }

    unsigned long id() const {
        return _id;
    }

    void lock_callback(int mode, int type, const char* file, int line) {
        if (mode & CRYPTO_LOCK) {
            _mutex[type]->lock();
        } else {
            _mutex[type]->unlock();
        }
    }

    static void init() {
        while ((int)_mutex.size() < CRYPTO_num_locks()) {
            _mutex.emplace_back(stdx::make_unique<stdx::recursive_mutex>());
        }
    }

    static SSLThreadInfo* get() {
        SSLThreadInfo* me = _thread.get();
        if (!me) {
            me = new SSLThreadInfo();
            _thread.reset(me);
        }
        return me;
    }

private:
    unsigned _id;

    static AtomicUInt32 _next;
    // Note: see SERVER-8734 for why we are using a recursive mutex here.
    // Once the deadlock fix in OpenSSL is incorporated into most distros of
    // Linux, this can be changed back to a nonrecursive mutex.
    static std::vector<std::unique_ptr<stdx::recursive_mutex>> _mutex;
    static boost::thread_specific_ptr<SSLThreadInfo> _thread;
};

unsigned long _ssl_id_callback() {
    return SSLThreadInfo::get()->id();
}

void _ssl_locking_callback(int mode, int type, const char* file, int line) {
    SSLThreadInfo::get()->lock_callback(mode, type, file, line);
}

// We only want to free SSL_CTX objects if they have been populated. OpenSSL seems to perform this
// check before freeing them, but because it does not document this, we should protect ourselves.
void _free_ssl_context(SSL_CTX* ctx) {
    if (ctx != nullptr) {
        SSL_CTX_free(ctx);
    }
}

AtomicUInt32 SSLThreadInfo::_next;
std::vector<std::unique_ptr<stdx::recursive_mutex>> SSLThreadInfo::_mutex;
boost::thread_specific_ptr<SSLThreadInfo> SSLThreadInfo::_thread;

////////////////////////////////////////////////////////////////

SimpleMutex sslManagerMtx;
SSLManagerInterface* theSSLManager = NULL;
using UniqueSSLContext = std::unique_ptr<SSL_CTX, decltype(&_free_ssl_context)>;
static const int BUFFER_SIZE = 8 * 1024;
static const int DATE_LEN = 128;

class SSLManager : public SSLManagerInterface {
public:
    explicit SSLManager(const SSLParams& params, bool isServer);

    /**
     * Initializes an OpenSSL context according to the provided settings. Only settings which are
     * acceptable on non-blocking connections are set.
     */
    Status initSSLContext(SSL_CTX* context,
                          const SSLParams& params,
                          ConnectionDirection direction) final;

    virtual SSLConnection* connect(Socket* socket);

    virtual SSLConnection* accept(Socket* socket, const char* initialBytes, int len);

    virtual SSLPeerInfo parseAndValidatePeerCertificateDeprecated(const SSLConnection* conn,
                                                                  const std::string& remoteHost);

    StatusWith<boost::optional<SSLPeerInfo>> parseAndValidatePeerCertificate(
        SSL* conn, const std::string& remoteHost) final;

    virtual const SSLConfiguration& getSSLConfiguration() const {
        return _sslConfiguration;
    }

    virtual int SSL_read(SSLConnection* conn, void* buf, int num);

    virtual int SSL_write(SSLConnection* conn, const void* buf, int num);

    virtual unsigned long ERR_get_error();

    virtual char* ERR_error_string(unsigned long e, char* buf);

    virtual int SSL_get_error(const SSLConnection* conn, int ret);

    virtual int SSL_shutdown(SSLConnection* conn);

    virtual void SSL_free(SSLConnection* conn);

private:
    const int _rolesNid = OBJ_create(mongodbRolesOID.identifier.c_str(),
                                     mongodbRolesOID.shortDescription.c_str(),
                                     mongodbRolesOID.longDescription.c_str());
    UniqueSSLContext _serverContext;  // SSL context for incoming connections
    UniqueSSLContext _clientContext;  // SSL context for outgoing connections
    bool _weakValidation;
    bool _allowInvalidCertificates;
    bool _allowInvalidHostnames;
    SSLConfiguration _sslConfiguration;

    /**
     * creates an SSL object to be used for this file descriptor.
     * caller must SSL_free it.
     */
    SSL* _secure(SSL_CTX* context, int fd);

    /**
     * Given an error code from an SSL-type IO function, logs an
     * appropriate message and throws a SocketException
     */
    MONGO_COMPILER_NORETURN void _handleSSLError(int code, int ret);

    /*
     * Init the SSL context using parameters provided in params. This SSL context will
     * be configured for blocking send/receive.
     */
    bool _initSynchronousSSLContext(UniqueSSLContext* context,
                                    const SSLParams& params,
                                    ConnectionDirection direction);

    /*
     * Converts time from OpenSSL return value to unsigned long long
     * representing the milliseconds since the epoch.
     */
    unsigned long long _convertASN1ToMillis(ASN1_TIME* t);

    /*
     * Parse and store x509 subject name from the PEM keyfile.
     * For server instances check that PEM certificate is not expired
     * and extract server certificate notAfter date.
     * @param keyFile referencing the PEM file to be read.
     * @param subjectName as a pointer to the subject name variable being set.
     * @param serverNotAfter a Date_t object pointer that is valued if the
     * date is to be checked (as for a server certificate) and null otherwise.
     * @return bool showing if the function was successful.
     */
    bool _parseAndValidateCertificate(const std::string& keyFile,
                                      const std::string& keyPassword,
                                      std::string* subjectName,
                                      Date_t* serverNotAfter);


    StatusWith<stdx::unordered_set<RoleName>> _parsePeerRoles(X509* peerCert) const;

    /** @return true if was successful, otherwise false */
    bool _setupPEM(SSL_CTX* context, const std::string& keyFile, const std::string& password);

    /*
     * Set up an SSL context for certificate validation by loading a CA
     */
    Status _setupCA(SSL_CTX* context, const std::string& caFile);

    /*
     * Set up an SSL context for certificate validation by loading the system's CA store
     */
    Status _setupSystemCA(SSL_CTX* context);

    /*
     * Import a certificate revocation list into an SSL context
     * for use with validating certificates
     */
    bool _setupCRL(SSL_CTX* context, const std::string& crlFile);

    /*
     * sub function for checking the result of an SSL operation
     */
    bool _doneWithSSLOp(SSLConnection* conn, int status);

    /*
     * Send and receive network data
     */
    void _flushNetworkBIO(SSLConnection* conn);

    /*
     * match a remote host name to an x.509 host name
     */
    bool _hostNameMatch(const char* nameToMatch, const char* certHostName);

    /**
     * Callbacks for SSL functions
     */
    static int password_cb(char* buf, int num, int rwflag, void* userdata);
    static int verify_cb(int ok, X509_STORE_CTX* ctx);
};

void setupFIPS() {
// Turn on FIPS mode if requested, OPENSSL_FIPS must be defined by the OpenSSL headers
#if defined(MONGO_CONFIG_HAVE_FIPS_MODE_SET)
    int status = FIPS_mode_set(1);
    if (!status) {
        severe() << "can't activate FIPS mode: "
                 << SSLManagerInterface::getSSLErrorMessage(ERR_get_error());
        fassertFailedNoTrace(16703);
    }
    log() << "FIPS 140-2 mode activated";
#else
    severe() << "this version of mongodb was not compiled with FIPS support";
    fassertFailedNoTrace(17089);
#endif
}

}  // namespace

// Global variable indicating if this is a server or a client instance
bool isSSLServer = false;


MONGO_INITIALIZER(SetupOpenSSL)(InitializerContext*) {
    SSL_library_init();
    SSL_load_error_strings();
    ERR_load_crypto_strings();

    if (sslGlobalParams.sslFIPSMode) {
        setupFIPS();
    }

    // Add all digests and ciphers to OpenSSL's internal table
    // so that encryption/decryption is backwards compatible
    OpenSSL_add_all_algorithms();

    // Setup OpenSSL multithreading callbacks
    CRYPTO_set_id_callback(_ssl_id_callback);
    CRYPTO_set_locking_callback(_ssl_locking_callback);

    SSLThreadInfo::init();
    SSLThreadInfo::get();

    return Status::OK();
}

MONGO_INITIALIZER_WITH_PREREQUISITES(SSLManager, ("SetupOpenSSL"))(InitializerContext*) {
    stdx::lock_guard<SimpleMutex> lck(sslManagerMtx);
    if (!isSSLServer || (sslGlobalParams.sslMode.load() != SSLParams::SSLMode_disabled)) {
        theSSLManager = new SSLManager(sslGlobalParams, isSSLServer);
    }
    return Status::OK();
}

std::unique_ptr<SSLManagerInterface> SSLManagerInterface::create(const SSLParams& params,
                                                                 bool isServer) {
    return stdx::make_unique<SSLManager>(params, isServer);
}

SSLManagerInterface* getSSLManager() {
    stdx::lock_guard<SimpleMutex> lck(sslManagerMtx);
    if (theSSLManager)
        return theSSLManager;
    return NULL;
}

std::string getCertificateSubjectName(X509* cert) {
    std::string result;

    BIO* out = BIO_new(BIO_s_mem());
    uassert(16884, "unable to allocate BIO memory", NULL != out);
    ON_BLOCK_EXIT(BIO_free, out);

    if (X509_NAME_print_ex(out, X509_get_subject_name(cert), 0, XN_FLAG_RFC2253) >= 0) {
        if (BIO_number_written(out) > 0) {
            result.resize(BIO_number_written(out));
            BIO_read(out, &result[0], result.size());
        }
    } else {
        log() << "failed to convert subject name to RFC2253 format";
    }

    return result;
}

SSLConnection::SSLConnection(SSL_CTX* context, Socket* sock, const char* initialBytes, int len)
    : socket(sock) {
    // This just ensures that SSL multithreading support is set up for this thread,
    // if it's not already.
    SSLThreadInfo::get();

    ssl = SSL_new(context);

    std::string sslErr =
        NULL != getSSLManager() ? getSSLManager()->getSSLErrorMessage(ERR_get_error()) : "";
    massert(15861, "Error creating new SSL object " + sslErr, ssl);

    BIO_new_bio_pair(&internalBIO, BUFFER_SIZE, &networkBIO, BUFFER_SIZE);
    SSL_set_bio(ssl, internalBIO, internalBIO);

    if (len > 0) {
        int toBIO = BIO_write(networkBIO, initialBytes, len);
        if (toBIO != len) {
            LOG(3) << "Failed to write initial network data to the SSL BIO layer";
            throw SocketException(SocketException::RECV_ERROR, socket->remoteString());
        }
    }
}

SSLConnection::~SSLConnection() {
    if (ssl) {  // The internalBIO is automatically freed as part of SSL_free
        SSL_free(ssl);
    }
    if (networkBIO) {
        BIO_free(networkBIO);
    }
}

namespace {
void canonicalizeClusterDN(std::vector<std::string>* dn) {
    // remove all RDNs we don't care about
    for (size_t i = 0; i < dn->size(); i++) {
        std::string& comp = dn->at(i);
        boost::algorithm::trim(comp);
        if (!mongoutils::str::startsWith(comp.c_str(), "DC=") &&
            !mongoutils::str::startsWith(comp.c_str(), "O=") &&
            !mongoutils::str::startsWith(comp.c_str(), "OU=")) {
            dn->erase(dn->begin() + i);
            i--;
        }
    }
    std::stable_sort(dn->begin(), dn->end());
}
}

bool SSLConfiguration::isClusterMember(StringData subjectName) const {
    std::vector<std::string> clientRDN = StringSplitter::split(subjectName.toString(), ",");
    std::vector<std::string> serverRDN = StringSplitter::split(serverSubjectName, ",");

    canonicalizeClusterDN(&clientRDN);
    canonicalizeClusterDN(&serverRDN);

    if (clientRDN.size() == 0 || clientRDN.size() != serverRDN.size()) {
        return false;
    }

    for (size_t i = 0; i < serverRDN.size(); i++) {
        if (clientRDN[i] != serverRDN[i]) {
            return false;
        }
    }
    return true;
}

BSONObj SSLConfiguration::getServerStatusBSON() const {
    BSONObjBuilder security;
    security.append("SSLServerSubjectName", serverSubjectName);
    security.appendBool("SSLServerHasCertificateAuthority", hasCA);
    security.appendDate("SSLServerCertificateExpirationDate", serverCertificateExpirationDate);
    return security.obj();
}

SSLManagerInterface::~SSLManagerInterface() {}

SSLManager::SSLManager(const SSLParams& params, bool isServer)
    : _serverContext(nullptr, _free_ssl_context),
      _clientContext(nullptr, _free_ssl_context),
      _weakValidation(params.sslWeakCertificateValidation),
      _allowInvalidCertificates(params.sslAllowInvalidCertificates),
      _allowInvalidHostnames(params.sslAllowInvalidHostnames) {
    if (!_initSynchronousSSLContext(&_clientContext, params, ConnectionDirection::kOutgoing)) {
        uasserted(16768, "ssl initialization problem");
    }

    // pick the certificate for use in outgoing connections,
    std::string clientPEM, clientPassword;
    if (!isServer || params.sslClusterFile.empty()) {
        // We are either a client, or a server without a cluster key,
        // so use the PEM key file, if specified
        clientPEM = params.sslPEMKeyFile;
        clientPassword = params.sslPEMKeyPassword;
    } else {
        // We are a server with a cluster key, so use the cluster key file
        clientPEM = params.sslClusterFile;
        clientPassword = params.sslClusterPassword;
    }

    if (!clientPEM.empty()) {
        if (!_parseAndValidateCertificate(
                clientPEM, clientPassword, &_sslConfiguration.clientSubjectName, NULL)) {
            uasserted(16941, "ssl initialization problem");
        }
    }
    // SSL server specific initialization
    if (isServer) {
        if (!_initSynchronousSSLContext(&_serverContext, params, ConnectionDirection::kIncoming)) {
            uasserted(16562, "ssl initialization problem");
        }

        if (!_parseAndValidateCertificate(params.sslPEMKeyFile,
                                          params.sslPEMKeyPassword,
                                          &_sslConfiguration.serverSubjectName,
                                          &_sslConfiguration.serverCertificateExpirationDate)) {
            uasserted(16942, "ssl initialization problem");
        }

        static CertificateExpirationMonitor task =
            CertificateExpirationMonitor(_sslConfiguration.serverCertificateExpirationDate);
    }
}

int SSLManager::password_cb(char* buf, int num, int rwflag, void* userdata) {
    // Unless OpenSSL misbehaves, num should always be positive
    fassert(17314, num > 0);
    invariant(userdata);
    auto pw = static_cast<const std::string*>(userdata);

    const size_t copied = pw->copy(buf, num - 1);
    buf[copied] = '\0';
    return copied;
}

int SSLManager::verify_cb(int ok, X509_STORE_CTX* ctx) {
    return 1;  // always succeed; we will catch the error in our get_verify_result() call
}

int SSLManager::SSL_read(SSLConnection* conn, void* buf, int num) {
    int status;
    do {
        status = ::SSL_read(conn->ssl, buf, num);
    } while (!_doneWithSSLOp(conn, status));

    if (status <= 0)
        _handleSSLError(SSL_get_error(conn, status), status);
    return status;
}

int SSLManager::SSL_write(SSLConnection* conn, const void* buf, int num) {
    int status;
    do {
        status = ::SSL_write(conn->ssl, buf, num);
    } while (!_doneWithSSLOp(conn, status));

    if (status <= 0)
        _handleSSLError(SSL_get_error(conn, status), status);
    return status;
}

unsigned long SSLManager::ERR_get_error() {
    return ::ERR_get_error();
}

char* SSLManager::ERR_error_string(unsigned long e, char* buf) {
    return ::ERR_error_string(e, buf);
}

int SSLManager::SSL_get_error(const SSLConnection* conn, int ret) {
    return ::SSL_get_error(conn->ssl, ret);
}

int SSLManager::SSL_shutdown(SSLConnection* conn) {
    int status;
    do {
        status = ::SSL_shutdown(conn->ssl);
    } while (!_doneWithSSLOp(conn, status));

    if (status < 0)
        _handleSSLError(SSL_get_error(conn, status), status);
    return status;
}

void SSLManager::SSL_free(SSLConnection* conn) {
    return ::SSL_free(conn->ssl);
}

Status SSLManager::initSSLContext(SSL_CTX* context,
                                  const SSLParams& params,
                                  ConnectionDirection direction) {
    // SSL_OP_ALL - Activate all bug workaround options, to support buggy client SSL's.
    // SSL_OP_NO_SSLv2 - Disable SSL v2 support
    // SSL_OP_NO_SSLv3 - Disable SSL v3 support
    long supportedProtocols = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;

    // Set the supported TLS protocols. Allow --sslDisabledProtocols to disable selected
    // ciphers.
    if (!params.sslDisabledProtocols.empty()) {
        for (const SSLParams::Protocols& protocol : params.sslDisabledProtocols) {
            if (protocol == SSLParams::Protocols::TLS1_0) {
                supportedProtocols |= SSL_OP_NO_TLSv1;
            } else if (protocol == SSLParams::Protocols::TLS1_1) {
                supportedProtocols |= SSL_OP_NO_TLSv1_1;
            } else if (protocol == SSLParams::Protocols::TLS1_2) {
                supportedProtocols |= SSL_OP_NO_TLSv1_2;
            }
        }
    }
    ::SSL_CTX_set_options(context, supportedProtocols);

    // HIGH - Enable strong ciphers
    // !EXPORT - Disable export ciphers (40/56 bit)
    // !aNULL - Disable anonymous auth ciphers
    // @STRENGTH - Sort ciphers based on strength
    std::string cipherConfig = "HIGH:!EXPORT:!aNULL@STRENGTH";

    // Allow the cipher configuration string to be overriden by --sslCipherConfig
    if (!params.sslCipherConfig.empty()) {
        cipherConfig = params.sslCipherConfig;
    }

    if (0 == ::SSL_CTX_set_cipher_list(context, cipherConfig.c_str())) {
        return Status(ErrorCodes::InvalidSSLConfiguration,
                      str::stream() << "Can not set supported cipher suites: "
                                    << getSSLErrorMessage(ERR_get_error()));
    }

    // We use the address of the context as the session id context.
    if (0 == ::SSL_CTX_set_session_id_context(
                 context, reinterpret_cast<unsigned char*>(&context), sizeof(context))) {
        return Status(ErrorCodes::InvalidSSLConfiguration,
                      str::stream() << "Can not store ssl session id context: "
                                    << getSSLErrorMessage(ERR_get_error()));
    }

    if (direction == ConnectionDirection::kOutgoing && !params.sslClusterFile.empty()) {
        ::EVP_set_pw_prompt("Enter cluster certificate passphrase");
        if (!_setupPEM(context, params.sslClusterFile, params.sslClusterPassword)) {
            return Status(ErrorCodes::InvalidSSLConfiguration, "Can not set up ssl clusterFile.");
        }
    } else if (!params.sslPEMKeyFile.empty()) {
        // Use the pemfile for everything else
        ::EVP_set_pw_prompt("Enter PEM passphrase");
        if (!_setupPEM(context, params.sslPEMKeyFile, params.sslPEMKeyPassword)) {
            return Status(ErrorCodes::InvalidSSLConfiguration, "Can not set up PEM key file.");
        }
    }

    const auto status =
        params.sslCAFile.empty() ? _setupSystemCA(context) : _setupCA(context, params.sslCAFile);
    if (!status.isOK())
        return status;

    if (!params.sslCRLFile.empty()) {
        if (!_setupCRL(context, params.sslCRLFile)) {
            return Status(ErrorCodes::InvalidSSLConfiguration, "Can not set up CRL file.");
        }
    }

    return Status::OK();
}

bool SSLManager::_initSynchronousSSLContext(UniqueSSLContext* contextPtr,
                                            const SSLParams& params,
                                            ConnectionDirection direction) {
    *contextPtr = UniqueSSLContext(SSL_CTX_new(SSLv23_method()), _free_ssl_context);

    uassertStatusOK(initSSLContext(contextPtr->get(), params, direction));

    // If renegotiation is needed, don't return from recv() or send() until it's successful.
    // Note: this is for blocking sockets only.
    SSL_CTX_set_mode(contextPtr->get(), SSL_MODE_AUTO_RETRY);

    return true;
}

unsigned long long SSLManager::_convertASN1ToMillis(ASN1_TIME* asn1time) {
    BIO* outBIO = BIO_new(BIO_s_mem());
    int timeError = ASN1_TIME_print(outBIO, asn1time);
    ON_BLOCK_EXIT(BIO_free, outBIO);

    if (timeError <= 0) {
        error() << "ASN1_TIME_print failed or wrote no data.";
        return 0;
    }

    char dateChar[DATE_LEN];
    timeError = BIO_gets(outBIO, dateChar, DATE_LEN);
    if (timeError <= 0) {
        error() << "BIO_gets call failed to transfer contents to buf";
        return 0;
    }

    // Ensure that day format is two digits for parsing.
    // Jun  8 17:00:03 2014 becomes Jun 08 17:00:03 2014.
    if (dateChar[4] == ' ') {
        dateChar[4] = '0';
    }

    std::istringstream inStringStream((std::string(dateChar, 20)));
    boost::posix_time::time_input_facet* inputFacet =
        new boost::posix_time::time_input_facet("%b %d %H:%M:%S %Y");

    inStringStream.imbue(std::locale(std::cout.getloc(), inputFacet));
    boost::posix_time::ptime posixTime;
    inStringStream >> posixTime;

    const boost::gregorian::date epoch = boost::gregorian::date(1970, boost::gregorian::Jan, 1);

    return (posixTime - boost::posix_time::ptime(epoch)).total_milliseconds();
}

bool SSLManager::_parseAndValidateCertificate(const std::string& keyFile,
                                              const std::string& keyPassword,
                                              std::string* subjectName,
                                              Date_t* serverCertificateExpirationDate) {
    BIO* inBIO = BIO_new(BIO_s_file());
    if (inBIO == NULL) {
        error() << "failed to allocate BIO object: " << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    ON_BLOCK_EXIT(BIO_free, inBIO);
    if (BIO_read_filename(inBIO, keyFile.c_str()) <= 0) {
        error() << "cannot read key file when setting subject name: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    // Callback will not manipulate the password, so const_cast is safe.
    X509* x509 = PEM_read_bio_X509(inBIO,
                                   NULL,
                                   &SSLManager::password_cb,
                                   const_cast<void*>(static_cast<const void*>(&keyPassword)));
    if (x509 == NULL) {
        error() << "cannot retrieve certificate from keyfile: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }
    ON_BLOCK_EXIT(X509_free, x509);

    *subjectName = getCertificateSubjectName(x509);
    if (serverCertificateExpirationDate != NULL) {
        unsigned long long notBeforeMillis = _convertASN1ToMillis(X509_get_notBefore(x509));
        if (notBeforeMillis == 0) {
            error() << "date conversion failed";
            return false;
        }

        unsigned long long notAfterMillis = _convertASN1ToMillis(X509_get_notAfter(x509));
        if (notAfterMillis == 0) {
            error() << "date conversion failed";
            return false;
        }

        if ((notBeforeMillis > curTimeMillis64()) || (curTimeMillis64() > notAfterMillis)) {
            severe() << "The provided SSL certificate is expired or not yet valid.";
            fassertFailedNoTrace(28652);
        }

        *serverCertificateExpirationDate = Date_t::fromMillisSinceEpoch(notAfterMillis);
    }

    return true;
}

bool SSLManager::_setupPEM(SSL_CTX* context,
                           const std::string& keyFile,
                           const std::string& password) {
    if (SSL_CTX_use_certificate_chain_file(context, keyFile.c_str()) != 1) {
        error() << "cannot read certificate file: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    BIO* inBio = BIO_new(BIO_s_file());
    if (!inBio) {
        error() << "failed to allocate BIO object: " << getSSLErrorMessage(ERR_get_error());
        return false;
    }
    const auto bioGuard = MakeGuard([&inBio]() { BIO_free(inBio); });

    if (BIO_read_filename(inBio, keyFile.c_str()) <= 0) {
        error() << "cannot read PEM key file: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    // If password is empty, use default OpenSSL callback, which uses the terminal
    // to securely request the password interactively from the user.
    decltype(&SSLManager::password_cb) password_cb = nullptr;
    void* userdata = nullptr;
    if (!password.empty()) {
        password_cb = &SSLManager::password_cb;
        // SSLManager::password_cb will not manipulate the password, so const_cast is safe.
        userdata = const_cast<void*>(static_cast<const void*>(&password));
    }
    EVP_PKEY* privateKey = PEM_read_bio_PrivateKey(inBio, nullptr, password_cb, userdata);
    if (!privateKey) {
        error() << "cannot read PEM key file: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }
    const auto privateKeyGuard = MakeGuard([&privateKey]() { EVP_PKEY_free(privateKey); });

    if (SSL_CTX_use_PrivateKey(context, privateKey) != 1) {
        error() << "cannot use PEM key file: " << keyFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    // Verify that the certificate and the key go together.
    if (SSL_CTX_check_private_key(context) != 1) {
        error() << "SSL certificate validation: " << getSSLErrorMessage(ERR_get_error());
        return false;
    }

    return true;
}

Status SSLManager::_setupCA(SSL_CTX* context, const std::string& caFile) {
    // Set the list of CAs sent to clients
    STACK_OF(X509_NAME)* certNames = SSL_load_client_CA_file(caFile.c_str());
    if (certNames == NULL) {
        return Status(ErrorCodes::InvalidSSLConfiguration,
                      str::stream() << "cannot read certificate authority file: " << caFile << " "
                                    << getSSLErrorMessage(ERR_get_error()));
    }
    SSL_CTX_set_client_CA_list(context, certNames);

    // Load trusted CA
    if (SSL_CTX_load_verify_locations(context, caFile.c_str(), NULL) != 1) {
        return Status(ErrorCodes::InvalidSSLConfiguration,
                      str::stream() << "cannot read certificate authority file: " << caFile << " "
                                    << getSSLErrorMessage(ERR_get_error()));
    }

    // Set SSL to require peer (client) certificate verification
    // if a certificate is presented
    SSL_CTX_set_verify(context, SSL_VERIFY_PEER, &SSLManager::verify_cb);
    _sslConfiguration.hasCA = true;
    return Status::OK();
}

inline Status checkX509_STORE_error() {
    const auto errCode = ERR_peek_last_error();
    if (ERR_GET_LIB(errCode) != ERR_LIB_X509 ||
        ERR_GET_REASON(errCode) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
        return {ErrorCodes::InvalidSSLConfiguration,
                str::stream() << "Error adding certificate to X509 store: "
                              << ERR_reason_error_string(errCode)};
    }
    return Status::OK();
}

#if defined(_WIN32)
// This imports the certificates in a given Windows certificate store into an X509_STORE for
// openssl to use during certificate validation.
Status importCertStoreToX509_STORE(const wchar_t* storeName,
                                   DWORD storeLocation,
                                   X509_STORE* verifyStore) {
    HCERTSTORE systemStore = CertOpenStore(
        CERT_STORE_PROV_SYSTEM_W, 0, NULL, storeLocation, const_cast<LPWSTR>(storeName));
    if (systemStore == NULL) {
        return {ErrorCodes::InvalidSSLConfiguration,
                str::stream() << "error opening system CA store: " << errnoWithDescription()};
    }
    auto systemStoreGuard = MakeGuard([systemStore]() { CertCloseStore(systemStore, 0); });

    PCCERT_CONTEXT certCtx = NULL;
    while ((certCtx = CertEnumCertificatesInStore(systemStore, certCtx)) != NULL) {
        auto certBytes = static_cast<const unsigned char*>(certCtx->pbCertEncoded);
        X509* x509Obj = d2i_X509(NULL, &certBytes, certCtx->cbCertEncoded);
        if (x509Obj == NULL) {
            return {ErrorCodes::InvalidSSLConfiguration,
                    str::stream() << "Error parsing X509 object from Windows certificate store"
                                  << SSLManagerInterface::getSSLErrorMessage(ERR_get_error())};
        }
        const auto x509ObjGuard = MakeGuard([&x509Obj]() { X509_free(x509Obj); });

        if (X509_STORE_add_cert(verifyStore, x509Obj) != 1) {
            auto status = checkX509_STORE_error();
            if (!status.isOK())
                return status;
        }
    }
    int lastError = GetLastError();
    if (lastError != CRYPT_E_NOT_FOUND) {
        return {ErrorCodes::InvalidSSLConfiguration,
                str::stream() << "Error enumerating certificates: "
                              << errnoWithDescription(lastError)};
    }

    return Status::OK();
}
#elif defined(__APPLE__)

template <typename T>
class CFTypeRefHolder {
public:
    explicit CFTypeRefHolder(T ptr) : ref(static_cast<CFTypeRef>(ptr)) {}
    ~CFTypeRefHolder() {
        CFRelease(ref);
    }
    operator T() {
        return static_cast<T>(ref);
    }

private:
    CFTypeRef ref = nullptr;
};
template <typename T>
CFTypeRefHolder<T> makeCFTypeRefHolder(T ptr) {
    return CFTypeRefHolder<T>(ptr);
}

std::string OSStatusToString(OSStatus status) {
    auto errMsg = makeCFTypeRefHolder(SecCopyErrorMessageString(status, NULL));
    return std::string{CFStringGetCStringPtr(errMsg, kCFStringEncodingUTF8)};
}

Status importKeychainToX509_STORE(X509_STORE* verifyStore) {
    CFArrayRef result;
    OSStatus status;

    // This copies all the certificates trusted by the system (regardless of what keychain they're
    // attached to) into a CFArray.
    if ((status = SecTrustCopyAnchorCertificates(&result)) != 0) {
        return {ErrorCodes::InvalidSSLConfiguration,
                str::stream() << "Error enumerating certificates: " << OSStatusToString(status)};
    }
    const auto resultGuard = makeCFTypeRefHolder(result);

    for (CFIndex i = 0; i < CFArrayGetCount(result); i++) {
        SecCertificateRef cert =
            static_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(result, i)));

        auto rawData = makeCFTypeRefHolder(SecCertificateCopyData(cert));
        if (!rawData) {
            return {ErrorCodes::InvalidSSLConfiguration,
                    str::stream() << "Error enumerating certificates: "
                                  << OSStatusToString(status)};
        }
        const uint8_t* rawDataPtr = CFDataGetBytePtr(rawData);

        // Parse an openssl X509 object from each returned certificate
        X509* x509Cert = d2i_X509(nullptr, &rawDataPtr, CFDataGetLength(rawData));
        if (!x509Cert) {
            return {ErrorCodes::InvalidSSLConfiguration,
                    str::stream() << "Error parsing X509 certificate from system keychain: "
                                  << ERR_reason_error_string(ERR_peek_last_error())};
        }
        const auto x509CertGuard = MakeGuard([&x509Cert]() { X509_free(x509Cert); });

        // Add the parsed X509 object to the X509_STORE verification store
        if (X509_STORE_add_cert(verifyStore, x509Cert) != 1) {
            auto status = checkX509_STORE_error();
            if (!status.isOK())
                return status;
        }
    }

    return Status::OK();
}
#endif

Status SSLManager::_setupSystemCA(SSL_CTX* context) {
#if !defined(_WIN32) && !defined(__APPLE__)
    // On non-Windows/non-Apple platforms, the OpenSSL libraries should have been configured
    // with default locations for CA certificates.
    if (SSL_CTX_set_default_verify_paths(context) != 1) {
        return {ErrorCodes::InvalidSSLConfiguration,
                str::stream() << "error loading system CA certificates "
                              << "(default certificate file: "
                              << X509_get_default_cert_file()
                              << ", "
                              << "default certificate path: "
                              << X509_get_default_cert_dir()
                              << ")"};
    }
    return Status::OK();
#else

    X509_STORE* verifyStore = SSL_CTX_get_cert_store(context);
    if (!verifyStore) {
        return {ErrorCodes::InvalidSSLConfiguration,
                "no X509 store found for SSL context while loading system certificates"};
    }
#if defined(_WIN32)
    auto status = importCertStoreToX509_STORE(L"root", CERT_SYSTEM_STORE_CURRENT_USER, verifyStore);
    if (!status.isOK())
        return status;
    return importCertStoreToX509_STORE(L"CA", CERT_SYSTEM_STORE_CURRENT_USER, verifyStore);
#elif defined(__APPLE__)
    return importKeychainToX509_STORE(verifyStore);
#endif
#endif
}

bool SSLManager::_setupCRL(SSL_CTX* context, const std::string& crlFile) {
    X509_STORE* store = SSL_CTX_get_cert_store(context);
    fassert(16583, store);

    X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
    X509_LOOKUP* lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
    fassert(16584, lookup);

    int status = X509_load_crl_file(lookup, crlFile.c_str(), X509_FILETYPE_PEM);
    if (status == 0) {
        error() << "cannot read CRL file: " << crlFile << ' '
                << getSSLErrorMessage(ERR_get_error());
        return false;
    }
    log() << "ssl imported " << status << " revoked certificate" << ((status == 1) ? "" : "s")
          << " from the revocation list.";
    return true;
}

/*
* The interface layer between network and BIO-pair. The BIO-pair buffers
* the data to/from the TLS layer.
*/
void SSLManager::_flushNetworkBIO(SSLConnection* conn) {
    char buffer[BUFFER_SIZE];
    int wantWrite;

    /*
    * Write the complete contents of the buffer. Leaving the buffer
    * unflushed could cause a deadlock.
    */
    while ((wantWrite = BIO_ctrl_pending(conn->networkBIO)) > 0) {
        if (wantWrite > BUFFER_SIZE) {
            wantWrite = BUFFER_SIZE;
        }
        int fromBIO = BIO_read(conn->networkBIO, buffer, wantWrite);

        int writePos = 0;
        do {
            int numWrite = fromBIO - writePos;
            numWrite = send(conn->socket->rawFD(), buffer + writePos, numWrite, portSendFlags);
            if (numWrite < 0) {
                conn->socket->handleSendError(numWrite, "");
            }
            writePos += numWrite;
        } while (writePos < fromBIO);
    }

    int wantRead;
    while ((wantRead = BIO_ctrl_get_read_request(conn->networkBIO)) > 0) {
        if (wantRead > BUFFER_SIZE) {
            wantRead = BUFFER_SIZE;
        }

        int numRead = recv(conn->socket->rawFD(), buffer, wantRead, portRecvFlags);
        if (numRead <= 0) {
            conn->socket->handleRecvError(numRead, wantRead);
            continue;
        }

        int toBIO = BIO_write(conn->networkBIO, buffer, numRead);
        if (toBIO != numRead) {
            LOG(3) << "Failed to write network data to the SSL BIO layer";
            throw SocketException(SocketException::RECV_ERROR, conn->socket->remoteString());
        }
    }
}

bool SSLManager::_doneWithSSLOp(SSLConnection* conn, int status) {
    int sslErr = SSL_get_error(conn, status);
    switch (sslErr) {
        case SSL_ERROR_NONE:
            _flushNetworkBIO(conn);  // success, flush network BIO before leaving
            return true;
        case SSL_ERROR_WANT_WRITE:
        case SSL_ERROR_WANT_READ:
            _flushNetworkBIO(conn);  // not ready, flush network BIO and try again
            return false;
        default:
            return true;
    }
}

SSLConnection* SSLManager::connect(Socket* socket) {
    std::unique_ptr<SSLConnection> sslConn =
        stdx::make_unique<SSLConnection>(_clientContext.get(), socket, (const char*)NULL, 0);

    int ret = ::SSL_set_tlsext_host_name(sslConn->ssl, socket->remoteAddr().hostOrIp().c_str());
    if (ret != 1)
        _handleSSLError(SSL_get_error(sslConn.get(), ret), ret);

    do {
        ret = ::SSL_connect(sslConn->ssl);
    } while (!_doneWithSSLOp(sslConn.get(), ret));

    if (ret != 1)
        _handleSSLError(SSL_get_error(sslConn.get(), ret), ret);

    return sslConn.release();
}

SSLConnection* SSLManager::accept(Socket* socket, const char* initialBytes, int len) {
    std::unique_ptr<SSLConnection> sslConn =
        stdx::make_unique<SSLConnection>(_serverContext.get(), socket, initialBytes, len);

    int ret;
    do {
        ret = ::SSL_accept(sslConn->ssl);
    } while (!_doneWithSSLOp(sslConn.get(), ret));

    if (ret != 1)
        _handleSSLError(SSL_get_error(sslConn.get(), ret), ret);

    return sslConn.release();
}

// TODO SERVER-11601 Use NFC Unicode canonicalization
bool SSLManager::_hostNameMatch(const char* nameToMatch, const char* certHostName) {
    if (strlen(certHostName) < 2) {
        return false;
    }

    // match wildcard DNS names
    if (certHostName[0] == '*' && certHostName[1] == '.') {
        // allow name.example.com if the cert is *.example.com, '*' does not match '.'
        const char* subName = strchr(nameToMatch, '.');
        return subName && !strcasecmp(certHostName + 1, subName);
    } else {
        return !strcasecmp(nameToMatch, certHostName);
    }
}

StatusWith<boost::optional<SSLPeerInfo>> SSLManager::parseAndValidatePeerCertificate(
    SSL* conn, const std::string& remoteHost) {
    if (!_sslConfiguration.hasCA && isSSLServer)
        return {boost::none};

    X509* peerCert = SSL_get_peer_certificate(conn);

    if (NULL == peerCert) {  // no certificate presented by peer
        if (_weakValidation) {
            warning() << "no SSL certificate provided by peer";
        } else {
            auto msg = "no SSL certificate provided by peer; connection rejected";
            error() << msg;
            return Status(ErrorCodes::SSLHandshakeFailed, msg);
        }
        return {boost::none};
    }
    ON_BLOCK_EXIT(X509_free, peerCert);

    long result = SSL_get_verify_result(conn);

    if (result != X509_V_OK) {
        if (_allowInvalidCertificates) {
            warning() << "SSL peer certificate validation failed: "
                      << X509_verify_cert_error_string(result);
        } else {
            str::stream msg;
            msg << "SSL peer certificate validation failed: "
                << X509_verify_cert_error_string(result);
            error() << msg.ss.str();
            return Status(ErrorCodes::SSLHandshakeFailed, msg);
        }
    }

    // TODO: check optional cipher restriction, using cert.
    std::string peerSubjectName = getCertificateSubjectName(peerCert);
    LOG(2) << "Accepted TLS connection from peer: " << peerSubjectName;

    StatusWith<stdx::unordered_set<RoleName>> swPeerCertificateRoles = _parsePeerRoles(peerCert);
    if (!swPeerCertificateRoles.isOK()) {
        return swPeerCertificateRoles.getStatus();
    }

    // If this is an SSL client context (on a MongoDB server or client)
    // perform hostname validation of the remote server
    if (remoteHost.empty()) {
        return boost::make_optional(
            SSLPeerInfo(peerSubjectName, std::move(swPeerCertificateRoles.getValue())));
    }

    // Try to match using the Subject Alternate Name, if it exists.
    // RFC-2818 requires the Subject Alternate Name to be used if present.
    // Otherwise, the most specific Common Name field in the subject field
    // must be used.

    bool sanMatch = false;
    bool cnMatch = false;
    StringBuilder certificateNames;

    STACK_OF(GENERAL_NAME)* sanNames = static_cast<STACK_OF(GENERAL_NAME)*>(
        X509_get_ext_d2i(peerCert, NID_subject_alt_name, NULL, NULL));

    if (sanNames != NULL) {
        int sanNamesList = sk_GENERAL_NAME_num(sanNames);
        certificateNames << "SAN(s): ";
        for (int i = 0; i < sanNamesList; i++) {
            const GENERAL_NAME* currentName = sk_GENERAL_NAME_value(sanNames, i);
            if (currentName && currentName->type == GEN_DNS) {
                char* dnsName = reinterpret_cast<char*>(ASN1_STRING_data(currentName->d.dNSName));
                if (_hostNameMatch(remoteHost.c_str(), dnsName)) {
                    sanMatch = true;
                    break;
                }
                certificateNames << std::string(dnsName) << " ";
            }
        }
        sk_GENERAL_NAME_pop_free(sanNames, GENERAL_NAME_free);
    } else if (peerSubjectName.find("CN=") != std::string::npos) {
        // If Subject Alternate Name (SAN) doesn't exist and Common Name (CN) does,
        // check Common Name.
        int cnBegin = peerSubjectName.find("CN=") + 3;
        int cnEnd = peerSubjectName.find(",", cnBegin);
        std::string commonName = peerSubjectName.substr(cnBegin, cnEnd - cnBegin);

        if (_hostNameMatch(remoteHost.c_str(), commonName.c_str())) {
            cnMatch = true;
        }
        certificateNames << "CN: " << commonName;
    } else {
        certificateNames << "No Common Name (CN) or Subject Alternate Names (SAN) found";
    }

    if (!sanMatch && !cnMatch) {
        StringBuilder msgBuilder;
        msgBuilder << "The server certificate does not match the host name. Hostname: "
                   << remoteHost << " does not match " << certificateNames.str();
        std::string msg = msgBuilder.str();
        if (_allowInvalidCertificates || _allowInvalidHostnames) {
            warning() << msg;
        } else {
            error() << msg;
            return Status(ErrorCodes::SSLHandshakeFailed, msg);
        }
    }

    return boost::make_optional(SSLPeerInfo(peerSubjectName, stdx::unordered_set<RoleName>()));
}


SSLPeerInfo SSLManager::parseAndValidatePeerCertificateDeprecated(const SSLConnection* conn,
                                                                  const std::string& remoteHost) {
    auto swPeerSubjectName = parseAndValidatePeerCertificate(conn->ssl, remoteHost);
    // We can't use uassertStatusOK here because we need to throw a SocketException.
    if (!swPeerSubjectName.isOK()) {
        throw SocketException(SocketException::CONNECT_ERROR,
                              swPeerSubjectName.getStatus().reason());
    }
    return swPeerSubjectName.getValue().get_value_or(SSLPeerInfo());
}

StatusWith<stdx::unordered_set<RoleName>> SSLManager::_parsePeerRoles(X509* peerCert) const {
    // exts is owned by the peerCert
    const STACK_OF(X509_EXTENSION)* exts = X509_get0_extensions(peerCert);

    int extCount = 0;
    if (exts) {
        extCount = sk_X509_EXTENSION_num(exts);
    }

    ASN1_OBJECT* rolesObj = OBJ_nid2obj(_rolesNid);

    // Search all certificate extensions for our own
    stdx::unordered_set<RoleName> roles;
    for (int i = 0; i < extCount; i++) {
        X509_EXTENSION* ex = sk_X509_EXTENSION_value(exts, i);
        ASN1_OBJECT* obj = X509_EXTENSION_get_object(ex);

        if (!OBJ_cmp(obj, rolesObj)) {
            // We've found an extension which has our roles OID
            ASN1_OCTET_STRING* data = X509_EXTENSION_get_data(ex);

            /*
             * MongoDBAuthorizationGrant ::= CHOICE {
             *  MongoDBRole,
             *  ...!UTF8String:"Unrecognized entity in MongoDBAuthorizationGrant"
             * }
             * MongoDBAuthorizationGrants ::= SET OF MongoDBAuthorizationGrant
             */
            // Extract the set of roles from our extension, and load them into an OpenSSL stack.
            STACK_OF(ASN1_TYPE)* mongoDBAuthorizationGrants = nullptr;

            // OpenSSL's parsing function will try and manipulate the pointer it's passed. If we
            // passed it 'data->data' directly, it would modify structures owned by peerCert.
            const unsigned char* dataBytes = data->data;
            mongoDBAuthorizationGrants =
                d2i_ASN1_SET_ANY(&mongoDBAuthorizationGrants, &dataBytes, data->length);
            if (!mongoDBAuthorizationGrants) {
                return Status(ErrorCodes::FailedToParse,
                              "Failed to parse x509 authorization grants");
            }
            const auto grantGuard = MakeGuard([&mongoDBAuthorizationGrants]() {
                sk_ASN1_TYPE_pop_free(mongoDBAuthorizationGrants, ASN1_TYPE_free);
            });

            /*
             * MongoDBRole ::= SEQUENCE {
             *  role     UTF8String,
             *  database UTF8String
             * }
             */
            // Loop through every role in the stack.
            ASN1_TYPE* MongoDBRoleWrapped = nullptr;
            while ((MongoDBRoleWrapped = sk_ASN1_TYPE_pop(mongoDBAuthorizationGrants))) {
                const auto roleWrappedGuard =
                    MakeGuard([MongoDBRoleWrapped]() { ASN1_TYPE_free(MongoDBRoleWrapped); });

                if (MongoDBRoleWrapped->type == V_ASN1_SEQUENCE) {
                    // Unwrap the ASN1Type into a STACK_OF(ASN1_TYPE)
                    unsigned char* roleBytes = ASN1_STRING_data(MongoDBRoleWrapped->value.sequence);
                    int roleBytesLength = ASN1_STRING_length(MongoDBRoleWrapped->value.sequence);
                    ASN1_SEQUENCE_ANY* MongoDBRole = nullptr;
                    MongoDBRole = d2i_ASN1_SEQUENCE_ANY(
                        &MongoDBRole, (const unsigned char**)&roleBytes, roleBytesLength);
                    if (!MongoDBRole) {
                        return Status(ErrorCodes::FailedToParse,
                                      "Failed to parse role in x509 authorization grant");
                    }
                    const auto roleGuard = MakeGuard(
                        [&MongoDBRole]() { sk_ASN1_TYPE_pop_free(MongoDBRole, ASN1_TYPE_free); });

                    if (sk_ASN1_TYPE_num(MongoDBRole) != 2) {
                        return Status(ErrorCodes::FailedToParse,
                                      "Role entity in MongoDBAuthorizationGrant must have exactly "
                                      "2 sequence elements");
                    }
                    // Extract the subcomponents of the sequence, which are popped off the stack in
                    // reverse order. Here, parse the role's database.
                    ASN1_TYPE* roleComponent = sk_ASN1_TYPE_pop(MongoDBRole);
                    const auto roleDBGuard =
                        MakeGuard([roleComponent]() { ASN1_TYPE_free(roleComponent); });
                    if (roleComponent->type != V_ASN1_UTF8STRING) {
                        return Status(ErrorCodes::FailedToParse,
                                      "database in MongoDBRole must be a UTF8 string");
                    }
                    std::string roleDB(
                        reinterpret_cast<char*>(ASN1_STRING_data(roleComponent->value.utf8string)));

                    // Parse the role's name.
                    roleComponent = sk_ASN1_TYPE_pop(MongoDBRole);
                    const auto roleNameGuard =
                        MakeGuard([roleComponent]() { ASN1_TYPE_free(roleComponent); });
                    if (roleComponent->type != V_ASN1_UTF8STRING) {
                        return Status(ErrorCodes::FailedToParse,
                                      "role in MongoDBRole must be a UTF8 string");
                    }
                    std::string roleName(
                        reinterpret_cast<char*>(ASN1_STRING_data(roleComponent->value.utf8string)));

                    // Construct a RoleName from the subcomponents
                    roles.emplace(RoleName(roleName, roleDB));

                } else {
                    return Status(ErrorCodes::FailedToParse,
                                  "Unrecognized entity in MongoDBAuthorizationGrant");
                }
            }
            LOG(1) << "MONGODB-X509 authorization parsed the following roles from peer "
                      "certificate: "
                   << [&roles]() {
                          StringBuilder sb;
                          std::for_each(roles.begin(), roles.end(), [&sb](const RoleName& role) {
                              sb << role.toString();
                          });
                          return sb.str();
                      }();
        }
    }

    return roles;
}

std::string SSLManagerInterface::getSSLErrorMessage(int code) {
    // 120 from the SSL documentation for ERR_error_string
    static const size_t msglen = 120;

    char msg[msglen];
    ERR_error_string_n(code, msg, msglen);
    return msg;
}

void SSLManager::_handleSSLError(int code, int ret) {
    int err = ERR_get_error();

    switch (code) {
        case SSL_ERROR_WANT_READ:
        case SSL_ERROR_WANT_WRITE:
            // should not happen because we turned on AUTO_RETRY
            // However, it turns out this CAN happen during a connect, if the other side
            // accepts the socket connection but fails to do the SSL handshake in a timely
            // manner.
            error() << "SSL: " << code << ", possibly timed out during connect";
            break;

        case SSL_ERROR_ZERO_RETURN:
            // TODO: Check if we can avoid throwing an exception for this condition
            LOG(3) << "SSL network connection closed";
            break;
        case SSL_ERROR_SYSCALL:
            // If ERR_get_error returned 0, the error queue is empty
            // check the return value of the actual SSL operation
            if (err != 0) {
                error() << "SSL: " << getSSLErrorMessage(err);
            } else if (ret == 0) {
                error() << "Unexpected EOF encountered during SSL communication";
            } else {
                error() << "The SSL BIO reported an I/O error " << errnoWithDescription();
            }
            break;
        case SSL_ERROR_SSL: {
            error() << "SSL: " << getSSLErrorMessage(err);
            break;
        }

        default:
            error() << "unrecognized SSL error";
            break;
    }
    throw SocketException(SocketException::CONNECT_ERROR, "");
}
#else

MONGO_INITIALIZER(SSLManager)(InitializerContext*) {
    // we need a no-op initializer so that we can depend on SSLManager as a prerequisite in
    // non-SSL builds.
    return Status::OK();
}

#endif  // #ifdef MONGO_CONFIG_SSL
}