summaryrefslogtreecommitdiff
path: root/cpp/src/IceSSL/Context.cpp
blob: 660ef2b796fd8e223dfa29d202fd1b0ab4fa4b33 (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
// **********************************************************************
//
// Copyright (c) 2002
// ZeroC, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <Ice/LoggerUtil.h>
#include <Ice/Properties.h>

#include <IceSSL/DefaultCertificateVerifier.h>
#include <IceSSL/Exception.h>
#include <IceSSL/RSAKeyPair.h>
#include <IceSSL/CertificateDesc.h>
#include <IceSSL/SslTransceiver.h>
#include <IceSSL/Context.h>
#include <IceSSL/OpenSSLJanitors.h>
#include <IceSSL/OpenSSLUtils.h>
#include <IceSSL/TraceLevels.h>

#include <openssl/err.h>

using namespace std;
using namespace Ice;
using namespace IceInternal;

void ::IceInternal::incRef(::IceSSL::Context* p) { p->__incRef(); }
void ::IceInternal::decRef(::IceSSL::Context* p) { p->__decRef(); }

IceSSL::Context::~Context()
{
    if(_sslContext != 0)
    {
        SSL_CTX_free(_sslContext);

        _sslContext = 0;
    }
}

bool
IceSSL::Context::isConfigured()
{
    return (_sslContext != 0 ? true : false);
}

void
IceSSL::Context::setCertificateVerifier(const CertificateVerifierPtr& verifier)
{
    _certificateVerifier = verifier;
}

void
IceSSL::Context::addTrustedCertificateBase64(const string& trustedCertString)
{
    RSAPublicKey pubKey(trustedCertString);

    addTrustedCertificate(pubKey);
}

void
IceSSL::Context::addTrustedCertificate(const Ice::ByteSeq& trustedCert)
{
    RSAPublicKey pubKey(trustedCert);

    addTrustedCertificate(pubKey);
}

void
IceSSL::Context::setRSAKeysBase64(const string& privateKey,
                                           const string& publicKey)
{
    if(privateKey.empty())
    {
        IceSSL::PrivateKeyException privateKeyEx(__FILE__, __LINE__);

        privateKeyEx.message = "Empty private key supplied.";

        throw privateKeyEx;
    }

    addKeyCert(privateKey, publicKey);
}

void
IceSSL::Context::setRSAKeys(const Ice::ByteSeq& privateKey, const Ice::ByteSeq& publicKey)
{
    if(privateKey.empty())
    {
        IceSSL::PrivateKeyException privateKeyEx(__FILE__, __LINE__);

        privateKeyEx.message = "Empty private key supplied.";

        throw privateKeyEx;
    }

    addKeyCert(privateKey, publicKey);
}

void
IceSSL::Context::configure(const GeneralConfig& generalConfig,
                                    const CertificateAuthority& certificateAuthority,
                                    const BaseCertificates& baseCertificates)
{
    // Create an SSL Context based on the context params.
    createContext(generalConfig.getProtocol());

    // Get the cipherlist and set it in the context.
    setCipherList(generalConfig.getCipherList());

    // Set the certificate verification mode.
    SSL_CTX_set_verify(_sslContext, generalConfig.getVerifyMode(), verifyCallback);

    // Set the certificate verify depth
    SSL_CTX_set_verify_depth(_sslContext, generalConfig.getVerifyDepth());

    // Determine the number of retries the user gets on passphrase entry.
    string passphraseRetries = _properties->getPropertyWithDefault(_passphraseRetriesProperty,
                                                                        _maxPassphraseRetriesDefault);
    int retries = atoi(passphraseRetries.c_str());
    retries = (retries < 0 ? 0 : retries);
    _maxPassphraseTries = retries + 1;

    // Process the RSA Certificate
    setKeyCert(baseCertificates.getRSACert(), _rsaPrivateKeyProperty, _rsaPublicKeyProperty);

    // Process the DSA Certificate
    setKeyCert(baseCertificates.getDSACert(), _dsaPrivateKeyProperty, _dsaPublicKeyProperty);

    // Set the DH key agreement parameters.
    if(baseCertificates.getDHParams().getKeySize() != 0)
    {
        setDHParams(baseCertificates);
    }
}

//
// Protected
//

IceSSL::Context::Context(const TraceLevelsPtr& traceLevels, const LoggerPtr& logger, const PropertiesPtr& properties) :
    _traceLevels(traceLevels),
    _logger(logger),
    _properties(properties)
{
    _certificateVerifier = new DefaultCertificateVerifier(traceLevels, logger);
    _sslContext = 0;

    _maxPassphraseRetriesDefault = "4";
}

SSL_METHOD*
IceSSL::Context::getSslMethod(SslProtocol sslVersion)
{
    SSL_METHOD* sslMethod = 0;

    switch(sslVersion)
    {
        case SSL_V2 :
        {
            sslMethod = SSLv2_method();
            break;
        }

        case SSL_V23 :
        {
            sslMethod = SSLv23_method();
            break;
        }

        case SSL_V3 :
        {
            sslMethod = SSLv3_method();
            break;
        }

        case TLS_V1 :
        {
            sslMethod = TLSv1_method();
            break;
        }

        default :
        {
            if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
            { 
                Trace out(_logger, _traceLevels->securityCat);
                out << "WRN ssl version " << sslVersion;
                out << " not supported (defaulting to SSL_V23)";
            }

            sslMethod = SSLv23_method();
        }
    }

    return sslMethod;
}

void
IceSSL::Context::createContext(SslProtocol sslProtocol)
{
    if(_sslContext != 0)
    {
        SSL_CTX_free(_sslContext);
        _sslContext = 0;
    }

    _sslContext = SSL_CTX_new(getSslMethod(sslProtocol));

    if(_sslContext == 0)
    {
        ContextInitializationException contextInitEx(__FILE__, __LINE__);

        contextInitEx.message = "unable to create ssl context\n" + sslGetErrors();

        throw contextInitEx;
    }

    // Turn off session caching, supposedly fixes a problem with multithreading.
    SSL_CTX_set_session_cache_mode(_sslContext, SSL_SESS_CACHE_OFF);
}

void
IceSSL::Context::loadCertificateAuthority(const CertificateAuthority& certAuth)
{
    assert(_sslContext != 0);

    string fileName = certAuth.getCAFileName();
    string certPath = certAuth.getCAPath();

    const char* caFile = 0;
    const char* caPath = 0;

    // The following checks are required to send the expected values to the OpenSSL library.
    // It does not like receiving "", but prefers NULLs.

    if(!fileName.empty())
    {
        caFile = fileName.c_str();
    }

    if(!certPath.length())
    {
        caPath = certPath.c_str();
    }

    // SSL_CTX_set_default_passwd_cb(sslContext, passwordCallback);

    // Check the Certificate Authority file(s).
    int loadVerifyRet = SSL_CTX_load_verify_locations(_sslContext, caFile, caPath);

    if(!loadVerifyRet)
    { 
        if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
        {
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN unable to load certificate authorities.";
        }
    }
    else
    {
        int setDefaultVerifyPathsRet = SSL_CTX_set_default_verify_paths(_sslContext);


        if(!setDefaultVerifyPathsRet && (_traceLevels->security >= IceSSL::SECURITY_WARNINGS))
        { 
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN unable to verify certificate authorities.";
        }
    }

    // Now we add whatever override/addition that we wish to put into the trusted certificates list
    string caCertBase64 = _properties->getProperty(_caCertificateProperty);
    if(!caCertBase64.empty())
    {
         addTrustedCertificateBase64(caCertBase64);
    }
}

void
IceSSL::Context::setKeyCert(const CertificateDesc& certDesc,
                                     const string& privateProperty,
                                     const string& publicProperty)
{
    string privateKey;
    string publicKey;

    if(!privateProperty.empty())
    {
        privateKey = _properties->getProperty(privateProperty);
    }

    if(!publicProperty.empty())
    {
        publicKey = _properties->getProperty(publicProperty);
    }

    if(!privateKey.empty() && !publicKey.empty())
    {
        addKeyCert(privateKey, publicKey);
    }
    else if(certDesc.getKeySize() != 0)
    {
        const CertificateFile& privateKey = certDesc.getPrivate();
        const CertificateFile& publicKey  = certDesc.getPublic();

        addKeyCert(privateKey, publicKey);
    }
}

void
IceSSL::Context::checkKeyCert()
{
    assert(_sslContext != 0);

    // Check to see if the Private and Public keys that have been
    // set against the SSL context match up.
    if(!SSL_CTX_check_private_key(_sslContext))
    {
        CertificateKeyMatchException certKeyMatchEx(__FILE__, __LINE__);

        certKeyMatchEx.message = "private key does not match the certificate public key";
        string sslError = sslGetErrors();

        if(!sslError.empty())
        {
            certKeyMatchEx.message += "\n";
            certKeyMatchEx.message += sslError;
        }

        throw certKeyMatchEx;
    }
}

void
IceSSL::Context::addTrustedCertificate(const RSAPublicKey& trustedCertificate)
{
    if(_sslContext == 0)
    {
        ContextNotConfiguredException contextConfigEx(__FILE__, __LINE__);

        contextConfigEx.message = "ssl context not configured";

        throw contextConfigEx;
    }

    X509_STORE* certStore = SSL_CTX_get_cert_store(_sslContext);

    assert(certStore != 0);

    if(X509_STORE_add_cert(certStore, trustedCertificate.getX509PublicKey()) == 0)
    {
        TrustedCertificateAddException trustEx(__FILE__, __LINE__);

        trustEx.message = sslGetErrors();

        throw trustEx;
    }
}

void
IceSSL::Context::addKeyCert(const CertificateFile& privateKey, const CertificateFile& publicCert)
{
    assert(_sslContext != 0);

    if(!publicCert.getFileName().empty())
    {
	string publicCertFile = publicCert.getFileName();
        const char* publicFile = publicCertFile.c_str();
        int publicEncoding = publicCert.getEncoding();

        string privCertFile = privateKey.getFileName();
        const char* privKeyFile = privCertFile.c_str();
        int privKeyFileType = privateKey.getEncoding();

        // Set which Public Key file to use.
        if(SSL_CTX_use_certificate_file(_sslContext, publicFile, publicEncoding) <= 0)
        {
            CertificateLoadException certLoadEx(__FILE__, __LINE__);

            certLoadEx.message = "unable to load certificate from '";
            certLoadEx.message += publicFile;
            certLoadEx.message += "'\n";
            certLoadEx.message += sslGetErrors();

            throw certLoadEx;
        }

        if(privateKey.getFileName().empty())
        {
            if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
            { 
                Trace out(_logger, _traceLevels->securityCat);
                out << "WRN no private key specified -- using the certificate";
            }

            privKeyFile = publicFile;
            privKeyFileType = publicEncoding;
        }

        int retryCount = 0;
        int pkLoadResult;
        int errCode = 0;

        while(retryCount != _maxPassphraseTries)
        {
            // We ignore the errors and remove them from the stack.
            string errorString = sslGetErrors();

            // Set which Private Key file to use.
            pkLoadResult = SSL_CTX_use_PrivateKey_file(_sslContext, privKeyFile, privKeyFileType);

            if(pkLoadResult <= 0)
            {
                errCode = ERR_GET_REASON(ERR_peek_error());
            }
            else
            {
                // The load went fine - continue on.
                break;
            }

            // PEM errors, most likely related to a bad passphrase.
            if(errCode != PEM_R_BAD_PASSWORD_READ &&
                errCode != PEM_R_BAD_DECRYPT &&
                errCode != PEM_R_BAD_BASE64_DECODE)
            {
                // Other errors get dealt with below.
                break;
            }

            cout << "Passphrase error!" << endl;

            retryCount++;
        }

        if(pkLoadResult <= 0)
        {
            int errCode = ERR_GET_REASON(ERR_peek_error());

            // Note: Because OpenSSL currently (V0.9.6b) performs a check to see if the
            //       key matches the private key when calling SSL_CTX_use_PrivateKey_file().
            if(errCode == X509_R_KEY_VALUES_MISMATCH || errCode == X509_R_KEY_TYPE_MISMATCH)
            {
                CertificateKeyMatchException certKeyMatchEx(__FILE__, __LINE__);

                certKeyMatchEx.message = "private key does not match the certificate public key";
                string sslError = sslGetErrors();

                if(!sslError.empty())
                {
                    certKeyMatchEx.message += "\n";
                    certKeyMatchEx.message += sslError;
                }

                throw certKeyMatchEx;
            }
            else
            {
                PrivateKeyLoadException pklEx(__FILE__, __LINE__);

                pklEx.message = "unable to load private key from '";
                pklEx.message += privKeyFile;
                pklEx.message += "'\n";
                pklEx.message += sslGetErrors();

	        throw pklEx;
            }
        }

        checkKeyCert();
    }
}

void
IceSSL::Context::addKeyCert(const RSAKeyPair& keyPair)
{
    if(_sslContext == 0)
    {
        ContextNotConfiguredException contextConfigEx(__FILE__, __LINE__);

        contextConfigEx.message = "ssl context not configured";

        throw contextConfigEx;
    }

    // Note: Normally I would use an X509Janitor and RSAJanitor to ensure that
    //       memory was being freed properly when exceptions are thrown, but
    //       both SSL_CTX_use_certificate and SSL_CTX_use_RSAPrivateKey free
    //       certificate/key memory regardless if the call succeeded.

    // Set which Public Key file to use.
    if(SSL_CTX_use_certificate(_sslContext, keyPair.getX509PublicKey()) <= 0)
    {
        CertificateLoadException certLoadEx(__FILE__, __LINE__);

        certLoadEx.message = "unable to set certificate from memory";
        string sslError = sslGetErrors();

        if(!sslError.empty())
        {
            certLoadEx.message += "\n";
            certLoadEx.message += sslError;
        }

        throw certLoadEx;
    }

    // Set which Private Key file to use.
    if(SSL_CTX_use_RSAPrivateKey(_sslContext, keyPair.getRSAPrivateKey()) <= 0)
    {
        int errCode = ERR_GET_REASON(ERR_peek_error());

        // Note: Because OpenSSL currently (V0.9.6b) performs a check to see if the
        //       key matches the private key when calling SSL_CTX_use_PrivateKey_file().
        if(errCode == X509_R_KEY_VALUES_MISMATCH || errCode == X509_R_KEY_TYPE_MISMATCH)
        {
            CertificateKeyMatchException certKeyMatchEx(__FILE__, __LINE__);

            certKeyMatchEx.message = "private key does not match the certificate public key";
            string sslError = sslGetErrors();

            if(!sslError.empty())
            {
                certKeyMatchEx.message += "\n";
                certKeyMatchEx.message += sslError;
            }

            throw certKeyMatchEx;
        }
        else
        {
            PrivateKeyLoadException pklEx(__FILE__, __LINE__);

            pklEx.message = "unable to set private key from memory";
            string sslError = sslGetErrors();

            if(!sslError.empty())
            {
                pklEx.message += "\n";
                pklEx.message += sslError;
            }

            throw pklEx;
        }
    }

    checkKeyCert();
}

void
IceSSL::Context::addKeyCert(const Ice::ByteSeq& privateKey, const Ice::ByteSeq& publicKey)
{
    Ice::ByteSeq privKey = privateKey;

    if(privKey.empty())
    {
        if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
        { 
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN no private key specified -- using the certificate";
        }

        privKey = publicKey;
    }

    // Make a key pair based on the DER encoded byte sequences.
    addKeyCert(RSAKeyPair(privKey, publicKey));
}

void
IceSSL::Context::addKeyCert(const string& privateKey, const string& publicKey)
{
    string privKey = privateKey;

    if(privKey.empty())
    {
        if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
        { 
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN no private key specified -- using the certificate";
        }

        privKey = publicKey;
    }

    // Make a key pair based on the Base64 encoded strings.
    addKeyCert(RSAKeyPair(privKey, publicKey));
}

SSL*
IceSSL::Context::createSSLConnection(int socket)
{
    assert(_sslContext != 0);

    SSL* sslConnection = SSL_new(_sslContext);
    assert(sslConnection != 0);

    SSL_clear(sslConnection);

    SSL_set_fd(sslConnection, socket);

    return sslConnection;
}

void
IceSSL::Context::transceiverSetup(const SslTransceiverPtr& transceiver)
{
    // Set the Post-Handshake Read timeout
    // This timeout is implemented once on the first read after hanshake.
    int handshakeReadTimeout = _properties->getPropertyAsIntWithDefault(_handshakeTimeoutProperty, 5000);
    transceiver->setHandshakeReadTimeout(handshakeReadTimeout);
}

void
IceSSL::Context::setCipherList(const string& cipherList)
{
    assert(_sslContext != 0);

    if(!cipherList.empty() && (!SSL_CTX_set_cipher_list(_sslContext, cipherList.c_str())) &&
        (_traceLevels->security >= IceSSL::SECURITY_WARNINGS))
    {
        Trace out(_logger, _traceLevels->securityCat);
        out << "WRN error setting cipher list " << cipherList << " -- using default list" << "\n";
        out << sslGetErrors();
    }
}

void
IceSSL::Context::setDHParams(const BaseCertificates& baseCerts)
{
    DH* dh = 0;

    string dhFile = baseCerts.getDHParams().getFileName();
    int encoding = baseCerts.getDHParams().getEncoding();

    // File type must be PEM - that's the only way we can load DH Params, apparently.
    if((!dhFile.empty()) && (encoding == SSL_FILETYPE_PEM))
    {
        dh = loadDHParam(dhFile.c_str());
    }

    if(dh == 0)
    {
        if(_traceLevels->security >= IceSSL::SECURITY_WARNINGS)
        { 
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN Could not load Diffie-Hellman params, generating a temporary 512bit key.";
        }

        dh = getTempDH512();
    }

    if(dh != 0)
    {
        SSL_CTX_set_tmp_dh(_sslContext, dh);

        DH_free(dh);
    }
}