summaryrefslogtreecommitdiff
path: root/cpp/src/IceSSL/Instance.cpp
blob: 03bb4010062d9a0aa5ca9c462cb62e93d3c3ae35 (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
// **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IceSSL/Instance.h>
#include <IceSSL/EndpointI.h>
#include <IceSSL/Util.h>
#include <IceSSL/TrustManager.h>

#include <Ice/Communicator.h>
#include <Ice/LocalException.h>
#include <Ice/Logger.h>
#include <Ice/LoggerUtil.h>
#include <Ice/Properties.h>
#include <Ice/ProtocolPluginFacade.h>

#include <IceUtil/Mutex.h>
#include <IceUtil/MutexPtrLock.h>
#include <IceUtil/StringUtil.h>

#include <openssl/rand.h>
#include <openssl/err.h>

#include <IceUtil/DisableWarnings.h>

using namespace std;
using namespace Ice;
using namespace IceSSL;

IceUtil::Shared* IceInternal::upCast(IceSSL::Instance* p) { return p; }

namespace
{

IceUtil::Mutex* staticMutex = 0;
int instanceCount = 0;
IceUtil::Mutex* locks = 0;

class Init
{
public:

    Init()
    {
        staticMutex = new IceUtil::Mutex;
    }

    ~Init()
    {
        delete staticMutex;
        staticMutex = 0;

        if(locks)
        {
            delete[] locks;
            locks = 0;
        }
    }
};

Init init;

}

extern "C"
{

//
// OpenSSL mutex callback.
//
void
IceSSL_opensslLockCallback(int mode, int n, const char* file, int line)
{
    assert(locks);
    if(mode & CRYPTO_LOCK)
    {
        locks[n].lock();
    }
    else
    {
        locks[n].unlock();
    }
}

//
// OpenSSL thread id callback.
//
unsigned long
IceSSL_opensslThreadIdCallback()
{
#if defined(_WIN32)
    return static_cast<unsigned long>(GetCurrentThreadId());
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(__osf1__)
    //
    // On some platforms, pthread_t is a pointer to a per-thread structure.
    //
    return reinterpret_cast<unsigned long>(pthread_self());
#elif (defined(__linux) || defined(__sun) || defined(__hpux)) || defined(_AIX)
    //
    // On Linux, Solaris, HP-UX and AIX, pthread_t is an integer.
    //
    return static_cast<unsigned long>(pthread_self());
#else
#   error "Unknown platform"
#endif
}

int
IceSSL_opensslPasswordCallback(char* buf, int size, int flag, void* userData)
{
    IceSSL::Instance* p = reinterpret_cast<IceSSL::Instance*>(userData);
    string passwd = p->password(flag == 1);
    int sz = static_cast<int>(passwd.size());
    if(sz > size)
    {
        sz = size - 1;
    }
    strncpy(buf, passwd.c_str(), sz);
    buf[sz] = '\0';

    memset(&passwd[0], 0, static_cast<size_t>(passwd.size()));

    return sz;
}

#ifndef OPENSSL_NO_DH
DH*
IceSSL_opensslDHCallback(SSL* ssl, int /*isExport*/, int keyLength)
{
    IceSSL::Instance* p = reinterpret_cast<IceSSL::Instance*>(SSL_CTX_get_ex_data(ssl->ctx, 0));
    return p->dhParams(keyLength);
}
#endif

int
IceSSL_opensslVerifyCallback(int ok, X509_STORE_CTX* ctx)
{
    SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
    IceSSL::Instance* p = reinterpret_cast<IceSSL::Instance*>(SSL_CTX_get_ex_data(ssl->ctx, 0));
    return p->verifyCallback(ok, ssl, ctx);
}

}

static bool
passwordError()
{
    int reason = ERR_GET_REASON(ERR_peek_error());
    return (reason == PEM_R_BAD_BASE64_DECODE ||
            reason == PEM_R_BAD_DECRYPT ||
            reason == PEM_R_BAD_PASSWORD_READ ||
            reason == PEM_R_PROBLEMS_GETTING_PASSWORD);
}

IceSSL::Instance::Instance(const CommunicatorPtr& communicator) :
    _logger(communicator->getLogger()),
    _initialized(false),
    _ctx(0)
{
    __setNoDelete(true);

    //
    // Initialize OpenSSL if necessary.
    //
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> sync(staticMutex);
    instanceCount++;

    if(instanceCount == 1)
    {
        PropertiesPtr properties = communicator->getProperties();

        //
        // Create the mutexes and set the callbacks.
        //
        if(!locks)
        {
            locks = new IceUtil::Mutex[CRYPTO_num_locks()];
            CRYPTO_set_locking_callback(IceSSL_opensslLockCallback);
            CRYPTO_set_id_callback(IceSSL_opensslThreadIdCallback);
        }

        //
        // Load human-readable error messages.
        //
        SSL_load_error_strings();

        //
        // Initialize the SSL library.
        //
        SSL_library_init();

        //
        // Initialize the PRNG.
        //
#ifdef WINDOWS
        RAND_screen(); // Uses data from the screen if possible.
#endif
        char randFile[1024];
        if(RAND_file_name(randFile, sizeof(randFile))) // Gets the name of a default seed file.
        {
            RAND_load_file(randFile, 1024);
        }
        string randFiles = properties->getProperty("IceSSL.Random");
        if(!randFiles.empty())
        {
            vector<string> files;
#ifdef _WIN32
            const string sep = ";";
#else
            const string sep = ":";
#endif
            string defaultDir = properties->getProperty("IceSSL.DefaultDir");
            if(!IceUtilInternal::splitString(randFiles, sep, files))
            {
                PluginInitializationException ex(__FILE__, __LINE__);
                ex.reason = "IceSSL: invalid value for IceSSL.Random:\n" + randFiles;
                throw ex;
            }
            for(vector<string>::iterator p = files.begin(); p != files.end(); ++p)
            {
                string file = *p;
                if(!checkPath(file, defaultDir, false))
                {
                    PluginInitializationException ex(__FILE__, __LINE__);
                    ex.reason = "IceSSL: entropy data file not found:\n" + file;
                    throw ex;
                }
                if(!RAND_load_file(file.c_str(), 1024))
                {
                    PluginInitializationException ex(__FILE__, __LINE__);
                    ex.reason = "IceSSL: unable to load entropy data from " + file;
                    throw ex;
                }
            }
        }
#ifndef _WIN32
        //
        // The Entropy Gathering Daemon (EGD) is not available on Windows.
        // The file should be a Unix domain socket for the daemon.
        //
        string entropyDaemon = properties->getProperty("IceSSL.EntropyDaemon");
        if(!entropyDaemon.empty())
        {
            if(RAND_egd(entropyDaemon.c_str()) <= 0)
            {
                PluginInitializationException ex(__FILE__, __LINE__);
                ex.reason = "IceSSL: EGD failure using file " + entropyDaemon;
                throw ex;
            }
        }
#endif
        if(!RAND_status())
        {
            communicator->getLogger()->warning("IceSSL: insufficient data to initialize PRNG");
        }
    }

    _facade = IceInternal::getProtocolPluginFacade(communicator);
    _securityTraceLevel = communicator->getProperties()->getPropertyAsInt("IceSSL.Trace.Security");
    _securityTraceCategory = "Security";
    _trustManager = new TrustManager(communicator);
    
    //
    // Register the endpoint factory. We have to do this now, rather than
    // in initialize, because the communicator may need to interpret
    // proxies before the plug-in is fully initialized.
    //
    _facade->addEndpointFactory(new EndpointFactoryI(this));

    __setNoDelete(false);
}

IceSSL::Instance::~Instance()
{
    //
    // Clean up OpenSSL resources.
    //
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> sync(staticMutex);

    if(--instanceCount == 0)
    {
        //
        // NOTE: We can't destroy the locks here: threads wich might have called openssl methods
        // might access openssl locks upon termination (from DllMain/THREAD_DETACHED). Instead, 
        // we release the locks in the ~Init() static destructor. See bug #4156.
        //
        //CRYPTO_set_locking_callback(0);
        //CRYPTO_set_id_callback(0);
        //delete[] locks;
        //locks = 0;

        CRYPTO_cleanup_all_ex_data();
        RAND_cleanup();
        ERR_free_strings();
        EVP_cleanup();
    }
}

void
IceSSL::Instance::initialize()
{
    if(_initialized)
    {
        return;
    }

    try
    {
        const string propPrefix = "IceSSL.";
        PropertiesPtr properties = communicator()->getProperties();

        //
        // CheckCertName determines whether we compare the name in a peer's
        // certificate against its hostname.
        //
        _checkCertName = properties->getPropertyAsIntWithDefault(propPrefix + "CheckCertName", 0) > 0;

        //
        // VerifyDepthMax establishes the maximum length of a peer's certificate
        // chain, including the peer's certificate. A value of 0 means there is
        // no maximum.
        //
        _verifyDepthMax = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyDepthMax", 2);

        //
        // VerifyPeer determines whether certificate validation failures abort a connection.
        //
        _verifyPeer = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyPeer", 2);

        //
        // Create an SSL context if the application hasn't supplied one.
        //
        if(!_ctx)
        {
            _ctx = SSL_CTX_new(SSLv23_method());
            if(!_ctx)
            {
                PluginInitializationException ex(__FILE__, __LINE__);
                ex.reason = "IceSSL: unable to create SSL context:\n" + sslErrors();
                throw ex;
            }

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            string defaultDir = properties->getProperty(propPrefix + "DefaultDir");

            //
            // If the configuration defines a password, or the application has supplied
            // a password prompt object, then register a password callback. Otherwise,
            // let OpenSSL use its default behavior.
            //
            {
                // TODO: Support quoted value?
                string password = properties->getProperty(propPrefix + "Password");
                if(!password.empty() || _prompt)
                {
                    SSL_CTX_set_default_passwd_cb(_ctx, IceSSL_opensslPasswordCallback);
                    SSL_CTX_set_default_passwd_cb_userdata(_ctx, this);
                    _password = password;
                }
            }

            int passwordRetryMax = properties->getPropertyAsIntWithDefault(propPrefix + "PasswordRetryMax", 3);

            //
            // Establish the location of CA certificates.
            //
            {
                string caFile = properties->getProperty(propPrefix + "CertAuthFile");
                string caDir = properties->getPropertyWithDefault(propPrefix + "CertAuthDir", defaultDir);
                const char* file = 0;
                const char* dir = 0;
                if(!caFile.empty())
                {
                    if(!checkPath(caFile, defaultDir, false))
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: CA certificate file not found:\n" + caFile;
                        throw ex;
                    }
                    file = caFile.c_str();
                }
                if(!caDir.empty())
                {
                    if(!checkPath(caDir, defaultDir, true))
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: CA certificate directory not found:\n" + caDir;
                        throw ex;
                    }
                    dir = caDir.c_str();
                }
                if(file || dir)
                {
                    //
                    // The certificate may be stored in an encrypted file, so handle
                    // password retries.
                    //
                    int count = 0;
                    int err = 0;
                    while(count < passwordRetryMax)
                    {
                        ERR_clear_error();
                        err = SSL_CTX_load_verify_locations(_ctx, file, dir);
                        if(err)
                        {
                            break;
                        }
                        ++count;
                    }
                    if(err == 0)
                    {
                        string msg = "IceSSL: unable to establish CA certificates";
                        if(passwordError())
                        {
                            msg += ":\ninvalid password";
                        }
                        else
                        {
                            string err = sslErrors();
                            if(!err.empty())
                            {
                                msg += ":\n" + err;
                            }
                        }
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = msg;
                        throw ex;
                    }
                }
            }

            //
            // Establish the certificate chains and private keys. One RSA certificate and
            // one DSA certificate are allowed.
            //
            {
#ifdef _WIN32
                const string sep = ";";
#else
                const string sep = ":";
#endif
                string certFile = properties->getProperty(propPrefix + "CertFile");
                string keyFile = properties->getProperty(propPrefix + "KeyFile");
                vector<string>::size_type numCerts = 0;
                if(!certFile.empty())
                {
                    vector<string> files;
                    if(!IceUtilInternal::splitString(certFile, sep, files) || files.size() > 2)
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: invalid value for " + propPrefix + "CertFile:\n" + certFile;
                        throw ex;
                    }
                    numCerts = files.size();
                    for(vector<string>::iterator p = files.begin(); p != files.end(); ++p)
                    {
                        string file = *p;
                        if(!checkPath(file, defaultDir, false))
                        {
                            PluginInitializationException ex(__FILE__, __LINE__);
                            ex.reason = "IceSSL: certificate file not found:\n" + file;
                            throw ex;
                        }
                        //
                        // The certificate may be stored in an encrypted file, so handle
                        // password retries.
                        //
                        int count = 0;
                        int err = 0;
                        while(count < passwordRetryMax)
                        {
                            ERR_clear_error();
                            err = SSL_CTX_use_certificate_chain_file(_ctx, file.c_str());
                            if(err)
                            {
                                break;
                            }
                            ++count;
                        }
                        if(err == 0)
                        {
                            string msg = "IceSSL: unable to load certificate chain from file " + file;
                            if(passwordError())
                            {
                                msg += ":\ninvalid password";
                            }
                            else
                            {
                                string err = sslErrors();
                                if(!err.empty())
                                {
                                    msg += ":\n" + err;
                                }
                            }
                            PluginInitializationException ex(__FILE__, __LINE__);
                            ex.reason = msg;
                            throw ex;
                        }
                    }
                }
                if(keyFile.empty())
                {
                    keyFile = certFile; // Assume the certificate file also contains the private key.
                }
                if(!keyFile.empty())
                {
                    vector<string> files;
                    if(!IceUtilInternal::splitString(keyFile, sep, files) || files.size() > 2)
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: invalid value for " + propPrefix + "KeyFile:\n" + keyFile;
                        throw ex;
                    }
                    if(files.size() != numCerts)
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: " + propPrefix + "KeyFile does not agree with " + propPrefix + "CertFile";
                        throw ex;
                    }
                    for(vector<string>::iterator p = files.begin(); p != files.end(); ++p)
                    {
                        string file = *p;
                        if(!checkPath(file, defaultDir, false))
                        {
                            PluginInitializationException ex(__FILE__, __LINE__);
                            ex.reason = "IceSSL: key file not found:\n" + file;
                            throw ex;
                        }
                        //
                        // The private key may be stored in an encrypted file, so handle
                        // password retries.
                        //
                        int count = 0;
                        int err = 0;
                        while(count < passwordRetryMax)
                        {
                            ERR_clear_error();
                            err = SSL_CTX_use_PrivateKey_file(_ctx, file.c_str(), SSL_FILETYPE_PEM);
                            if(err)
                            {
                                break;
                            }
                            ++count;
                        }
                        if(err == 0)
                        {
                            string msg = "IceSSL: unable to load private key from file " + file;
                            if(passwordError())
                            {
                                msg += ":\ninvalid password";
                            }
                            else
                            {
                                string err = sslErrors();
                                if(!err.empty())
                                {
                                    msg += ":\n" + err;
                                }
                            }
                            PluginInitializationException ex(__FILE__, __LINE__);
                            ex.reason = msg;
                            throw ex;
                        }
                    }
                    if(!SSL_CTX_check_private_key(_ctx))
                    {
                        PluginInitializationException ex(__FILE__, __LINE__);
                        ex.reason = "IceSSL: unable to validate private key(s):\n" + sslErrors();
                        throw ex;
                    }
                }
            }

            //
            // Diffie Hellman configuration.
            //
            {
#ifndef OPENSSL_NO_DH
                _dhParams = new DHParams;
                SSL_CTX_set_options(_ctx, SSL_OP_SINGLE_DH_USE);
                SSL_CTX_set_tmp_dh_callback(_ctx, IceSSL_opensslDHCallback);
#endif
                //
                // Properties have the following form:
                //
                // ...DH.<keyLength>=file
                //
                const string dhPrefix = propPrefix + "DH.";
                PropertyDict d = properties->getPropertiesForPrefix(dhPrefix);
                if(!d.empty())
                {
#ifdef OPENSSL_NO_DH
                    _logger->warning("IceSSL: OpenSSL is not configured for Diffie Hellman");
#else
                    for(PropertyDict::iterator p = d.begin(); p != d.end(); ++p)
                    {
                        string s = p->first.substr(dhPrefix.size());
                        int keyLength = atoi(s.c_str());
                        if(keyLength > 0)
                        {
                            string file = p->second;
                            if(!checkPath(file, defaultDir, false))
                            {
                                PluginInitializationException ex(__FILE__, __LINE__);
                                ex.reason = "IceSSL: DH parameter file not found:\n" + file;
                                throw ex;
                            }
                            if(!_dhParams->add(keyLength, file))
                            {
                                PluginInitializationException ex(__FILE__, __LINE__);
                                ex.reason = "IceSSL: unable to read DH parameter file " + file;
                                throw ex;
                            }
                        }
                    }
#endif
                }
            }
        }

        //
        // Store a pointer to ourself for use in OpenSSL callbacks.
        //
        SSL_CTX_set_ex_data(_ctx, 0, this);

        //
        // This is necessary for successful interop with Java. Without it, a Java
        // client would fail to reestablish a connection: the server gets the
        // error "session id context uninitialized" and the client receives
        // "SSLHandshakeException: Remote host closed connection during handshake".
        //
        SSL_CTX_set_session_cache_mode(_ctx, SSL_SESS_CACHE_OFF);

        //
        // Select protocols.
        //
        StringSeq protocols = properties->getPropertyAsList(propPrefix + "Protocols");
        if(!protocols.empty())
        {
            parseProtocols(protocols);
        }

        //
        // Establish the cipher list.
        //
        string ciphers = properties->getProperty(propPrefix + "Ciphers");
        if(!ciphers.empty())
        {
            if(!SSL_CTX_set_cipher_list(_ctx, ciphers.c_str()))
            {
                PluginInitializationException ex(__FILE__, __LINE__);
                ex.reason = "IceSSL: unable to set ciphers using `" + ciphers + "':\n" + sslErrors();
                throw ex;
            }
        }

        //
        // Determine whether a certificate is required from the peer.
        //
        {
            int sslVerifyMode;
            switch(_verifyPeer)
            {
            case 0:
                sslVerifyMode = SSL_VERIFY_NONE;
                break;
            case 1:
                sslVerifyMode = SSL_VERIFY_PEER;
                break;
            case 2:
                sslVerifyMode = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
                break;
            default:
            {
                PluginInitializationException ex(__FILE__, __LINE__);
                ex.reason = "IceSSL: invalid value for " + propPrefix + "VerifyPeer";
                throw ex;
            }
            }
            SSL_CTX_set_verify(_ctx, sslVerifyMode, IceSSL_opensslVerifyCallback);
        }
    }
    catch(...)
    {
        //
        // We free the SSL context regardless of whether the plugin created it
        // or the application supplied it.
        //
        SSL_CTX_free(_ctx);
        _ctx = 0;
        throw;
    }

    _initialized = true;
}

void
IceSSL::Instance::context(SSL_CTX* context)
{
    if(_initialized)
    {
        PluginInitializationException ex(__FILE__, __LINE__);
        ex.reason = "IceSSL: plug-in is already initialized";
        throw ex;
    }

    assert(!_ctx);
    _ctx = context;
}

SSL_CTX*
IceSSL::Instance::context() const
{
    return _ctx;
}

void
IceSSL::Instance::setCertificateVerifier(const CertificateVerifierPtr& verifier)
{
    _verifier = verifier;
}

void
IceSSL::Instance::setPasswordPrompt(const PasswordPromptPtr& prompt)
{
    _prompt = prompt;
}

CommunicatorPtr
IceSSL::Instance::communicator() const
{
    return _facade->getCommunicator();
}

IceInternal::EndpointHostResolverPtr
IceSSL::Instance::endpointHostResolver() const
{
    return _facade->getEndpointHostResolver();
}

IceInternal::ProtocolSupport
IceSSL::Instance::protocolSupport() const
{
    return _facade->getProtocolSupport();
}

string
IceSSL::Instance::defaultHost() const
{
    return _facade->getDefaultHost();
}

int
IceSSL::Instance::networkTraceLevel() const
{
    return _facade->getNetworkTraceLevel();
}

string
IceSSL::Instance::networkTraceCategory() const
{
    return _facade->getNetworkTraceCategory();
}

int
IceSSL::Instance::securityTraceLevel() const
{
    return _securityTraceLevel;
}

string
IceSSL::Instance::securityTraceCategory() const
{
    return _securityTraceCategory;
}

void
IceSSL::Instance::verifyPeer(SSL* ssl, SOCKET fd, const string& address, const string& adapterName, bool incoming)
{
    long result = SSL_get_verify_result(ssl);
    if(result != X509_V_OK)
    {
        if(_verifyPeer == 0)
        {
            if(_securityTraceLevel >= 1)
            {
                ostringstream ostr;
                ostr << "IceSSL: ignoring certificate verification failure:\n" << X509_verify_cert_error_string(result);
                _logger->trace(_securityTraceCategory, ostr.str());
            }
        }
        else
        {
            ostringstream ostr;
            ostr << "IceSSL: certificate verification failed:\n" << X509_verify_cert_error_string(result);
            string msg = ostr.str();
            if(_securityTraceLevel >= 1)
            {
                _logger->trace(_securityTraceCategory, msg);
            }
            SecurityException ex(__FILE__, __LINE__);
            ex.reason = msg;
            throw ex;
        }
    }

    X509* rawCert = SSL_get_peer_certificate(ssl);
    CertificatePtr cert;
    if(rawCert != 0)
    {
        cert = new Certificate(rawCert);
    }

    //
    // For an outgoing connection, we compare the proxy address (if any) against
    // fields in the server's certificate (if any).
    //
    if(cert && !address.empty())
    {
        //
        // Extract the IP addresses and the DNS names from the subject
        // alternative names.
        //
        vector<pair<int, string> > subjectAltNames = cert->getSubjectAlternativeNames();
        vector<string> ipAddresses;
        vector<string> dnsNames;
        for(vector<pair<int, string> >::const_iterator p = subjectAltNames.begin(); p != subjectAltNames.end(); ++p)
        {
            if(p->first == 7)
            {
                ipAddresses.push_back(IceUtilInternal::toLower(p->second));
            }
            else if(p->first == 2)
            {
                dnsNames.push_back(IceUtilInternal::toLower(p->second));
            }
        }

        //
        // Compare the peer's address against the common name.
        //
        bool certNameOK = false;
        string dn;
        string addrLower = IceUtilInternal::toLower(address);
        {
            DistinguishedName d = cert->getSubjectDN();
            dn = IceUtilInternal::toLower(string(d));
            string cn = "cn=" + addrLower;
            string::size_type pos = dn.find(cn);
            if(pos != string::npos)
            {
                //
                // Ensure we match the entire common name.
                //
                certNameOK = (pos + cn.size() == dn.size()) || (dn[pos + cn.size()] == ',');
            }
        }

        //
        // Compare the peer's address against the the dnsName and ipAddress
        // values in the subject alternative name.
        //
        if(!certNameOK)
        {
            certNameOK = find(ipAddresses.begin(), ipAddresses.end(), addrLower) != ipAddresses.end();
        }
        if(!certNameOK)
        {
            certNameOK = find(dnsNames.begin(), dnsNames.end(), addrLower) != dnsNames.end();
        }

        //
        // Log a message if the name comparison fails. If CheckCertName is defined,
        // we also raise an exception to abort the connection. Don't log a message if
        // CheckCertName is not defined and a verifier is present.
        //
        if(!certNameOK && (_checkCertName || (_securityTraceLevel >= 1 && !_verifier)))
        {
            ostringstream ostr;
            ostr << "IceSSL: ";
            if(!_checkCertName)
            {
                ostr << "ignoring ";
            }
            ostr << "certificate validation failure:\npeer certificate does not have `" << address
                 << "' as its commonName or in its subjectAltName extension";
            if(!dn.empty())
            {
                ostr << "\nSubject DN: " << dn;
            }
            if(!dnsNames.empty())
            {
                ostr << "\nDNS names found in certificate: ";
                for(vector<string>::const_iterator p = dnsNames.begin(); p != dnsNames.end(); ++p)
                {
                    if(p != dnsNames.begin())
                    {
                        ostr << ", ";
                    }
                    ostr << *p;
                }
            }
            if(!ipAddresses.empty())
            {
                ostr << "\nIP addresses found in certificate: ";
                for(vector<string>::const_iterator p = ipAddresses.begin(); p != ipAddresses.end(); ++p)
                {
                    if(p != ipAddresses.begin())
                    {
                        ostr << ", ";
                    }
                    ostr << *p;
                }
            }
            string msg = ostr.str();
            if(_securityTraceLevel >= 1)
            {
                Trace out(_logger, _securityTraceCategory);
                out << msg;
            }
            if(_checkCertName)
            {
                SecurityException ex(__FILE__, __LINE__);
                ex.reason = msg;
                throw ex;
            }
        }
    }

    ConnectionInfo info = populateConnectionInfo(ssl, fd, adapterName, incoming);

    if(_verifyDepthMax > 0 && static_cast<int>(info.certs.size()) > _verifyDepthMax)
    {
        ostringstream ostr;
        ostr << (incoming ? "incoming" : "outgoing") << " connection rejected:\n"
             << "length of peer's certificate chain (" << info.certs.size() << ") exceeds maximum of "
             << _verifyDepthMax;
        string msg = ostr.str();
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + IceInternal::fdToString(fd));
        }
        SecurityException ex(__FILE__, __LINE__);
        ex.reason = msg;
        throw ex;
    }

    if(!_trustManager->verify(info))
    {
        string msg = string(incoming ? "incoming" : "outgoing") + " connection rejected by trust manager";
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + IceInternal::fdToString(fd));
        }
        SecurityException ex(__FILE__, __LINE__);
        ex.reason = msg;
        throw ex;
    }

    if(_verifier && !_verifier->verify(info))
    {
        string msg = string(incoming ? "incoming" : "outgoing") + " connection rejected by certificate verifier";
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + IceInternal::fdToString(fd));
        }
        SecurityException ex(__FILE__, __LINE__);
        ex.reason = msg;
        throw ex;
    }
}

string
IceSSL::Instance::sslErrors() const
{
    return getSslErrors(_securityTraceLevel >= 1);
}

void
IceSSL::Instance::destroy()
{
    _facade = 0;

    if(_ctx)
    {
        SSL_CTX_free(_ctx);
    }
}

string
IceSSL::Instance::password(bool /*encrypting*/)
{
    if(_prompt)
    {
        try
        {
            return _prompt->getPassword();
        }
        catch(...)
        {
            //
            // Don't allow exceptions to cross an OpenSSL boundary.
            //
            return string();
        }
    }
    else
    {
        return _password;
    }
}

int
IceSSL::Instance::verifyCallback(int ok, SSL* ssl, X509_STORE_CTX* c)
{
    if(!ok && _securityTraceLevel >= 1)
    {
        X509* cert = X509_STORE_CTX_get_current_cert(c);
        int err = X509_STORE_CTX_get_error(c);
        char buf[256];

        Trace out(_logger, _securityTraceCategory);
        out << "certificate verification failure\n";

        X509_NAME_oneline(X509_get_issuer_name(cert), buf, static_cast<int>(sizeof(buf)));
        out << "issuer = " << buf << '\n';
        X509_NAME_oneline(X509_get_subject_name(cert), buf, static_cast<int>(sizeof(buf)));
        out << "subject = " << buf << '\n';
        out << "depth = " << X509_STORE_CTX_get_error_depth(c) << '\n';
        out << "error = " << X509_verify_cert_error_string(err) << '\n';
        out << IceInternal::fdToString(SSL_get_fd(ssl));
    }
    return ok;
}

#ifndef OPENSSL_NO_DH
DH*
IceSSL::Instance::dhParams(int keyLength)
{
    return _dhParams->get(keyLength);
}
#endif

void
IceSSL::Instance::traceConnection(SSL* ssl, bool incoming)
{
    Trace out(_logger, _securityTraceCategory);
    out << "SSL summary for " << (incoming ? "incoming" : "outgoing") << " connection\n";
    SSL_CIPHER* cipher = SSL_get_current_cipher(ssl);
    if(!cipher)
    {
        out << "unknown cipher\n";
    }
    else
    {
        out << "cipher = " << SSL_CIPHER_get_name(cipher) << "\n";
        out << "bits = " << SSL_CIPHER_get_bits(cipher, 0) << "\n";
        out << "protocol = " << SSL_get_version(ssl) << "\n";
    }
    out << IceInternal::fdToString(SSL_get_fd(ssl));
}

void
IceSSL::Instance::parseProtocols(const StringSeq& protocols)
{
    bool sslv3 = false, tlsv1 = false;
    for(Ice::StringSeq::const_iterator p = protocols.begin(); p != protocols.end(); ++p)
    {
        string prot = *p;

        if(prot == "ssl3" || prot == "sslv3")
        {
            sslv3 = true;
        }
        else if(prot == "tls" || prot == "tls1" || prot == "tlsv1")
        {
            tlsv1 = true;
        }
        else
        {
            PluginInitializationException ex(__FILE__, __LINE__);
            ex.reason = "IceSSL: unrecognized protocol `" + prot + "'";
            throw ex;
        }
    }

    long opts = SSL_OP_NO_SSLv2; // SSLv2 is not supported.
    if(!sslv3)
    {
        opts |= SSL_OP_NO_SSLv3;
    }
    if(!tlsv1)
    {
        opts |= SSL_OP_NO_TLSv1;
    }
    SSL_CTX_set_options(_ctx, opts);
}