summaryrefslogtreecommitdiff
path: root/src/mongo/util/net/ssl_manager_test.cpp
blob: 2fc17e8f3365738ee2ca06dc3852af0a9ea9f49b (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
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    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 Server Side 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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest

#include <fstream>

#include "mongo/config.h"
#include "mongo/platform/basic.h"

#include "mongo/transport/service_entry_point.h"
#include "mongo/transport/transport_layer_asio.h"
#include "mongo/transport/transport_layer_manager.h"
#include "mongo/util/net/ssl/context.hpp"
#include "mongo/util/net/ssl_manager.h"
#include "mongo/util/net/ssl_options.h"

#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"

#if MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL
#include "mongo/util/net/dh_openssl.h"
#include "mongo/util/net/ssl/context_openssl.hpp"
#endif


namespace mongo {
namespace {

// Test implementation needed by ASIO transport.
class ServiceEntryPointUtil : public ServiceEntryPoint {
public:
    void startSession(transport::SessionHandle session) override {
        stdx::unique_lock<Latch> lk(_mutex);
        _sessions.push_back(std::move(session));
        LOGV2(2303202, "started session");
        _cv.notify_one();
    }

    void endAllSessions(transport::Session::TagMask tags) override {
        LOGV2(2303302, "end all sessions");
        std::vector<transport::SessionHandle> old_sessions;
        {
            stdx::unique_lock<Latch> lock(_mutex);
            old_sessions.swap(_sessions);
        }
        old_sessions.clear();
    }

    Status start() override {
        return Status::OK();
    }

    bool shutdown(Milliseconds timeout) override {
        return true;
    }

    void appendStats(BSONObjBuilder*) const override {}

    size_t numOpenSessions() const override {
        stdx::unique_lock<Latch> lock(_mutex);
        return _sessions.size();
    }

    Future<DbResponse> handleRequest(OperationContext* opCtx,
                                     const Message& request) noexcept override {
        MONGO_UNREACHABLE;
    }

    void setTransportLayer(transport::TransportLayer* tl) {
        _transport = tl;
    }

    void waitForConnect() {
        stdx::unique_lock<Latch> lock(_mutex);
        _cv.wait(lock, [&] { return !_sessions.empty(); });
    }

private:
    mutable Mutex _mutex = MONGO_MAKE_LATCH("::_mutex");
    stdx::condition_variable _cv;
    std::vector<transport::SessionHandle> _sessions;
    transport::TransportLayer* _transport = nullptr;
};

std::string loadFile(const std::string& name) {
    std::ifstream input(name);
    std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
    return str;
}

TEST(SSLManager, matchHostname) {
    enum Expected : bool { match = true, mismatch = false };
    const struct {
        Expected expected;
        std::string hostname;
        std::string certName;
    } tests[] = {
        // clang-format off
        // Matches?  |    Hostname and possibly FQDN   |  Certificate name
        {match,                    "foo.bar.bas" ,           "*.bar.bas."},
        {mismatch,       "foo.subdomain.bar.bas" ,           "*.bar.bas."},
        {match,                    "foo.bar.bas.",           "*.bar.bas."},
        {mismatch,       "foo.subdomain.bar.bas.",           "*.bar.bas."},

        {match,                    "foo.bar.bas" ,           "*.bar.bas"},
        {mismatch,       "foo.subdomain.bar.bas" ,           "*.bar.bas"},
        {match,                    "foo.bar.bas.",           "*.bar.bas"},
        {mismatch,       "foo.subdomain.bar.bas.",           "*.bar.bas"},

        {mismatch,                "foo.evil.bas" ,           "*.bar.bas."},
        {mismatch,      "foo.subdomain.evil.bas" ,           "*.bar.bas."},
        {mismatch,                "foo.evil.bas.",           "*.bar.bas."},
        {mismatch,      "foo.subdomain.evil.bas.",           "*.bar.bas."},

        {mismatch,                "foo.evil.bas" ,           "*.bar.bas"},
        {mismatch,      "foo.subdomain.evil.bas" ,           "*.bar.bas"},
        {mismatch,                "foo.evil.bas.",           "*.bar.bas"},
        {mismatch,      "foo.subdomain.evil.bas.",           "*.bar.bas"},
        // clang-format on
    };
    bool failure = false;
    for (const auto& test : tests) {
        if (bool(test.expected) != hostNameMatchForX509Certificates(test.hostname, test.certName)) {
            failure = true;
            LOGV2_DEBUG(23266,
                        1,
                        "Failure for Hostname: {test_hostname} Certificate: {test_certName}",
                        "test_hostname"_attr = test.hostname,
                        "test_certName"_attr = test.certName);
        } else {
            LOGV2_DEBUG(23267,
                        1,
                        "Passed for Hostname: {test_hostname} Certificate: {test_certName}",
                        "test_hostname"_attr = test.hostname,
                        "test_certName"_attr = test.certName);
        }
    }
    ASSERT_FALSE(failure);
}

std::vector<RoleName> getSortedRoles(const stdx::unordered_set<RoleName>& roles) {
    std::vector<RoleName> vec;
    vec.reserve(roles.size());
    std::copy(roles.begin(), roles.end(), std::back_inserter<std::vector<RoleName>>(vec));
    std::sort(vec.begin(), vec.end());
    return vec;
}

TEST(SSLManager, MongoDBRolesParser) {
    /*
    openssl asn1parse -genconf mongodbroles.cnf -out foo.der

    -------- mongodbroles.cnf --------
    asn1 = SET:MongoDBAuthorizationGrant

    [MongoDBAuthorizationGrant]
    grant1 = SEQUENCE:MongoDBRole

    [MongoDBRole]
    role  = UTF8:role_name
    database = UTF8:Third field
    */
    // Positive: Simple parsing test
    {
        unsigned char derData[] = {0x31, 0x1a, 0x30, 0x18, 0x0c, 0x09, 0x72, 0x6f, 0x6c, 0x65,
                                   0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x0c, 0x0b, 0x54, 0x68, 0x69,
                                   0x72, 0x64, 0x20, 0x66, 0x69, 0x65, 0x6c, 0x64};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_OK(swPeer.getStatus());
        auto item = *(swPeer.getValue().begin());
        ASSERT_EQ(item.getRole(), "role_name");
        ASSERT_EQ(item.getDB(), "Third field");
    }

    // Positive: Very long role_name, and long form lengths
    {
        unsigned char derData[] = {
            0x31, 0x82, 0x01, 0x3e, 0x30, 0x82, 0x01, 0x3a, 0x0c, 0x82, 0x01, 0x29, 0x72, 0x6f,
            0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61,
            0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c,
            0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d,
            0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65,
            0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65,
            0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f,
            0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72,
            0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e,
            0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f,
            0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61,
            0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c,
            0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d,
            0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65,
            0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65,
            0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f,
            0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72,
            0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e,
            0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f,
            0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61,
            0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c,
            0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d,
            0x65, 0x0c, 0x0b, 0x54, 0x68, 0x69, 0x72, 0x64, 0x20, 0x66, 0x69, 0x65, 0x6c, 0x64};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_OK(swPeer.getStatus());

        auto item = *(swPeer.getValue().begin());
        ASSERT_EQ(item.getRole(),
                  "role_namerole_namerole_namerole_namerole_namerole_namerole_namerole_namerole_"
                  "namerole_namerole_namerole_namerole_namerole_namerole_namerole_namerole_"
                  "namerole_namerole_namerole_namerole_namerole_namerole_namerole_namerole_"
                  "namerole_namerole_namerole_namerole_namerole_namerole_namerole_namerole_name");
        ASSERT_EQ(item.getDB(), "Third field");
    }

    // Negative: Encode MAX_INT64 into a length
    {
        unsigned char derData[] = {0x31, 0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                                   0xff, 0x3e, 0x18, 0x0c, 0x09, 0x72, 0x6f, 0x6c, 0x65, 0x5f,
                                   0x6e, 0x61, 0x6d, 0x65, 0x0c, 0x0b, 0x54, 0x68, 0x69, 0x72,
                                   0x64, 0x20, 0x66, 0x69, 0x65, 0x6c, 0x64};

        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Runt, only a tag
    {
        unsigned char derData[] = {0x31};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Runt, only a tag and short length
    {
        unsigned char derData[] = {0x31, 0x0b};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Runt, only a tag and long length with wrong missing length
    {
        unsigned char derData[] = {
            0x31,
            0x88,
            0xff,
            0xff,
        };
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Runt, only a tag and long length
    {
        unsigned char derData[] = {
            0x31,
            0x82,
            0xff,
            0xff,
        };
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Single UTF8 String
    {
        unsigned char derData[] = {
            0x0c, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Negative: Unknown type - IAString
    {
        unsigned char derData[] = {
            0x16, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_NOT_OK(swPeer.getStatus());
    }

    // Positive: two roles
    {
        unsigned char derData[] = {0x31, 0x2b, 0x30, 0x0f, 0x0c, 0x06, 0x62, 0x61, 0x63,
                                   0x6b, 0x75, 0x70, 0x0c, 0x05, 0x61, 0x64, 0x6d, 0x69,
                                   0x6e, 0x30, 0x18, 0x0c, 0x0f, 0x72, 0x65, 0x61, 0x64,
                                   0x41, 0x6e, 0x79, 0x44, 0x61, 0x74, 0x61, 0x62, 0x61,
                                   0x73, 0x65, 0x0c, 0x05, 0x61, 0x64, 0x6d, 0x69, 0x6e};
        auto swPeer = parsePeerRoles(ConstDataRange(derData));
        ASSERT_OK(swPeer.getStatus());

        auto roles = getSortedRoles(swPeer.getValue());
        ASSERT_EQ(roles[0].getRole(), "backup");
        ASSERT_EQ(roles[0].getDB(), "admin");
        ASSERT_EQ(roles[1].getRole(), "readAnyDatabase");
        ASSERT_EQ(roles[1].getDB(), "admin");
    }
}

TEST(SSLManager, TLSFeatureParser) {
    {
        // test correct feature resolution with one feature
        unsigned char derData[] = {0x30, 0x03, 0x02, 0x01, 0x05};
        std::vector<DERInteger> correctFeatures = {{0x05}};
        auto swFeatures = parseTLSFeature(ConstDataRange(derData));
        ASSERT_OK(swFeatures.getStatus());

        auto features = swFeatures.getValue();
        ASSERT_TRUE(features == correctFeatures);
    }

    {
        // test incorrect feature resolution (malformed header)
        unsigned char derData[] = {0xFF, 0x03, 0x02, 0x01, 0x05};
        std::vector<DERInteger> correctFeatures = {{0x05}};
        auto swFeatures = parseTLSFeature(ConstDataRange(derData));
        ASSERT_NOT_OK(swFeatures.getStatus());
    }

    {
        // test feature resolution with multiple features
        unsigned char derData[] = {0x30, 0x06, 0x02, 0x01, 0x05, 0x02, 0x01, 0x01};
        std::vector<DERInteger> correctFeatures = {{0x05}, {0x01}};
        auto swFeatures = parseTLSFeature(ConstDataRange(derData));
        ASSERT_OK(swFeatures.getStatus());

        auto features = swFeatures.getValue();
        ASSERT_TRUE(features == correctFeatures);
    }
}

TEST(SSLManager, EscapeRFC2253) {
    ASSERT_EQ(escapeRfc2253("abc"), "abc");
    ASSERT_EQ(escapeRfc2253(" abc"), "\\ abc");
    ASSERT_EQ(escapeRfc2253("#abc"), "\\#abc");
    ASSERT_EQ(escapeRfc2253("a,c"), "a\\,c");
    ASSERT_EQ(escapeRfc2253("a+c"), "a\\+c");
    ASSERT_EQ(escapeRfc2253("a\"c"), "a\\\"c");
    ASSERT_EQ(escapeRfc2253("a\\c"), "a\\\\c");
    ASSERT_EQ(escapeRfc2253("a<c"), "a\\<c");
    ASSERT_EQ(escapeRfc2253("a>c"), "a\\>c");
    ASSERT_EQ(escapeRfc2253("a;c"), "a\\;c");
    ASSERT_EQ(escapeRfc2253("abc "), "abc\\ ");
}

#if MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL
TEST(SSLManager, DHCheckRFC7919) {
    auto dhparams = makeDefaultDHParameters();
    ASSERT_EQ(verifyDHParameters(dhparams), 0);
}
#endif

struct FlattenedX509Name {
    using EntryVector = std::vector<std::pair<std::string, std::string>>;

    FlattenedX509Name(std::initializer_list<EntryVector::value_type> forVector)
        : value(forVector) {}

    FlattenedX509Name() = default;

    void addPair(std::string oid, std::string val) {
        value.emplace_back(std::move(oid), std::move(val));
    }

    std::string toString() const {
        bool first = true;
        StringBuilder sb;
        for (const auto& entry : value) {
            sb << (first ? "\"" : ",\"") << entry.first << "\"=\"" << entry.second << "\"";
            first = false;
        }

        return sb.str();
    }

    EntryVector value;

    bool operator==(const FlattenedX509Name& other) const {
        return value == other.value;
    }
};

std::ostream& operator<<(std::ostream& o, const FlattenedX509Name& name) {
    o << name.toString();
    return o;
}

FlattenedX509Name flattenX509Name(const SSLX509Name& name) {
    FlattenedX509Name ret;
    for (const auto& entry : name.entries()) {
        for (const auto& rdn : entry) {
            ret.addPair(rdn.oid, rdn.value);
        }
    }

    return ret;
}

TEST(SSLManager, DNParsingAndNormalization) {
    std::vector<std::pair<std::string, FlattenedX509Name>> tests = {
        // Basic DN parsing
        {"UID=jsmith,DC=example,DC=net",
         {{"0.9.2342.19200300.100.1.1", "jsmith"},
          {"0.9.2342.19200300.100.1.25", "example"},
          {"0.9.2342.19200300.100.1.25", "net"}}},
        {"OU=Sales+CN=J.  Smith,DC=example,DC=net",
         {{"2.5.4.11", "Sales"},
          {"2.5.4.3", "J.  Smith"},
          {"0.9.2342.19200300.100.1.25", "example"},
          {"0.9.2342.19200300.100.1.25", "net"}}},
        {"CN=server, O=, DC=example, DC=net",
         {{"2.5.4.3", "server"},
          {"2.5.4.10", ""},
          {"0.9.2342.19200300.100.1.25", "example"},
          {"0.9.2342.19200300.100.1.25", "net"}}},
        {R"(CN=James \"Jim\" Smith\, III,DC=example,DC=net)",
         {{"2.5.4.3", R"(James "Jim" Smith, III)"},
          {"0.9.2342.19200300.100.1.25", "example"},
          {"0.9.2342.19200300.100.1.25", "net"}}},
        // Per RFC4518, control sequences are mapped to nothing and whitepace is mapped to ' '
        {"CN=Before\\0aAfter,O=tabs\tare\tspaces\u200B,DC=\\07\\08example,DC=net",
         {{"2.5.4.3", "Before After"},
          {"2.5.4.10", "tabs are spaces"},
          {"0.9.2342.19200300.100.1.25", "example"},
          {"0.9.2342.19200300.100.1.25", "net"}}},
        // Check that you can't fake a cluster dn with poor comma escaping
        {R"(CN=evil\,OU\=Kernel,O=MongoDB Inc.,L=New York City,ST=New York,C=US)",
         {{"2.5.4.3", "evil,OU=Kernel"},
          {"2.5.4.10", "MongoDB Inc."},
          {"2.5.4.7", "New York City"},
          {"2.5.4.8", "New York"},
          {"2.5.4.6", "US"}}},
        // check space handling (must be escaped at the beginning and end of strings)
        {R"(CN= \ escaped spaces\20\  )", {{"2.5.4.3", " escaped spaces  "}}},
        {"CN=server, O=MongoDB Inc.", {{"2.5.4.3", "server"}, {"2.5.4.10", "MongoDB Inc."}}},
        // Check that escaped #'s work correctly at the beginning of the string and throughout.
        {R"(CN=\#1 = \\#1)", {{"2.5.4.3", "#1 = \\#1"}}},
        {R"(CN== \#1)", {{"2.5.4.3", "= #1"}}},
        // check that escaped utf8 string properly parse to utf8
        {R"(CN=Lu\C4\8Di\C4\87)", {{"2.5.4.3", "Lučić"}}},
        // check that unescaped utf8 strings round trip correctly
        {"CN = Калоян, O=مُنظّمة الدُّول المُصدِّرة للنّفْط, L=大田区\\, 東京都",
         {{"2.5.4.3", "Калоян"},
          {"2.5.4.10", "مُنظّمة الدُّول المُصدِّرة للنّفْط"},
          {"2.5.4.7", "大田区, 東京都"}}}};

    for (const auto& test : tests) {
        LOGV2(23268, "Testing DN \"{test_first}\"", "test_first"_attr = test.first);
        auto swDN = parseDN(test.first);
        ASSERT_OK(swDN.getStatus());
        ASSERT_OK(swDN.getValue().normalizeStrings());
        auto decoded = flattenX509Name(swDN.getValue());
        ASSERT_EQ(decoded, test.second);
    }
}

TEST(SSLManager, BadDNParsing) {
    std::vector<std::string> tests = {"CN=#12345", R"(CN=\B)", R"(CN=<", "\)"};
    for (const auto& test : tests) {
        LOGV2(23269, "Testing bad DN: \"{test}\"", "test"_attr = test);
        auto swDN = parseDN(test);
        ASSERT_NOT_OK(swDN.getStatus());
    }
}

TEST(SSLManager, RotateCertificatesFromFile) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    // Server is required to have the sslPEMKeyFile.
    params.sslPEMKeyFile = "jstests/libs/server.pem";
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslClusterFile = "jstests/libs/client.pem";

    std::shared_ptr<SSLManagerInterface> manager =
        SSLManagerInterface::create(params, true /* isSSLServer */);

    ServiceEntryPointUtil sepu;

    auto options = [] {
        ServerGlobalParams params;
        params.noUnixSocket = true;
        transport::TransportLayerASIO::Options opts(&params);
        return opts;
    }();
    transport::TransportLayerASIO tla(options, &sepu);
    uassertStatusOK(tla.rotateCertificates(manager, false /* asyncOCSPStaple */));
}

TEST(SSLManager, InitContextFromFileShouldFail) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    // Server is required to have the sslPEMKeyFile.
    // We force the initialization to fail by omitting this param.
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslClusterFile = "jstests/libs/client.pem";
#if MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL
    ASSERT_THROWS_CODE([&params] { SSLManagerInterface::create(params, true /* isSSLServer */); }(),
                       DBException,
                       ErrorCodes::InvalidSSLConfiguration);
#endif
}

TEST(SSLManager, RotateClusterCertificatesFromFile) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    // Client doesn't need params.sslPEMKeyFile.
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslClusterFile = "jstests/libs/client.pem";

    std::shared_ptr<SSLManagerInterface> manager =
        SSLManagerInterface::create(params, false /* isSSLServer */);

    ServiceEntryPointUtil sepu;

    auto options = [] {
        ServerGlobalParams params;
        params.noUnixSocket = true;
        transport::TransportLayerASIO::Options opts(&params);
        return opts;
    }();
    transport::TransportLayerASIO tla(options, &sepu);
    uassertStatusOK(tla.rotateCertificates(manager, false /* asyncOCSPStaple */));
}

#if MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL

TEST(SSLManager, InitContextFromFile) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    // Client doesn't need params.sslPEMKeyFile.
    params.sslClusterFile = "jstests/libs/client.pem";

    std::shared_ptr<SSLManagerInterface> manager =
        SSLManagerInterface::create(params, false /* isSSLServer */);

    auto egress = std::make_unique<asio::ssl::context>(asio::ssl::context::sslv23);
    uassertStatusOK(manager->initSSLContext(
        egress->native_handle(), params, SSLManagerInterface::ConnectionDirection::kOutgoing));
}

TEST(SSLManager, InitContextFromMemory) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    params.sslCAFile = "jstests/libs/ca.pem";

    TransientSSLParams transientParams;
    transientParams.sslClusterPEMPayload = loadFile("jstests/libs/client.pem");

    std::shared_ptr<SSLManagerInterface> manager =
        SSLManagerInterface::create(params, transientParams, false /* isSSLServer */);

    auto egress = std::make_unique<asio::ssl::context>(asio::ssl::context::sslv23);
    uassertStatusOK(manager->initSSLContext(
        egress->native_handle(), params, SSLManagerInterface::ConnectionDirection::kOutgoing));
}

// Tests when 'is server' param to managed interface creation is set, it is ignored.
TEST(SSLManager, IgnoreInitServerSideContextFromMemory) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    params.sslPEMKeyFile = "jstests/libs/server.pem";
    params.sslCAFile = "jstests/libs/ca.pem";

    TransientSSLParams transientParams;
    transientParams.sslClusterPEMPayload = loadFile("jstests/libs/client.pem");

    std::shared_ptr<SSLManagerInterface> manager =
        SSLManagerInterface::create(params, transientParams, true /* isSSLServer */);

    auto egress = std::make_unique<asio::ssl::context>(asio::ssl::context::sslv23);
    uassertStatusOK(manager->initSSLContext(
        egress->native_handle(), params, SSLManagerInterface::ConnectionDirection::kOutgoing));
}

TEST(SSLManager, TransientSSLParams) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslClusterFile = "jstests/libs/client.pem";

    ServiceEntryPointUtil sepu;

    auto options = [] {
        ServerGlobalParams params;
        params.noUnixSocket = true;
        transport::TransportLayerASIO::Options opts(&params);
        return opts;
    }();
    transport::TransportLayerASIO tla(options, &sepu);

    TransientSSLParams transientSSLParams;
    transientSSLParams.sslClusterPEMPayload = loadFile("jstests/libs/client.pem");
    transientSSLParams.targetedClusterConnectionString = ConnectionString::forLocal();

    auto swContext = tla.createTransientSSLContext(transientSSLParams);
    uassertStatusOK(swContext.getStatus());

    // Check that the manager owned by the transient context is also transient.
    ASSERT_TRUE(swContext.getValue()->manager->isTransient());
    ASSERT_EQ(transientSSLParams.targetedClusterConnectionString.toString(),
              swContext.getValue()->manager->getTargetedClusterConnectionString());
}

#endif  // MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL

static bool isSanWarningWritten(const std::vector<std::string>& logLines) {
    for (const auto& line : logLines) {
        if (std::string::npos !=
            line.find("Server certificate has no compatible Subject Alternative Name")) {
            return true;
        }
    }
    return false;
}

// This test verifies there is a startup warning if Subject Alternative Name is missing
TEST(SSLManager, InitContextSanWarning) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslPEMKeyFile = "jstests/libs/server_no_SAN.pem";

    startCapturingLogMessages();
    auto manager = SSLManagerInterface::create(params, true);
    auto egress = std::make_unique<asio::ssl::context>(asio::ssl::context::sslv23);

    uassertStatusOK(manager->initSSLContext(
        egress->native_handle(), params, SSLManagerInterface::ConnectionDirection::kIncoming));
    stopCapturingLogMessages();

    ASSERT_TRUE(isSanWarningWritten(getCapturedTextFormatLogMessages()));
}

// This test verifies there is no startup warning if Subject Alternative Name is present
TEST(SSLManager, InitContextNoSanWarning) {
    SSLParams params;
    params.sslMode.store(::mongo::sslGlobalParams.SSLMode_requireSSL);
    params.sslCAFile = "jstests/libs/ca.pem";
    params.sslPEMKeyFile = "jstests/libs/server.pem";

    startCapturingLogMessages();
    auto manager = SSLManagerInterface::create(params, true);
    auto egress = std::make_unique<asio::ssl::context>(asio::ssl::context::sslv23);

    uassertStatusOK(manager->initSSLContext(
        egress->native_handle(), params, SSLManagerInterface::ConnectionDirection::kIncoming));
    stopCapturingLogMessages();

    ASSERT_FALSE(isSanWarningWritten(getCapturedTextFormatLogMessages()));
}


}  // namespace
}  // namespace mongo